2012-05-09 138 views
2

我有這個webview代碼,我想讓用戶點擊PDF鏈接時可以打開PDF文件。這裏是代碼,你能告訴我我必須把這個內容放在PDF區嗎?我嘗試了很多不同的方式,並且無法看到PDF。謝謝您的幫助。Android - 在webview中加載PDF

try 
{ 
Intent intentUrl = new Intent(Intent.ACTION_VIEW); 
intentUrl.setDataAndType(url, "application/pdf"); 
intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
myActivity.startActivity(intentUrl); 
} 
catch (ActivityNotFoundException e) 
{ 
Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show(); 
} 

雖然我沒有嘗試過這個已經:作爲

webview.setWebViewClient (new WebViewClient() { 
    public boolean shouldOverrideUrlLoading(WebView view, String url) { 
     // do your handling codes here, which url is the requested url 
     // probably you need to open that url rather than redirect: 
     if (url.startsWith("tel:")) { 
      startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url))); 
     } else if (url.startsWith("mailto:")) { 
      url = url.replaceFirst("mailto:", ""); 
      url = url.trim(); 
      Intent i = new Intent(Intent.ACTION_SEND); 
      i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, 
        new String[]{url}); 
      startActivity(i); 

     } else if (url.startsWith("geo:")) { 
      try { 
      } catch (Exception e) { 
       System.out.println(e); 
      } 

     } else if (url.endsWith("pdf")) { 

      try { 

      } catch (Exception e) { 
       System.out.println(e); 
      } 

     } else { 
      view.loadUrl(url); 
     } 
     return true; 
     // then it is not handled by default action 
    } 
}); 

回答

10

這可能是那樣簡單。

在我們的應用程序中,我們將PDF下載到應用程序文件系統,使其具有世界可讀性,然後以Intent的形式傳遞路徑以打開PDF查看應用程序(例如Acrobat Reader)。請注意,您還需要關注清理這些下載的PDF!

在try塊

new DownloadPDFTask().execute(url); 

DownloadPDFTask類:

public class DownloadPDFTask extends AsyncTask<String, Void, Integer> 
{ 
    protected ProgressDialog mWorkingDialog; // progress dialog 
    protected String mFileName;   // downloaded file 
    protected String mError;   // for errors 

    @Override 
    protected Integer doInBackground(String... urls) 
    { 

    try 
    { 
     byte[] dataBuffer = new byte[4096]; 
      int nRead = 0; 

      // set local filename to last part of URL 
      String[] strURLParts = urls[0].split("/"); 
      if (strURLParts.length > 0) 
      mFileName = strURLParts[strURLParts.length - 1]; 
      else 
       mFileName = "REPORT.pdf"; 

      // download URL and store to strFileName 

      // connection to url 
     java.net.URL urlReport = new java.net.URL(urls[0]); 
      URLConnection urlConn = urlReport.openConnection(); 
      InputStream streamInput = urlConn.getInputStream(); 
      BufferedInputStream bufferedStreamInput = new BufferedInputStream(streamInput); 
      FileOutputStream outputStream = myActivity.openFileOutput(mFileName,Context.MODE_WORLD_READABLE); // must be world readable so external Intent can open! 
      while ((nRead = bufferedStreamInput.read(dataBuffer)) > 0) 
       outputStream.write(dataBuffer, 0, nRead); 
      streamInput.close(); 
      outputStream.close(); 
     } 
     catch (Exception e) 
     { 
     Log.e("myApp", e.getMessage()); 
     mError = e.getMessage(); 
     return (1); 
     } 

    return (0); 
    } 

    //------------------------------------------------------------------------- 
    // PreExecute - UI thread setup 
    //------------------------------------------------------------------------- 

    @Override 
    protected void onPreExecute() 
    { 
    // show "Downloading, Please Wait" dialog 
    mWorkingDialog = ProgressDialog.show(myActivity, "", "Downloading PDF Document, Please Wait...", true); 
    return; 
    } 

