Android

Android WebView讀取PDF

1.在AndroidManifest聲明網路權限

<uses-permission android:name="android.permission.INTERNET" />

2.XML佈局中

<WebView
  android:id="@+id/webView"
  android:layout_width="0dp"
  android:layout_height="450dp"
  app:layout_constraintEnd_toEndOf="parent"
  app:layout_constraintStart_toStartOf="parent"
  app:layout_constraintTop_toTopOf="parent" />

3.設定WebView去讀取PDF(利用Google文件)

WebView webView = findViewById(R.id.webView);
String url = "https://udemy-certificate.s3.amazonaws.com/pdf/UC-V439BFCL.pdf";

webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setSupportZoom(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.getSettings().setDisplayZoomControls(false);
webView.loadUrl("https://docs.google.com/gview?embedded=true&url=" + url);

4.設置讀取中讓用戶知道檔案還在讀取

ProgressDialog mProgressDialog = new ProgressDialog(context);
mProgressDialog.setTitle("讀取我的PDF");
mProgressDialog.show();
webView.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        return true;
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
       super.onPageStarted(view, url, favicon);
   }
    @Override
    public void onPageFinished(WebView view, String url) {
        super.onPageFinished(view, url);
        mProgressDialog.hide();
    }
});

發表迴響