加载pdf

这里主要加载网络pdf,经过了不小的挫折,pdfview只可加载本地文件,所以,需要进行下载,再展示

1.引入android_pdfview 和网络请求框架

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile 'com.joanzapata.pdfview:android-pdfview:1.0.4@aar

2.布局

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
<com.joanzapata.pdfview.PDFView
    android:id="@+id/pdf"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />
</LinearLayout> 
3.
package test.com.test;
import android.app.ProgressDialog;
import android.graphics.Canvas;

import android.os.Bundle;
import android.os.Environment;
import android.os.Looper;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.widget.Toast;

import com.joanzapata.pdfview.PDFView;
import com.joanzapata.pdfview.listener.OnDrawListener;
import com.joanzapata.pdfview.listener.OnLoadCompleteListener;
import com.joanzapata.pdfview.listener.OnPageChangeListener;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import okhttp3.Call;

public class Main2Activity extends AppCompatActivity {
    private PDFView pdf_view;
    private ProgressDialog mDialog;
    String url = "https://pic.bincrea.com/bc_bg_6D40C91A170D41C182511ABBB8A634A4.pdf";
    public static final String TAG = "Main2Activity";

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main2);
        pdf_view = findViewById(R.id.pdf);
        new Thread() {
            @Override
            public void run() {
                super.run();
                Looper.prepare();
                downFile();
                Looper.loop();
            }
        }.start();
    }

    private void downFile() {
        String urlString = "https://pic.bincrea.com/bc_bg_6D40C91A170D41C182511ABBB8A634A4.pdf";
        try {
            URL url = new URL(urlString);
            HttpURLConnection connection = (HttpURLConnection)
                    url.openConnection();
            connection.setRequestMethod("GET");
            connection.setDoInput(true);
            connection.setDoOutput(true);
            connection.setUseCaches(false);
            connection.setConnectTimeout(5000);
            connection.setReadTimeout(5000);
            //实现连接
            connection.connect();
            mDialog = new ProgressDialog(Main2Activity.this);
            mDialog.setMessage("正在加载...");
            mDialog.setCanceledOnTouchOutside(false);
            //如果文件下载过程中被取消的话,可能会导致打开的pdf文件出现缺少文字的bug,所以直接设置不能取消。。
            mDialog.setCancelable(false);
            mDialog.show();
            if (connection.getResponseCode() == 200) {
                InputStream is = connection.getInputStream();
                //以下为下载操作
                byte[] arr = new byte[1];
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedOutputStream bos = new BufferedOutputStream(baos);
                int n = is.read(arr);
                while (n > 0) {
                    bos.write(arr);
                    n = is.read(arr);
                }
                bos.close();
                String path = Environment.getExternalStorageDirectory()
                        + "/download/";
                String[] name = urlString.split("/");
                path = path + name[name.length - 1];
                File file = new File(path);
                FileOutputStream fos = new FileOutputStream(file);
                fos.write(baos.toByteArray());
                fos.close();
                //关闭网络连接
                connection.disconnect();
                Log.d("下载完成", "下载完成");
                setPdfView(file);//打开PDF文件
            }
        } catch (Exception e) {
            // TODO: handle exception
            System.out.println(e.getMessage());
        }
    }


    /**
     * 设置pdf属性
     *
     * @param file
     */
    private void setPdfView(File file) {
        pdf_view.setFitsSystemWindows(true);
        pdf_view.setFocusableInTouchMode(false);
        //home_pdfview.fromAsset(file).load();
        pdf_view.fromFile(file)
                .onLoad(new OnLoadCompleteListener() {
                    @Override
                    public void loadComplete(int nbPages) {
                        mDialog.dismiss();
                    }
                })
                //.swipeVertical(true)设置pdf文档垂直翻页,默认是左右滑动翻页
                .onDraw(new OnDrawListener() {
                    @Override
                    public void onLayerDrawn(Canvas canvas, float pageWidth, float pageHeight, int displayedPage) {
                        Log.e("monkey", "pageWidth -- " + pageWidth + " pageHeight -- " + pageHeight);
                    }
                })
                .onPageChange(new OnPageChangeListener() {
                    @Override
                    public void onPageChanged(int page, int pageCount) {
                        Toast.makeText(Main2Activity.this, "第" + page + "页/共" + pageCount + "页", Toast.LENGTH_SHORT).show();
                    }
                })
                .defaultPage(1)
                .swipeVertical(true)
                .showMinimap(true)//是否显示缩放小地图
                // 如果想要在正常状态下,双击放大,需要
                // (1).在PDFView.java中添加方法
                // public void zoomWithAnimation() {
                //     animationManager.startZoomAnimation(1f, 1.7f); //缩放比例可自己修改
                // }
                // (2).在DragPinchManager.java中改写方法
                // @Override
                // public void onDoubleTap(float x, float y) {
                //     if (isZooming()) { //放大状态
                //         pdfView.resetZoomWithAnimation(); //还原
                //     } else { //正常状态
                //         pdfView.zoomWithAnimation(); //放大
                //     }
                // }
                .load();
    }
}

猜你喜欢

转载自blog.csdn.net/TTHHVV/article/details/80644310
pdf
今日推荐