简体   繁体   中英

How to open local pdf file in WebView Android Studio

I am aware that this question has been asked many times, but I still cannot get it to work. I have a pdf in the raw folder and I am trying to open it in a webview using " https://drive.google.com/viewerng/viewer?embedded=true&url= " to open it in the webview.

I think my problem is I can't get the correct path for the pdf file. I've tried it three different ways, and either the webview says I get an error (the url doesn't exist), or it "opens" the pdf, but the webview displays this text in the middle, "No preview available".

These are the three ways I've tried to get the path of the file.

  1. "android.resource://com.an.example/raw/filename"
  2. "android.resource://" + getPackageName() + "/" + R.raw.filename;
  3. Environment.getExternalStorageDirectory() + "/filename.pdf"

For methods 1 and 3 I have tried "filename" and "filename.pdf"

None of these are allowing the pdf to load in the webview. Below is the code I use to load the pdf. (Note: this method does work if I use a web url and not a local file)

    webview = (WebView) findViewById(R.id.webView);
    webview.getSettings().setJavaScriptEnabled(true);

    webview.getSettings().setBuiltInZoomControls(true);

    String pdf = "one_of_the_above_methods";
    webview.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);

What am I doing wrong? Is there a better way to load a local pdf inside my app without having it take up the entire activity page?

I have a pdf in the raw folder and I am trying to open it in a webview using " https://drive.google.com/viewerng/viewer?embedded=true&url= " to open it in the webview.

That has never been possible.

Is there a better way to load a local pdf inside my app without having it take up the entire activity page?

The best thing is to not load it inside your app at all. Use the user's preferred PDF viewing app, via ACTION_VIEW .

Beyond that, you could use a slightly modified version of PDF.js on Android 4.4+. Or, use AndroidPdfViewer on a wider range of Android versions, though it makes your APK a lot bigger. See this blog post for more context on these and other (worse) options.

Also, here are sample apps demonstrating:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM