Android 如何本地載入pdf檔案

來源:互聯網
上載者:User

標籤:dism   exception   over   puts   對話方塊   als   common   sdcard   路徑   

大部分app開啟pdf檔案是通過intent調起手機中能開啟pdf檔案的工具,來查看pdf檔案,如果需求是,使用者在app內下載好pdf檔案後,不通過第三方的工具,本地開啟。

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

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

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

布局中引用PdfView

<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檔案,如果有直接開啟,沒有的話再去下載。

這裡我寫了一個載入中的對話方塊,開啟過程中和下載過程中用的都是這一個

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目錄中讀取

    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, //下載路徑);

 

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重新發送了一個訊息,

調用介面收到訊息後會重新調用refushUI();這個方法來開啟pdf檔案。

以上就是我對本地載入pdf檔案方法的總結,如果大家在使用的過程中有不理解或錯誤的地方,歡迎騷擾!

 

Android 如何本地載入pdf檔案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.