I want to open local (SD card) PDF file in a WebView.
I already tried this:
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().set
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 default options (like standard zoom): 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() + "#zoom=page-width");
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;"
E.g. If you don't like the right toolbar:
<div id="toolbarViewerRight" style="display: none;">...</div>
Update
'URL scheme "file" is not supported'
Might occur for newer versions of pdfjs. With version 1.8.188
this error does not appear.