2012-02-24 135 views
8

我想在我的WebView中打开PDF,并在此论坛上找到并合并代码。在WebView中打开PDF

但它捕捉到“找不到PDF应用程序”,尽管我安装了多个PDF应用程序,包括Adobe Reader。

下面的代码:

private class PsvWebViewClient extends WebViewClient { 
     @Override 
     public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      view.loadUrl(url); 

      if (url.contains(".pdf")) { 
       Uri path = Uri.parse(url); 
       Intent pdfIntent = new Intent(Intent.ACTION_VIEW); 
       pdfIntent.setDataAndType(path, "application/pdf"); 
       pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 

       try 
       { 
        startActivity(pdfIntent); 
       } 
       catch(ActivityNotFoundException e) 
       { 
        Toast.makeText(PsvWebViewActivity.this, "No PDF application found", Toast.LENGTH_SHORT).show(); 
       } 
       catch(Exception otherException) 
       { 
        Toast.makeText(PsvWebViewActivity.this, "Unknown error", Toast.LENGTH_SHORT).show(); 
       } 

      } 

      return true; 
     } } } 
+0

我觉得很奇怪,这是不行的,而且是唯一的答案是使用谷歌表示在WebView中它的时候,确实看起来很喜欢你想出手将PDF转发到另一个应用程序进行查看。 – BigOmega 2012-09-12 13:31:46

回答

28

你不能打开PDF直接在Android网络浏览器,但使用谷歌文档查看器,您可以在Android浏览器就像打开它......

mWebView.loadUrl("https://docs.google.com/gview?embedded=true&url="+ webUrl); 
+0

好的,这是有效的,它不工作,根据我尝试的方法不工作,我认为webview不太清楚 – 2012-02-24 19:20:29

+0

它的工作原理,但如果您更改您的** webUrl **文档,它需要时间来影响在谷歌文档。它显示旧文件。 – 2013-01-09 07:27:23

+5

它只打开有限数量的网址。之后,它会显示一条消息“您已达到最大带宽”。任何替代品? – 2013-04-16 14:40:23

5

我知道,这个问题很古老。

但我真的很喜欢Xamarin使用Mozilla的pdf.js的方法。它适用于较旧的Android版本,您不需要特殊的PDF查看器应用程序,您可以在应用程序视图层次结构中轻松显示PDF。

混帐此:https://mozilla.github.io/pdf.js/

附加选项:https://github.com/mozilla/pdf.js/wiki/Viewer-options

的pdfjs文件只需添加到您的资产目录:

enter image description here

,并调用它的方式如下:

// Assuming you got your pdf file: 
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf"); 

webview = (WebView) findViewById(R.id.webview); 
WebSettings settings = webview.getSettings(); 
settings.setJavaScriptEnabled(true); 
settings.setAllowFileAccessFromFileURLs(true); 
settings.setAllowUniversalAccessFromFileURLs(true); 
settings.setBuiltInZoomControls(true); 
webview.setWebChromeClient(new WebChromeClient()); 
webview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath()); 

很酷的事情:如果你想减少功能/控件的数量。转到Assets/pdfjs/web/viewer.html文件并将某些控件标记为隐藏。 With

style="display: none;" 

E.g.如果你不喜欢的权利工具栏:

<div id="toolbarViewerRight" style="display: none;">...</div>