Android 如何本地加載pdf文件

大部分app打開pdf文件是經過intent調起手機中能打開pdf文件的工具,來查看pdf文件,若是需求是,用戶在app內下載好pdf文件後,不經過第三方的工具,本地打開。android

這樣的需求要怎麼實現呢?上網查了一些資料,發現了一個很好用PDF開源庫。git

使用起來也很簡單,首先添加PDFView的引用github

compile 'com.github.barteksc:android-pdf-viewer:2.4.0'

佈局中引用PdfViewapp

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <include layout="@layout/common_title" />

    <com.github.barteksc.pdfviewer.PDFView
        android:id="@+id/pdf_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</LinearLayout>

接下來就是下載pdf文件,爲了節省用戶資源,在每次下載以前檢查一下本地是否有該pdf文件,若是有直接打開,沒有的話再去下載。ide

這裏我寫了一個加載中的對話框,打開過程當中和下載過程當中用的都是這一個工具

if (CheckFileExist(title)){
            builderShow = new CustomDialog(ShowPDFActivity.this);
            LayoutInflater inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            View view = inflater.inflate(R.layout.dialog_pdf_progress_new, null);
            builderShow.setContentView(view);
            builderShow.show();
            isDownload=false;
            refushUI();
        }else {
            isDownload=true;
            DownLoadPDF.getInstance().downLoadPDF(ShowPDFActivity.this, //下載路徑);

        }

若是本地有pdf文件,則開始加載pdf文件,refushUI();佈局

 

    public void refushUI(){
        try {
            pdfView.fromFile(new File(//pdf文件的絕對路徑,//標題))
                    .defaultPage(1)
                    .enableAnnotationRendering(false)
                    .onLoad(new OnLoadCompleteListener() {
                        @Override
                        public void loadComplete(int nbPages) {
                            if (isDownload){
                                DownLoadPDF.getInstance().closeDilaoig();
                            }
                            if (builderShow != null&&builderShow.isShowing()) {
                                builderShow.dismiss();
                            }
                        }
                    })
                    .scrollHandle(null)
                    .load();
        }catch (Exception e){
            e.printStackTrace();
        }
    }

 

PDFView加載pdf文件有兩種形式,一種是從文件中讀取,還有一種就是從assets目錄中讀取ui

    private void displayFromAssets(String assetFileName ) {
        pdfView.fromAsset(assetFileName)   //設置pdf文件地址
                .defaultPage(6)         //設置默認顯示第1頁
                .onPageChange(this)     //設置翻頁監聽
                .onLoad(this)           //設置加載監聽
                .onDraw(this)            //繪圖監聽
                .showMinimap(false)     //pdf放大的時候,是否在屏幕的右上角生成小地圖
                .swipeVertical( false )  //pdf文檔翻頁是不是垂直翻頁,默認是左右滑動翻頁
                .enableSwipe(true)   //是否容許翻頁,默認是容許翻頁
               // .pages( 2 , 3 , 4 , 5  )  //把2 , 3 , 4 , 5 過濾掉
                .load();
    }

    private void displayFromFile( File file ) {
        pdfView.fromFile(file)   //設置pdf文件地址
                .defaultPage(6)         //設置默認顯示第1頁
                .onPageChange(this)     //設置翻頁監聽
                .onLoad(this)           //設置加載監聽
                .onDraw(this)            //繪圖監聽
                .showMinimap(false)     //pdf放大的時候,是否在屏幕的右上角生成小地圖
                .swipeVertical( false )  //pdf文檔翻頁是不是垂直翻頁,默認是左右滑動翻頁
                .enableSwipe(true)   //是否容許翻頁,默認是容許翻
                // .pages( 2 , 3 , 4 , 5  )  //把2 , 3 , 4 , 5 過濾掉
                .load();
    }

本地沒有pdf文件,須要從服務端獲取, DownLoadPDF.getInstance().downLoadPDF(ShowPDFActivity.this, //下載路徑);this

 

public class DownLoadPDF {
    private static Context context;
    private static File file ;
    private static CustomDialog builder = null ;
    private static Handler ddhandle;
    private static DownLoadPDF instance = null;
    public static DownLoadPDF getInstance(){
        if(instance==null){
            synchronized (DownLoadPDF.class){
                if(instance==null){
                    instance = new DownLoadPDF();
                }
            }
        }
        return instance;
    }
    public void downLoadPDF(final Context con, final String url, final String title, final Handler ddhandler) {
        ddhandle = ddhandler;
        context = con;
        builder = new CustomDialog(con);
        LayoutInflater inflater = (LayoutInflater) con.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View view = inflater.inflate(R.layout.dialog_pdf_progress_new, null);
        builder.setContentView(view);
        builder.show();

        new Thread() {
            @Override
            public void run() {
                try {
                    file = getFileFromServer(url,title);
                    sleep(200);
                    if (file != null) {
                        handler.sendEmptyMessage(2);
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                    builder.dismiss();
                    handler.sendEmptyMessage(-1);
                }
            }
        }.start();
    }
    public void closeDilaoig(){
        if (builder != null&&builder.isShowing()) {
            builder.dismiss();
        }
    }public static int length ;
    public static File getFileFromServer(String path,String title)
            throws Exception {
        // 若是相等的話表示當前的sdcard掛載在手機上而且是可用的
        if (Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED)) {
            URL url = new URL(path);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setConnectTimeout(5000);
            conn.setDoInput(true);
            conn.connect();
            length = conn.getContentLength();
            InputStream is = conn.getInputStream();
            //將pdf文件存儲在指定文件夾下
            File filePath = new File(//指定文件夾路徑);
            if (!filePath.exists()){
                filePath.mkdir();
            }
            File file = new File(filePath , title+".pdf");
            FileOutputStream fos = new FileOutputStream(file);
            BufferedInputStream bis = new BufferedInputStream(is);
            byte[] buffer = new byte[1024];
            int len;
            while ((len = bis.read(buffer)) != -1) {
                fos.write(buffer, 0, len);
                handler.sendEmptyMessage(0);
            }
            fos.close();
            bis.close();
            is.close();
            return file;
        } else {
            handler.sendEmptyMessage(-1);
            return null;
        }
    }
    private static Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
            case 0:
                break;
            case -1:
                //下載失敗
                Toast.makeText(context, "下載失敗,請稍後再試!", Toast.LENGTH_SHORT).show();
                break;
            case 2:
                ddhandle.sendEmptyMessage(100);
                break;
            default:
                break;
            }
        }

    };
}

 

你們能夠看到,在pdf問價下載成功的時候handler.sendEmptyMessage(2);,當case爲2的時候,經過調用該工具類的頁面傳過來的ddhandle從新發送了一個消息,url

調用界面收到消息後會從新調用refushUI();這個方法來打開pdf文件。

以上就是我對本地加載pdf文件方法的總結,若是你們在使用的過程當中有不理解或錯誤的地方,歡迎騷擾!

相關文章
相關標籤/搜索