如何在Android中的WebView中打开本地PDF文件?

Gir*_*tel 16 pdf android webview

我想在WebView中打开本地(SD卡)PDF文件.

我已经尝试过了:

webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setPluginsEnabled(true);
webview.getSettings().setAllowFileAccess(true);
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

final Uri uri = Uri.fromFile(file);

webview.loadUrl(uri.toString());
Run Code Online (Sandbox Code Playgroud)

但它仍然没有打开它,所以让我知道如何在WebView中打开PDF?

Lep*_*ron 25

我知道,这个问题已经过时了.

但我真的很喜欢Xamarin使用Mozilla的pdf.js的方法.它适用于较旧的Android版本,您不需要特殊的PDF查看器应用程序,您可以轻松地应用程序视图层次结构中显示PDF .

Git for this:https: //mozilla.github.io/pdf.js/

其他默认选项(如标准缩放):https: //github.com/mozilla/pdf.js/wiki/Viewer-options

只需将pdfjs文件添加到Assets目录:

在此输入图像描述

并按以下方式调用它:

// Assuming you got your pdf file:
File file = new File(Environment.getExternalStorageDirectory() + "/test.pdf");

webview = (WebView) findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
settings.setAllowFileAccessFromFileURLs(true);
settings.setAllowUniversalAccessFromFileURLs(true);
settings.setBuiltInZoomControls(true);
webview.setWebChromeClient(new WebChromeClient());
webview.loadUrl("file:///android_asset/pdfjs/web/viewer.html?file=" + file.getAbsolutePath() + "#zoom=page-width");
Run Code Online (Sandbox Code Playgroud)

很酷的事情:如果你想减少功能/控制的数量.转到Assets/pdfjs/web/viewer.html文件并将某些控件标记为隐藏.同

style="display: none;"
Run Code Online (Sandbox Code Playgroud)

例如,如果您不喜欢正确的工具栏:

<div id="toolbarViewerRight" style="display: none;">...</div>
Run Code Online (Sandbox Code Playgroud)

  • Lepidopteron非常感谢,它效果很好.我有资产中的pdf,我将其复制到我的应用程序内的私人文件夹中并从那里打开 - 没有问题,没有权限混乱.使用最新的pdfjs 1.8.188 (2认同)

Jam*_*ica 5

正如@Sameer在上面的评论中回答的那样,在Webview中查看PDF的唯一解决方案是通过Google Docs的在线查看器,该查看器将呈现可读版本并将其发送回您的应用。

先前在这里讨论

  • 这对在您设备上本地放置的pdf有用吗? (2认同)

CSm*_*ith 2

你不能。使用 Intent,您可以在 Acrobat Reader 等外部查看器应用程序中打开 PDF:

try
{
 Intent intentUrl = new Intent(Intent.ACTION_VIEW);
 intentUrl.setDataAndType(uri, "application/pdf");
 intentUrl.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
 mActivity.startActivity(intentUrl);
}
catch (ActivityNotFoundException e)
{
 Toast.makeText(mActivity, "No PDF Viewer Installed", Toast.LENGTH_LONG).show();
}
Run Code Online (Sandbox Code Playgroud)