Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
491 views
in Technique[技术] by (71.8m points)

java - 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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:


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...