Display local PDF in Android WebView with Google Docs viewer

I’m trying to show a PDF file stored on my Android device using a WebView and Google Docs viewer. I know how to do this for online PDFs, but I’m stuck when it comes to local files.

Here’s what I’ve tried:

String devicePath = "file:///storage/emulated/0/MyFolder/document.pdf";
String viewerUrl = "https://docs.google.com/viewer?embedded=true&url=";

webView.loadUrl(viewerUrl + devicePath);

This doesn’t work. I’ve also tried encoding the path, but no luck.

Is it even possible to view local PDFs this way? If so, what am I doing wrong? I’d really appreciate any help or alternative solutions for displaying local PDFs in a WebView.

I’ve faced similar challenges with local PDFs in Android WebViews. From my experience, Google Docs viewer doesn’t work directly with local files. Instead, I’d recommend using a PDF library like AndroidPDF or PdfViewer.

What worked for me was using AndroidPDF. It’s straightforward to implement and handles local files well. You’ll need to add the dependency to your gradle file, then use something like:

PDFView pdfView = findViewById(R.id.pdfView);
pdfView.fromFile(new File("/storage/emulated/0/MyFolder/document.pdf"))
       .load();

This approach gives you more control over the PDF display and works smoothly with local files. Just make sure you have the necessary permissions to access the file location on the device. Hope this helps solve your issue!

While Google Docs viewer is great for online PDFs, it’s not designed for local files. A more reliable approach for your scenario would be to use a native PDF rendering solution.

I’ve had success with the PDF.js library in WebView. It’s open-source and works well with local files. Here’s a basic implementation:

  1. Download PDF.js and add it to your assets folder.
  2. Load PDF.js in your WebView.
  3. Use JavaScript to render the PDF.

Something like this in your WebView:

webView.loadUrl(“file:///android_asset/pdfjs/web/viewer.html?file=” + Uri.encode(pdfPath));

Make sure you have the correct file permissions. This method gives you a full-featured PDF viewer within your WebView, capable of handling local files efficiently.

have u tried using MuPDF? it’s pretty good for local PDFs in android. just add the library to ur project and use something like:

MuPDFCore core = new MuPDFCore(this, “/storage/emulated/0/MyFolder/document.pdf”);
mDocView.setAdapter(new MuPDFPageAdapter(this, core));

it’s fast and lightweight. might be worth a shot if other solutions didnt work for u.