2012-02-24 131 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>