如何在Android的WebView中打开本地PDF文件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11613505/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to open local PDF file in WebView in Android?
提问by Girish Patel
I want to open local (SD card) PDF file in a WebView.
我想在 WebView 中打开本地(SD 卡)PDF 文件。
I already tried this:
我已经试过了:
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());
But it's still not opening it, so let me know how I can open a PDF in WebView?
但它仍然没有打开它,所以让我知道如何在 WebView 中打开 PDF?
回答by Lepidopteron
I know, this question is old.
我知道,这个问题很老了。
But I really like the approach of Xamarin to make use of the pdf.js from Mozilla. It works on older Android versions, you don't need a special PDF Viewer app for this and you can easily display a PDF insideof your apps views hierarchy.
但我真的很喜欢 Xamarin 使用 Mozilla 的 pdf.js 的方法。它适用于较旧的 Android 版本,您不需要特殊的 PDF 查看器应用程序,您可以轻松地在应用程序视图层次结构内显示 PDF 。
Git for this: https://mozilla.github.io/pdf.js/
Git:https: //mozilla.github.io/pdf.js/
Additional default options (like standard zoom): https://github.com/mozilla/pdf.js/wiki/Viewer-options
其他默认选项(如标准缩放):https: //github.com/mozilla/pdf.js/wiki/Viewer-options
Just add the pdfjs files to your Assets directory:
只需将 pdfjs 文件添加到您的资产目录:
And call it the following way:
并按以下方式调用它:
// 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");
Cool thing: If you want to reduce the amount of functionalities / controls. Go to the Assets/pdfjs/web/viewer.html file and mark certain controls as hidden. With
很酷的事情:如果你想减少功能/控件的数量。转到 Assets/pdfjs/web/viewer.html 文件并将某些控件标记为隐藏。和
style="display: none;"
E.g. If you don't like the right toolbar:
例如,如果您不喜欢正确的工具栏:
<div id="toolbarViewerRight" style="display: none;">...</div>
Update
更新
'URL scheme "file" is not supported'
'不支持 URL 方案“文件”'
Might occur for newer versions of pdfjs. With version 1.8.188
this error does not appear.
较新版本的 pdfjs 可能会发生。使用版本1.8.188
不会出现此错误。
回答by James Wong - Reinstate Monica
As @Sameer replied in your comment above, the only solution to view PDF in webview is through Google Docs' online viewer which will render and send back a readable version to your app.
正如@Sameer 在您上面的评论中所回复的那样,在 webview 中查看 PDF 的唯一解决方案是通过 Google Docs 的在线查看器,它将呈现并向您的应用发送一个可读版本。
Previously discussed here
以前在这里讨论过
回答by CSmith
You cannot. Using an Intent, you can open the PDF in an external viewer application like Acrobat Reader:
你不能。使用 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();
}
回答by pallav bohara
After going through several posts I came across thissimple answer on Quora which pretty much do the work. Following are steps:-
在浏览了几篇文章后,我在 Quora 上发现了这个简单的答案,它几乎可以完成工作。以下是步骤:-
Add this dependency in your gradle file:
在您的 gradle 文件中添加此依赖项:
compile 'com.github.barteksc:android-pdf-viewer:2.0.3'
activity_main.xml
活动_main.xml
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
MainActivity.java
主活动.java
package pdfviewer.pdfviewer;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import com.github.barteksc.pdfviewer.PDFView;
import com.github.barteksc.pdfviewer.listener.OnLoadCompleteListener;
import com.github.barteksc.pdfviewer.listener.OnPageChangeListener;
import com.github.barteksc.pdfviewer.scroll.DefaultScrollHandle;
import com.shockwave.pdfium.PdfDocument;
import java.util.List;
public class MainActivity extends Activity implements OnPageChangeListener,OnLoadCompleteListener{
private static final String TAG = MainActivity.class.getSimpleName();
public static final String SAMPLE_FILE = "sample_pdf.pdf";
PDFView pdfView;
Integer pageNumber = 0;
String pdfFileName;
@Override protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pdfView= (PDFView)findViewById(R.id.pdfView);
displayFromAsset(SAMPLE_FILE);
}
private void displayFromAsset(String assetFileName) {
pdfFileName = assetFileName;
pdfView.fromAsset(SAMPLE_FILE)
.defaultPage(pageNumber)
.enableSwipe(true)
.swipeHorizontal(false)
.onPageChange(this)
.enableAnnotationRendering(true)
.onLoad(this)
.scrollHandle(new DefaultScrollHandle(this))
.load();
}
@Override public void onPageChanged(int page, int pageCount) {
pageNumber = page;
setTitle(String.format("%s %s / %s", pdfFileName, page + 1, pageCount));
}
@Override public void loadComplete(int nbPages) {
PdfDocument.Meta meta = pdfView.getDocumentMeta();
printBookmarksTree(pdfView.getTableOfContents(), "-");
}
public void printBookmarksTree(List<PdfDocument.Bookmark> tree, String sep) {
for (PdfDocument.Bookmark b : tree) {
Log.e(TAG, String.format("%s %s, p %d", sep, b.getTitle(), b.getPageIdx()));
if (b.hasChildren()) {
printBookmarksTree(b.getChildren(), sep + "-");
}
}
}
}
You have to make sure that your asset folder contains sample_pdf.pdf (Library also support opening pdf from Uri and SDCard)
您必须确保您的资产文件夹包含 sample_pdf.pdf(库也支持从 Uri 和 SDCard 打开 pdf)
Happy coding :)
快乐编码:)
回答by Mightian
From android OS 5.0(lollipop) on-wardsyou can use PdfRenderer instead of webview/library.
You can use this class to show pdf's within the app.
从 android OS 5.0(棒棒糖)开始,您可以使用PdfRenderer instead of webview/library.
您可以使用此类在应用程序中显示 pdf。
If you want to support OS lower than that you can use a library/other approach mentioned in other answer as there is no native support.
如果您想支持低于该操作系统的操作系统,您可以使用其他答案中提到的库/其他方法,因为没有本机支持。
Read more about it from the docs, you can also refer this example
回答by Grecha
WebView can not open a .pdf file. The most popular solution (google docs' url + your url in WebView) just shows you converted by google docs pictures. However there is still no simple way to open .pdf from url.
WebView 无法打开 .pdf 文件。最流行的解决方案(google docs 的 url + WebView 中的 url)只显示由 google docs 图片转换的。但是仍然没有简单的方法可以从 url 打开 .pdf。