如何从res/raw文件夹打开PDF文件?

3
我正在编写一个应用程序,当您点击按钮时打开PDF文件。以下是我的代码:
File pdfFile = new File(
                        "android.resource://com.dave.pdfviewer/"
                                + R.raw.userguide);
                Uri path = Uri.fromFile(pdfFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setDataAndType(path, "application/pdf");

                startActivity(intent);

但是当我运行它并按下按钮时,它会说“文档无法打开,因为它不是有效的PDF文档”。这让我很疯狂。我是否正确地访问文件?有什么建议吗?谢谢。


在这里找到重复的问题:https://dev59.com/Hmw15IYBdhLWcg3wntOh - nu everest
2个回答

6

您需要将PDF文件从assets文件夹复制到sd卡文件夹中。

.....
copyFile(this.getAssets().open("userguide.pdf"), new FileOutputStream(new File(getFilesDir(), "yourPath/userguide.pdf")));

File pdfFile = new File(getFilesDir(), "yourPath/userguide.pdf"); Uri path = Uri.fromFile(pdfFile);
                    Intent intent = new Intent(Intent.ACTION_VIEW);
                    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                    intent.setDataAndType(path, "application/pdf");

                    startActivity(intent);


}

private void copyFile(InputStream in, OutputStream out) throws IOException {
        byte[] buffer = new byte[1024];
        int read;
        while((read = in.read(buffer)) != -1){
          out.write(buffer, 0, read);
        }
    }

一定要用 try catch 包围起来! - Alex K

-1

您可以将PDF文件插入到Android的assets文件夹中,然后尝试使用以下代码:

File pdfFile = new File(getAsset().open("userguide.pdf"));
                Uri path = Uri.fromFile(pdfFile);
                Intent intent = new Intent(Intent.ACTION_VIEW);
                intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
                intent.setDataAndType(path, "application/pdf");

                startActivity(intent);

编辑: 来自资产文件夹的URi是:file:///android_asset/RELATIVE_PATH 那么源代码将是:

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

                    startActivity(intent);

1
文件pdfFile = new File(getAsset().open("userguide.pdf");无法编译。它说构造函数File(InputStream)未定义。 - DMC
现在当我尝试打开它时,它显示文档路径无效! - DMC
1
你是否已将PDF文件插入到你的资源文件夹中?顺便说一下,这是不可能的,因为PDF文件位于你的沙盒内,只有你的应用程序才能访问此路径。 - Jc Miñarro
是的,它肯定在资产文件夹中! - DMC
我已经添加了另一个含有解决方案的答案。可能会有些错误,因为我是在 webBrowser 中编写的,我没有像 Eclipse 这样的 IDE 工具。但是通过这个你可以得到如何解决它的想法。 - Jc Miñarro
@JcMiñarro 即使您编辑过答案,它仍然无法正常工作。因为其他应用程序无法访问您的资产文件。 - Bharat Dodeja

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接