简体   繁体   中英

Open PDF in a WebView

I want to open a PDF in my WebView, and I found and combined codes on this forum.

But it catches the "No PDF application found" although I have multiple PDF apps installed, including Adobe Reader.

Here the code:

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;
        }   } }

(1) Google Docs Viewer, You can open it in android Browser like,

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

Update:

(2) Check this library , in build.gradle (app module) add this dependency,

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

I know, this question is old.

But I really like the approach of Xamarin to make use of the pdf.js from Mozilla. It works on older Android versions, you don't need a special PDF Viewer app for this and you can easily display a PDF inside of your apps views hierarchy.

Git for this: https://mozilla.github.io/pdf.js/

Additional options: https://github.com/mozilla/pdf.js/wiki/Viewer-options

Just add the pdfjs files to your Assets directory:

在此处输入图片说明

And call it the following way:

// 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());

Cool thing: If you want to reduce the amount of functionalities / controls. Go to the Assets/pdfjs/web/viewer.html file and mark certain controls as hidden. With

style="display: none;"

Eg If you don't like the right toolbar:

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

Update: This will open built-in app (PDF Viewer) to display pdf file if OS >= Marshmallow (API 23), otherwise will open the browser to display pdf using "docs.google.com" server.

WebView webView = new WebView(this);

    String url = "http://www.pdf995.com/samples/pdf.pdf"; 

    // Support all types of OS versions.
    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M)
        webView.loadUrl(url); // This will open it with a built-in PDF viewer app.
    else
        webView.loadUrl("http://docs.google.com/viewerng/viewer?url="+ url); // This will open it with a browser. On Android 5.0 (Api 21 - Lollipop) and bellow.

    // Set Download listener.
    webView.setDownloadListener((url1, userAgent, contentDisposition, mimetype, contentLength)
            -> startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url1))));

you can try this. it works for both .pdf and .docx

 String pdfUrl = "https://www.abcd.com/assets/uploads/profilepics/abc.pdf"; //your pdf url
 String url = "http://docs.google.com/gview?embedded=true&url=" + pdfUrl;

 WebView webView = findViewById(R.id.webview_cv_viewer);
 webView.getSettings().setSupportZoom(true);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.loadUrl(url);

If you are trying to view a PDF that has a URL, and you are not accessing content that requires authentication, your best option is:

val webPage = Uri.parse(customizedUrl) //This is optional, based on how your URL is provided
val intent = Intent(Intent.ACTION_VIEW, webPage)
startActivity(intent)

The browser delegate opening the document to a PDF viewer on the device.

The old url is not working use this new url

mWebView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url="+ webUrl);

I think this has a limit , so better way is to directly launch an intent to a pdf viewer app , if there is no app to launch pdf then use a webview.

这对我有用

webView.loadUrl("https://docs.google.com/viewer?url=" + "url of your pdf"); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM