本文介绍了如何在WebView Android Studio中打开本地pdf文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道这个问题已经问了很多遍了,但是我仍然无法解决它.我在原始文件夹中有一个pdf文件,我正在尝试使用" https://drive.google.com/viewerng/viewer?embedded=true&url= "以在网络视图中将其打开.

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.

我认为我的问题是我无法获取pdf文件的正确路径.我用三种不同的方法尝试过,或者Webview提示我出错(URL不存在),或者它打开"了pdf,但是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/文件名"
  2. "android.resource://" + getPackageName()+"/" + R.raw.filename;
  3. Environment.getExternalStorageDirectory()+"/filename.pdf"

对于方法1和3,我尝试了"filename"和"filename.pdf"

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

所有这些都不允许将pdf加载到webview中.以下是我用来加载pdf的代码. (注意:如果我使用Web网址而不是本地文件,则此方法有效)

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

我做错了什么?有没有一种更好的方式可以在我的应用程序内部加载本地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?

推荐答案

那是不可能的.

最好的是根本不将其加载到您的应用程序中.通过ACTION_VIEW使用用户喜欢的PDF查看应用程序.

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

除此之外,您还可以在Android上使用 PDF.js 的稍作修改的版本4.4+.或者,在更广泛的Android版本上使用AndroidPdfViewer ,尽管它会使您的APK更大.请参阅此博客文章,以获取有关这些内容的更多信息,以及其他(更糟糕的)选项.

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:

  • PDF.js: https://github.com/commonsguy/cw-omnibus/tree/v8.10/PDF/PdfJS
  • AndroidPdfViewer: https://github.com/commonsguy/cw-omnibus/tree/v8.10/PDF/Pdfium

这篇关于如何在WebView Android Studio中打开本地pdf文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-29 21:12
查看更多