如何打开存储在 res/raw 或 assets 文件夹中的 pdf? [英] How to open a pdf stored either in res/raw or assets folder?

查看:35
本文介绍了如何打开存储在 res/raw 或 assets 文件夹中的 pdf?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将在我的应用程序中显示一个 pdf,并且该 pdf 必须与应用程序捆绑在一起.

I'm going to show a pdf in my application, and the pdf has to be bundled with the application.

这样做的好方法是什么?

What is a good way to do this?

我已经读过,可以通过将 pdf 文件添加到 res/raw 文件夹并从那里读取来实现这一点,但是当我将 pdf 文件放在那里时,我遇到了项目错误.

I have read that it might be possible to do this by adding the pdf file to a res/raw folder and read it from there, but i get project errors when i put the pdf file there.

所以我尝试将 pdf 文件放在项目的资产文件夹中,但没有出错.

So i tried to put the pdf file in the asset folder of the project, and it gave no errors.

这就是我试图显示 pdf 的方式:

This is how i've tried to show the pdf:

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

有什么想法或建议吗?

提前致谢

推荐答案

如果您的应用程序实际上实现了一个PDF阅读器.由于您希望它在单独的应用程序(例如 Adob​​e Reader)中显示,我建议您执行以下操作:

You would be able to show it from raw/ or assets/ if your application actually implemented a PDF reader. Since you want it to be displayed in a separate application (such as Adobe Reader), I suggest doing the following:

  1. 将 PDF 文件存储在 assets/ 目录中.
  2. 当用户想要查看它时,将其复制到公开.查看 openFileOutputgetExternalFilesDir.
  3. 像现在一样启动 Intent,除了使用 getAbsolutePath() 在新创建的意图数据文件上.
  1. Store the PDF file in the assets/ directory.
  2. When the user wants to view it, copy it somewhere public. Look into openFileOutput or getExternalFilesDir.
  3. Launch the Intent just like you are doing now, except use getAbsolutePath() on the newly created file for the intent's data.

请注意,用户可能没有 PDF 阅读应用程序.在这种情况下,捕获 ActivityNotFoundException 并显示适当的消息.

Be aware that a user might not have a PDF reading application. In this case, it is useful to catch the ActivityNotFoundException and show an appropriate message.

这篇关于如何打开存储在 res/raw 或 assets 文件夹中的 pdf?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