Android 如何本地加载pdf文件

大部分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文件方法的总结,如果大家在使用的过程中有不理解或错误的地方,欢迎骚扰!

 

posted @ 2017-04-27 16:31  CurtisWgh  阅读(6369)  评论(0编辑  收藏  举报