Pdf in WebView Android

Anil kumar
1 min readOct 25, 2019

--

If there is a requirement to show pdf files in the android app using a third-party library will really increase the apk size.

There is one possible way of showing pdf files using WebView in Android Application which will not affect the apk size and the user can see the pdf file in-app.

Here we will be using google docs in the view to upload the pdf file.

private void showPdfFile(final String imageString) {
showProgress();
pdfView.invalidate();
pdfView.getSettings().setJavaScriptEnabled(true);
pdfView.getSettings().setSupportZoom(true);
pdfView.loadUrl("http://docs.google.com/gview?embedded=true&url=" + imageString);
pdfView.setWebViewClient(new WebViewClient() {
boolean checkOnPageStartedCalled = false;

@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
checkOnPageStartedCalled = true;
}

@Override
public void onPageFinished(WebView view, String url) {
if (checkOnPageStartedCalled) {
pdfView.loadUrl(removePdfTopIcon);
hideProgress();
} else {
showPdfFile(imageString);
}
}
});
}

The challenge here I faced was some times it shows a blank screen and was not able to upload the pdf file in the WebView but whenever the onPageStarted function was called the webview was able to upload the pdf file. So calling recursively onPageStarted function if it is not called worked for me and was able to get the pdf every time.

After this, I was able to show multiple pdf files in WebView without any problems in loading the pdf to the WebView.

Pros

  1. No third party lib that will increase the apk size

Cons

  1. Little slow scroll
  2. Dependant on google docs, Hopefully, that not be a problem ever.

You can refer to the GitHub page where I have uploaded this to get a clear picture

https://github.com/anilkumar416/PdfInWebView

--

--