如何在webview android中打开pdf文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23751717/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 07:23:54  来源:igfitidea点击:

How to open a pdf file in webview android?

android

提问by user2699728

I have generated a pdf using itext library and it gets stored in sdcard. I have to open the pdf in webview , but when I searched for the solution I came to know I can open it using online google doc service ,but my pdf is stored in a sdcard. Is there a way to open a pdf from external storage in a webview?

我使用 itext 库生成了一个 pdf 并将其存储在 sdcard 中。我必须在 webview 中打开 pdf,但是当我搜索解决方案时,我才知道我可以使用在线 google doc 服务打开它,但我的 pdf 存储在 sdcard 中。有没有办法在 webview 中从外部存储打开 pdf?

回答by Akash Moradiya

To open pdf in Webview , it better to show pdf via google doc service,

要在 Webview 中打开 pdf,最好通过 google doc 服务显示 pdf,

WebView webView = (WebView) context.findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf");

this may help you

这可能会帮助你

回答by DenisMath

No, you can`t use WebView to show a PDF file from a sdcard. Only HTML file maybe shown.

不,您不能使用 WebView 显示 SD 卡中的 PDF 文件。可能只显示 HTML 文件。

The most simple solution of this task is to use an external PDF reader. Such approach it is convenient for users enough because a "hand made" PDF reader you create from a github open source code can be slow for displaying large pdf files.

此任务最简单的解决方案是使用外部 PDF 阅读器。这种方法对用户来说足够方便,因为您从 github 开源代码创建的“手工制作”PDF 阅读器在显示大型 pdf 文件时可能会很慢。

public class PDFReader {
public void read(Activity context,  String fileName){
    File appFolder = new File( Environment.getExternalStorageDirectory(), 
        context.getBaseContext().getPackageName() );
    File file = new File(appFolder, fileName);

    Uri path = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(path, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {
        context.startActivity(intent);
    } 
    catch (ActivityNotFoundException e) {
        Toast.makeText(context, "На устройстве не найдено доступного приложения для отображения PDF!", 
            Toast.LENGTH_SHORT).show();
    }
}

}