Code To Open A Pdf File From Within Either The Assets Or Raw Folder When A Button Is Pressed
Solution 1:
was originally assets folder but an answer here said items in the assets folder get compressed and PDF files should go to the raw folder
That's not usually a problem.
From the other answers I've gathered that the file first needs to be copied to internal storage for it to be viewable.
That is the convention nowadays, assuming that by internal storage you mean what the Android SDK refers to as internal storage. You would then use FileProvider to make the PDF available to PDF viewer apps.
I have also saved a PDF file in each folder (assets and raw)
Use getAssets().open(...) on a Context (e.g., an Activity) to get an InputStream on the asset, where ... is the relative path within assets/ to the PDF. So, if your PDF is in assets/doc.pdf, pass "doc.pdf" to open().
Or, use getResources().openRawResource() on a Context to get an InputStream on your raw resource.
Copying the PDF to a local file is then a matter of:
Creating a
Fileobject on your desired location (e.g.,new File(getFilesDir(), "doc.pdf")Creating a
FileOutputStreamfor that fileCopying the bytes from the
InputStreamto theFileOutputStream, using standard Java file I/O
You can then configure FileProvider (or a subclass) to serve the PDF from wherever you saved it, generate the Uri, and craft the ACTION_VIEWIntent to open a PDF viewer.
Here is a complete sample app that demonstrates all of this, though I launch the PDF viewer as part of starting the activity, rather than on a button click.
Solution 2:
It is a little bit late but, this code piece's path is raw and you can only reach pdf files with this code.
I hope it helps some
privatefunopenPDFFile() {
val intent = Intent("android.intent.action.GET_CONTENT")
intent.type = "application/pdf"
startActivityForResult(intent, OPERATION_CHOOSE_PDF)
}
Post a Comment for "Code To Open A Pdf File From Within Either The Assets Or Raw Folder When A Button Is Pressed"