【问题标题】:How to open PDF of any size in android?如何在android中打开任意大小的PDF?
【发布时间】:2019-11-13 19:50:59
【问题描述】:

我尝试使用嵌入式谷歌文档打开 PDF,如下所示:

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://docs.google.com/gview?embedded=true&url=https://aip.xyz.org/Accident.pdf"));
startActivity(browserIntent);

这可行,但不支持/打开大尺寸 pdf。然后从几个堆栈溢出建议中,我尝试使用如下意图选择器:

private void openPDF(int position) {
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(Uri.parse("https://aip.xyz.org/Accident.pdf"), "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
        Intent intent = Intent.createChooser(pdfIntent, "Open PDF using");
        try {
            startActivity(intent);
        } catch (ActivityNotFoundException e) {
            // Instruct the user to install a PDF reader here, or something
            Toast.makeText(context, "No Applications found to open pdf",Toast.LENGTH_SHORT).show();
        }
    }

但这也会引发错误“无法显示 pdf(无法打开 Pdf)”。我不明白这有什么问题。

【问题讨论】:

  • Android 没有嵌入式 PDF 查看 API。您可以搜索 PDF 库,或者我们的外部应用程序。

标签: android pdf


【解决方案1】:

选项 1:

您可以通过以下两种方式中的任何一种查看或下载 pdf,即在设备内置浏览器中打开它或通过将其嵌入到您的应用程序中的 web 视图中打开它。

要在浏览器中打开 pdf,

Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);

改为在 webview 中打开,

 Webview webView = (WebView) findViewById(R.id.webView1);
 webView.getSettings().setJavaScriptEnabled(true);
 webView.loadUrl(pdf_url);

选项 2:

您可以通过编程方式确定用户设备上是否存在合适的应用程序,而不会捕获异常。

Intent intent = new Intent(Intent.ACTION_VIEW,
        Uri.parse("path-to-document"));
intent.setType("application/pdf");
PackageManager pm = getPackageManager();
List<ResolveInfo> activities = pm.queryIntentActivities(intent, 0);
if (activities.size() > 0) {
    startActivity(intent);
} else {
    // Do something else here. Maybe pop up a Dialog or Toast
}

【讨论】:

  • 是的,但在选项 1 的情况下,有时 pdf 无法加载并抛出大尺寸无法加载的错误
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-05-15
  • 1970-01-01
  • 2020-06-01
  • 1970-01-01
  • 2015-03-08
  • 2018-11-21
  • 1970-01-01
相关资源
最近更新 更多