    //------------------------------------------------------------------------- 
    // PostExecute - UI thread finish 
    //------------------------------------------------------------------------- 

    @Override 
    protected void onPostExecute (Integer result) 
    { 
     if (mWorkingDialog != null) 
     { 
     mWorkingDialog.dismiss(); 
     mWorkingDialog = null; 
     } 

     switch (result) 
     { 
     case 0:       // a URL 

      // Intent to view download PDF 
      Uri uri = Uri.fromFile(myActivity.getFileStreamPath(mFileName)); 

      try 
      { 
       Intent intentUrl = new Intent(Intent.ACTION_VIEW); 
       intentUrl.setDataAndType(uri, "application/pdf"); 
       intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
       myActivity.startActivity(intentUrl); 
      } 
      catch (ActivityNotFoundException e) 
      { 
       Toast.makeText(myActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show(); 
      } 

      break; 

     case 1:       // Error 

      Toast.makeText(myActivity, mError, Toast.LENGTH_LONG).show(); 
      break; 

     } 

    } 

} 

任何提及 「myActivity」 必須與參考替換爲您的Activity類

+0

是否可以在不運行異步下載任務的情況下在webview上顯示PDF文件? – user1363871

+1

不,與iOS上的UIWebView不同,Android WebView不顯示PDF內容。你可以嘗試直接調用intent(即沒有AsyncDownloadTask),儘管無論如何你都會離開你的活動。 – CSmith

+0

嗯,所以在android中最好的方法是調用異步下載文件並保存。你知道這個過程是否可以自動找到文件名並保存爲SD卡上的名字?我在使用這個時總是指定了名字。謝謝! – user1363871

1

我試圖處理完全相同的情況。我提出的解決方案如下。

public boolean shouldOverrideUrlLoading(WebView view, String url) { 
      String cleanUrl = url; 
      if (url.contains("?")) { 
       // remove the query string 
       cleanUrl = url.substring(0,url.indexOf("?")); 
      } 

      if (cleanUrl.endsWith("pdf")) { 

       try { 
        Uri uriUrl = Uri.parse(cleanUrl); 
        Intent intentUrl = new Intent(Intent.ACTION_VIEW, uriUrl); 
        startActivity(intentUrl); 
        return true; 

       } catch (Exception e) { 
        System.out.println(e); 
        Toast.makeText(context,"No PDF Viewer Installed", Toast.LENGTH_LONG).show(); 
       } 
      } 

      return false; 
     } 

我需要確保它能處理pdf鏈接,即使有查詢字符串。 cleanUrl需要以「pdf」結尾仍然有點冒險,但只要這是真的,這應該起作用。如果您通過PHP腳本或其他東西來提供PDF,您可能需要深入一些,根據MIME類型或其他內容處理事情。

0

FWIW,mozilla擁有apache許可的PDF-reader-entirely-in-JavaScript。如果你不介意額外的尺寸,可能值得一看。這樣你就可以在瀏覽器中做所有的事情,而不必依靠第三方的PDF閱讀器。網頁視圖內

1

加載PDF:

WebView wv = (WebView) view.findViewById(R.id.webPage); 
      wv.getSettings().setJavaScriptEnabled(true); 
      wv.setWebViewClient(new WebClient()); 
      wv.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + mUrl); 
      wv.getSettings().setBuiltInZoomControls(true); 

mUrl - 將你的PDF鏈接

+0

很好的答案。 .. –

1

請結算處理重定向URL和打開的PDF沒有下載,在web視圖的例子。

private void init() 
{ 
    WebView webview = (WebView) findViewById(R.id.webview); 
    WebSettings settings = webview.getSettings(); 
    settings.setJavaScriptEnabled(true); 
    webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY); 

    PdfWebViewClient pdfWebViewClient = new PdfWebViewClient(this, webview); 
    pdfWebViewClient.loadPdfUrl(
       "https://www.google.co.in/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0ahUKEwjgwIfp3KXSAhXrhFQKHQqEDHYQFggZMAA&url=http%3A%2F%2Fwww.orimi.com%2Fpdf-test.pdf&usg=AFQjCNERYYcSfMLS5ukBcT2Qy11YxEhXqw&cad=rja"); 
} 

