如何在Webview中显示pdf文档?

shr*_*iya 106 pdf android webview

我想在webview上显示pdf内容.这是我的代码:

WebView webview = new WebView(this); 
setContentView(webview);
webview.getSettings().setJavaScriptEnabled(true); 
webview.loadUrl("http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf");
Run Code Online (Sandbox Code Playgroud)

我得到一个空白的屏幕.我也设置了互联网许可.

ant*_*afe 157

您可以使用Google文档查看器在线阅读您的pdf:

WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true); 
String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
Run Code Online (Sandbox Code Playgroud)

  • 经过2天的持续测试后,我在Google文档中收到错误消息,说"您已经达到了查看或下载非Google Docs格式的文件的带宽限制.".所以似乎不可靠. (40认同)
  • 这个解决方案绝对可怕.很多人都认为在你的应用程序中添加这些丑陋的东西让我很担心.此页面专为桌面设计.该网站明显针对桌面进行了优化.在移动设备上使用它并不是一个好的移动体验. (23认同)
  • 如果您离线怎么办? (6认同)
  • 文档网址现在重定向到云端硬盘:"https://drive.google.com/viewerng/viewer?embedded=true&url=" (3认同)
  • 谷歌阅读器可靠吗?如果谷歌更改了URL? (2认同)
  • @LyteSpeed 想知道是什么让我们在应用程序中放置如此​​丑陋的解决方法?是的,你已经知道了;谷歌的大大脑Android团队 (2认同)

slo*_*ott 33

如果您使用仅查看网址,则不建议用户登录Google帐户.

https://docs.google.com/viewer?url=http://my.domain.com/yourPdfUrlHere.pdf
Run Code Online (Sandbox Code Playgroud)


JDe*_*ais 8

在用户体验方面,使用谷歌文档打开PDF是一个坏主意.它真的很慢而且没有反应.

API 21之后的解决方案

从api 21开始,我们有了PdfRenderer,它有助于将pdf转换为Bitmap.我从来没用过它,但看起来很容易.

任何API级别的解决方案

其他解决方案是下载PDF并通过Intent将其传递给专用的PDF应用程序,该应用程序将执行显示它的banger工作.快速和良好的用户体验,特别是如果此功能不是您的应用程序的核心.

使用此代码下载并打开PDF

public class PdfOpenHelper {

public static void openPdfFromUrl(final String pdfUrl, final Activity activity){
    Observable.fromCallable(new Callable<File>() {
        @Override
        public File call() throws Exception {
            try{
                URL url = new URL(pdfUrl);
                URLConnection connection = url.openConnection();
                connection.connect();

                // download the file
                InputStream input = new BufferedInputStream(connection.getInputStream());
                File dir = new File(activity.getFilesDir(), "/shared_pdf");
                dir.mkdir();
                File file = new File(dir, "temp.pdf");
                OutputStream output = new FileOutputStream(file);

                byte data[] = new byte[1024];
                long total = 0;
                int count;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    output.write(data, 0, count);
                }

                output.flush();
                output.close();
                input.close();
                return file;
            } catch (IOException e) {
                e.printStackTrace();
            }
            return null;
        }
    })
            .subscribeOn(Schedulers.io())
            .observeOn(AndroidSchedulers.mainThread())
            .subscribe(new Subscriber<File>() {
                @Override
                public void onCompleted() {

                }

                @Override
                public void onError(Throwable e) {

                }

                @Override
                public void onNext(File file) {
                    String authority = activity.getApplicationContext().getPackageName() + ".fileprovider";
                    Uri uriToFile = FileProvider.getUriForFile(activity, authority, file);

                    Intent shareIntent = new Intent(Intent.ACTION_VIEW);
                    shareIntent.setDataAndType(uriToFile, "application/pdf");
                    shareIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                    if (shareIntent.resolveActivity(activity.getPackageManager()) != null) {
                        activity.startActivity(shareIntent);
                    }
                }
            });
}
Run Code Online (Sandbox Code Playgroud)

}

要使Intent起作用,您需要创建一个FileProvider来授予接收应用程序打开文件的权限.

以下是您如何实现它:在您的清单中:

    <provider
        android:name="android.support.v4.content.FileProvider"
        android:authorities="${applicationId}.fileprovider"
        android:exported="false"
        android:grantUriPermissions="true">

        <meta-data
            android:name="android.support.FILE_PROVIDER_PATHS"
            android:resource="@xml/file_paths" />

    </provider>
Run Code Online (Sandbox Code Playgroud)

最后在资源foler中创建一个file_paths.xml文件

<?xml version="1.0" encoding="utf-8"?>
<paths>
    <files-path name="shared_pdf" path="shared_pdf"/>
</paths>
Run Code Online (Sandbox Code Playgroud)

希望这有助于=)


Pau*_*lgo 7

您可以使用 Mozilla pdf.js项目。基本上它会向您显示 PDF。看看他们的例子

我只在浏览器(桌面和移动设备)上使用它,并且运行良好。


Nav*_*r M 6

在这里加载progressDialog。需要提供WebClient,否则将强制在浏览器中打开:

final ProgressDialog pDialog = new ProgressDialog(context);
    pDialog.setTitle(context.getString(R.string.app_name));
    pDialog.setMessage("Loading...");
    pDialog.setIndeterminate(false);
    pDialog.setCancelable(false);
    WebView webView = (WebView) rootView.findViewById(R.id.web_view);
    webView.getSettings().setJavaScriptEnabled(true);
    webView.setWebViewClient(new WebViewClient() {
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            pDialog.show();
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            pDialog.dismiss();
        }
    });
    String pdf = "http://www.adobe.com/devnet/acrobat/pdfs/pdf_open_parameters.pdf";
    webView.loadUrl("https://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
Run Code Online (Sandbox Code Playgroud)


Ath*_*ira 6

使用此代码:

private void pdfOpen(String fileUrl){

        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setPluginState(WebSettings.PluginState.ON);

        //---you need this to prevent the webview from
        // launching another browser when a url
        // redirection occurs---
        webView.setWebViewClient(new Callback());

        webView.loadUrl(
                "http://docs.google.com/gview?embedded=true&url=" + fileUrl);

    }

    private class Callback extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(
                WebView view, String url) {
            return (false);
        }
    }
Run Code Online (Sandbox Code Playgroud)