載入pdf

TTMMJJ99發表於2018-06-10

這裡主要載入網路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();
    }
}

相關文章