androidpdfandroid-intenttoastwebviewclient

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

Solution

  • (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'