【发布时间】:2021-05-01 23:52:10
【问题描述】:
我试图在 webview 中使用 url 显示 pdf 文件。虽然 webview 正在加载像 google.com 这样的网页,但当我尝试加载 pdf 的 url 时,它不会加载任何内容或抛出任何异常。
url在google chrome桌面浏览器中加载pdf,所以我猜问题不在于url本身。
这是我目前编写的代码:
onCreateView() 的 Fragment 加载 pdf
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_brochure, container, false);
webView = view.findViewById(R.id.webView);
// webView.loadUrl("https://google.com");
webView.loadUrl("https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf");
// webView.loadUrl(brochureUrl);
// Enable Javascript
WebSettings webSettings = webView.getSettings();
webSettings.setJavaScriptEnabled(true);
webSettings.setSupportZoom(true);
// Force links and redirects to open in the WebView instead of in a browser
webView.setWebViewClient(new WebViewClient());
return view;
}
布局(xml文件):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="@color/purple_500"
tools:context=".ui.project_details.project_details_pages.BrochureFragment">
<WebView
android:id="@+id/webView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="28dp"/>
</LinearLayout>
清单文件(仅我认为相关的部分)
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<application
android:allowBackup="true"
...
...
...
android:supportsRtl="true"
android:usesCleartextTraffic="true">
我想知道我错过了什么。另外,如果我能学习如何调试这类问题,那就太好了。
【问题讨论】:
-
WebView 无法显示 pdf 文档。
-
@blackapps,它可以。虽然我不确定显示机制是否与标准 pdf 查看器相同。
-
没有。这不可以。 WebView 用于 html 文档。答案中的示例不显示 pdf,但使用 html 作为 google pdf 到 html 转换器,如您在 url 上看到的那样。