android webview打开pdf文件

1.下载之后打开

思路如下:

if(本地没有该文件)
下载+打开
else打开

这段代码需要在WebViewClient的shouldOverrideUrlLoading进行拦截:

WebViewClient client = new WebViewClient() {
        /**
         * 防止加载网页时调起系统浏览器
         */
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            try {
                if(url.endsWith(".pdf")){
                    //进行下载等相关操作
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onReceivedHttpAuthRequest(WebView webview, com.tencent.smtt.export.external.interfaces.HttpAuthHandler httpAuthHandlerhost, String host, String realm) {
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {

        }

        @Override
        public void onPageFinished(WebView view, String url) {

        }
    };

    webview.setWebViewClient(client);

因为写的时候是已经封装过的,没办法展示,思路是这个思路,或者可以直接打开文件,系统会自动提示你下载,只不过下载位置就不一定了。。。所以也没办法在下载完打开。

打开系统下载

Intent intent = new Intent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("http:"), "application/pdf");
                    act.startActivity(intent);

自己下载后打开

Intent intent = new Intent();
                    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.fromFile(filename), "application/pdf");
                    act.startActivity(intent);

方法2.使用控件,在新的activity中打开(或者也可以在同一个界面,直接隐藏webview,不过这种情况需要处理返回键)

资源地址:https://github.com/barteksc/AndroidPdfViewer
当然,我写这种demo没有,所以也贴一下代码:
导入:

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

PdfActivity.java:

public class PdfActivity extends MyTitleActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_pdf);
        setTitleBarTitleText("文件内容");

        new AsyncTask<String, Void, InputStream>() {
            @Override
            protected InputStream doInBackground(String... strs) {
                URL url = null;
                try {
                    url = new URL(strs[0]);
                    HttpURLConnection connection = (HttpURLConnection)
                            url.openConnection();
                    connection.setRequestMethod("GET");//试过POST 可能报错
                    connection.setDoInput(true);
                    connection.setConnectTimeout(10000);
                    connection.setReadTimeout(10000);
                    //实现连接
                    connection.connect();

                    if (connection.getResponseCode() == 200) {
                        InputStream is = connection.getInputStream();
                        //这里给过去就行了
                        return is;
                    }
                } catch (MalformedURLException e) {
                    e.printStackTrace();
                } catch (ProtocolException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(InputStream inputStream) {
                super.onPostExecute(inputStream);
                PDFView pdfView = (PDFView) findViewById(R.id.pdfView);
                pdfView.fromStream(inputStream)
                        .enableSwipe(true)
                        .swipeHorizontal(false)
                        .enableDoubletap(true)
                        .defaultPage(0)
                        .onPageScroll(new OnPageScrollListener() {
                            @Override
                            public void onPageScrolled(int page, float positionOffset) {

                            }
                        })
                        .onError(new OnErrorListener() {
                            @Override
                            public void onError(Throwable t) {
                                Toast.makeText(getApplicationContext(), "error", Toast.LENGTH_SHORT).show();
                            }
                        })
                        .enableAnnotationRendering(false)
                        .password(null)
                        .scrollHandle(null)
                        .load();
            }
        }.execute(getIntent().getStringExtra("url"));

    }
}

这里需要前一个界面把url传进来:

intent.putExtra("url","xx");

xml:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:android="http://schemas.android.com/apk/res/android">
    <com.github.barteksc.pdfviewer.PDFView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/pdfView"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
</FrameLayout>

3.使用js进行加载

https://github.com/zhoukai1526/ReadPdf/blob/master/app/src/main/java/com/iwintrue/readpdf/MainActivity.java
具体就是这个网址下载的方式了,给的demo不是很好,换个pdf网址就不行了。
相应博客地址:https://blog.csdn.net/zach_zhou/article/details/55518367
不过确实也是一种思路,如果要用建议用pdfobject,官网在:https://pdfobject.com/

附录:使用js方式基本配置:

(1)webview配置

 WebSettings webSettings = mWebView.getSettings();

        // 设置与Js交互的权限
        webSettings.setJavaScriptEnabled(true);
        mWebView.addJavascriptInterface(new AndroidtoJs(), "test");

public class AndroidtoJs extends Object {
    // 定义JS需要调用的方法
    // 被JS调用的方法必须加入@JavascriptInterface注解
    @JavascriptInterface
    public void hello(String msg) {
        System.out.println("JS调用了Android的hello方法");
    }
}

(2)android调用js:
js方法(网页内):

function callJS(){
      alert("Android调用了JS的callJS方法");
   }

android调用:

mWebView.loadUrl("javascript:callJS()");

(3)js调用java
js方法:

function callAndroid(){
        // 由于对象映射,所以调用test对象等于调用Android映射的对象,此处和addJavascriptInterface最后一个字符串同名
            test.hello("js调用了android中的hello方法");
         }

如果确定用这种方式和公共网页交互也可以使用webviewjavasciptbridge,可以兼容苹果和android,当然如果是用于打开pdf是用不到的。

这里总结一下各种方法的优缺点:
1.下载打开
缺点需要下载到本地(需要一点时间,随着打开文件增多,会占用更多手机存储空间),手机必须有能打开pdf的软件,否则看不到。用户体验略差。
优点不会增加apk大小,不需要尽心额外配置。
2.apk内部打开
缺点占用大,大约要4.4M,相当于应用内部装了个pdf解析软件。
优点:不需要占用更多的手机存储空间,不需要进行文件下载,用户体验好,兼容性好。
3.用js交互方式
缺点:开发者必须要具备js交互的知识,因为是采用js控件的形式,可能会导致一定的兼容问题(这个没有经过测试,不知道兼容性如何),加载速度会比apk内部打开的速度要慢。
优点:既不会占用内存,也不会增大apk包大小(也会增大一个js文件一个html),如果显示没有问题,体验会非常好。

猜你喜欢

转载自blog.csdn.net/yu_duan_hun/article/details/80021785