16

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;
        }   } }
prayagupa
  • 30,204
  • 14
  • 155
  • 192
TheLD
  • 2,211
  • 4
  • 21
  • 26
  • I find it strange that this doesn't work, and that the only answer was showing it in a WebView using google, when really it looked liked you wanted to hand the PDF off to another application to view. – MetaGuru Sep 12 '12 at 13:31

7 Answers7

43

(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'
Samir Mangroliya
  • 39,918
  • 16
  • 117
  • 134
15

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:

enter image description here

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

E.g. If you don't like the right toolbar:

<div id="toolbarViewerRight" style="display: none;">...</div>
Lepidopteron
  • 6,056
  • 5
  • 41
  • 53
  • 1
    Thanks a lot! I have to open pdf offline so Google doc is not an appropriate option. – Chandler Apr 24 '18 at 01:50
  • it is possible to read file from personal (internal app) folder? – mas_bejo Oct 05 '18 at 03:23
  • @mas_bejo Maybe this helps you out: https://stackoverflow.com/questions/11406084/read-internal-files-inside-a-particular-folder-in-android . But you might also want to open a new question on StackOverflow, concerning your question – Lepidopteron Oct 05 '18 at 06:45
  • could i place this pdfjs on the server and use serverside url to open pdf previews if I am online? It takes 12MB so as my app opens online pdfs it will be nice to save this 12MB of apk size – Michał Ziobro Nov 28 '18 at 09:57
  • what about CORS - cross origin resource sharing. I try to open file from network url – Michał Ziobro Nov 28 '18 at 10:15
  • @MichałZiobro This should be possible, but be aware of long loading times, as the user would have to load the pdf and the pdfjs. – Lepidopteron Nov 28 '18 at 15:29
  • @MichałZiobro please open a new question regarding this issue for more detailed explanation opportunities regarding your setup – Lepidopteron Nov 28 '18 at 15:30
  • I solved this issue in viewer.js there is array with such allowed origins "null", "mozilla", etc. I have added my domains and it works correctly. I will test this server-side and check load time is acceptable or if it is better to have bigger apk size (12MB is uncompressed, if i compress it it takes only about 5-6MB) – Michał Ziobro Nov 29 '18 at 08:53
  • but the asset directory is not extracted yet, am i right? Throught out the android that directory doesnt get unpacked.... @Lepidopteron – gumuruh Mar 13 '22 at 19:39
  • As of API Target 30, you will need to add settings.setAllowFileAccess(true); – Dizzy Dec 22 '22 at 11:52
4

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))));
2

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);
Dinesh Sarma
  • 461
  • 3
  • 14
1

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.

Shalbert
  • 1,044
  • 11
  • 17
0

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.

Manohar
  • 22,116
  • 9
  • 108
  • 144
-1

this work for me

webView.loadUrl("https://docs.google.com/viewer?url=" + "url of your pdf"); 
Maysam R
  • 915
  • 10
  • 12