How to open a PDF file from res/raw Folder?

我的未来我决定 提交于 2020-01-11 09:50:43

问题


I am writing an application that opens a pdf file when you click a button. Below is my code:

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);

However when I run it and press the button it says "The document cannot be opened because its is not a valid PDF document". This is driving me mad. Am I accessing the file correctly? Any ideas? Thanks


回答1:


You have to copy the pdf from assets folder to sdcard folder.

.....
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);
        }
    }



回答2:


You can insert your pdf in the folder assets in android and then try with:

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);

Edit: The URi from folder assets is: file:///android_asset/RELATIVE_PATH Then the source will be:

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);


来源:https://stackoverflow.com/questions/13517412/how-to-open-a-pdf-file-from-res-raw-folder

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!