private class PdfWebViewClient extends WebViewClient 
{ 
    private static final String TAG = "PdfWebViewClient"; 
    private static final String PDF_EXTENSION = ".pdf"; 
    private static final String PDF_VIEWER_URL = "http://docs.google.com/gview?embedded=true&url="; 

    private Context mContext; 
    private WebView mWebView; 
    private ProgressDialog mProgressDialog; 
    private boolean isLoadingPdfUrl; 

    public PdfWebViewClient(Context context, WebView webView) 
    { 
     mContext = context; 
     mWebView = webView; 
     mWebView.setWebViewClient(this); 
    } 

    public void loadPdfUrl(String url) 
    { 
     mWebView.stopLoading(); 

     if (!TextUtils.isEmpty(url)) 
     { 
      isLoadingPdfUrl = isPdfUrl(url); 
      if (isLoadingPdfUrl) 
      { 
       mWebView.clearHistory(); 
      } 

      showProgressDialog(); 
     } 

     mWebView.loadUrl(url); 
    } 

    @SuppressWarnings("deprecation") 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView webView, String url) 
    { 
     return shouldOverrideUrlLoading(url); 
    } 

    @SuppressWarnings("deprecation") 
    @Override 
    public void onReceivedError(WebView webView, int errorCode, String description, String failingUrl) 
    { 
     handleError(errorCode, description.toString(), failingUrl); 
    } 

    @TargetApi(Build.VERSION_CODES.N) 
    @Override 
    public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request) 
    { 
     final Uri uri = request.getUrl(); 
     return shouldOverrideUrlLoading(webView, uri.toString()); 
    } 

    @TargetApi(Build.VERSION_CODES.N) 
    @Override 
    public void onReceivedError(final WebView webView, final WebResourceRequest request, final WebResourceError error) 
    { 
     final Uri uri = request.getUrl(); 
     handleError(error.getErrorCode(), error.getDescription().toString(), uri.toString()); 
    } 

    @Override 
    public void onPageFinished(final WebView view, final String url) 
    { 
     Log.i(TAG, "Finished loading. URL : " + url); 
     dismissProgressDialog(); 
    } 

    private boolean shouldOverrideUrlLoading(final String url) 
    { 
     Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url); 

     if (!isLoadingPdfUrl && isPdfUrl(url)) 
     { 
      mWebView.stopLoading(); 

      final String pdfUrl = PDF_VIEWER_URL + url; 

      new Handler().postDelayed(new Runnable() 
      { 
       @Override 
       public void run() 
       { 
        loadPdfUrl(pdfUrl); 
       } 
      }, 300); 

      return true; 
     } 

     return false; // Load url in the webView itself 
    } 

    private void handleError(final int errorCode, final String description, final String failingUrl) 
    { 
     Log.e(TAG, "Error : " + errorCode + ", " + description + " URL : " + failingUrl); 
    } 

    private void showProgressDialog() 
    { 
     dismissProgressDialog(); 
     mProgressDialog = ProgressDialog.show(mContext, "", "Loading..."); 
    } 

    private void dismissProgressDialog() 
    { 
     if (mProgressDialog != null && mProgressDialog.isShowing()) 
     { 
      mProgressDialog.dismiss(); 
      mProgressDialog = null; 
     } 
    } 

    private boolean isPdfUrl(String url) 
    { 
     if (!TextUtils.isEmpty(url)) 
     { 
      url = url.trim(); 
      int lastIndex = url.toLowerCase().lastIndexOf(PDF_EXTENSION); 
      if (lastIndex != -1) 
      { 
       return url.substring(lastIndex).equalsIgnoreCase(PDF_EXTENSION); 
      } 
     } 
     return false; 
    } 
}