Open and display pdf-file stored locally
-
31-05-2021 - |
Question
After reading through several Q/A, I still can't find a suitable answer for my current issue.
I have a pdf-file (known at compile time) which is stored in my /res/raw folder.
I have tried loading the file using:
InputStream is = getResources().openRawResource(R.raw.mypdf);
Then I want to display the pdf (in an intent) using the preferred pdf-reader on the device:
Intent i;
i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(file,"application/pdf");
startActivity(i);
The issue is that the intent takes in the type 'File', while my pdf is read as an 'InputStream'.
The question is: How can i display the pdf-file? i.e. how can I display an InputStream? or how can I store the pdf-file to allow opening with new File()?
Solution
TRY this..
//place pdf in asset folder just to try
Uri file= Uri.parse("file:///android_asset/mypdf.pdf");
String mimeType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(MimeTypeMap.getFileExtensionFromUrl(file.toString()));
try{
Intent i;
i = new Intent(Intent.ACTION_VIEW);
i.setDataAndType(file,mimeType);
startActivity(i);
}catch (ActivityNotFoundException e) {
Toast.makeText(this,
"No Application Available to fiew this file type",
Toast.LENGTH_SHORT).show();
}
OTHER TIPS
you could use an extern library joanzapata.pdfview
this code will show your pdf whereever u want in your layout
private PDFView pdfview;
pdfview = (PDFView) findViewById(R.id.pdfview);
File file = new File(filepath);
pdfview.fromFile(file)
.defaultPage(1)
.showMinimap(false)
.enableSwipe(true)
.onLoad(this)
.onPageChange(this)
.load();
or if the file is known at compile time and u have the pdf in the asset folder:
private PDFView pdfview;
pdfview = (PDFView) findViewById(R.id.pdfview);
pdfview.fromAsset(pdfName)
.defaultPage(1)
.showMinimap(false)
.enableSwipe(true)
.onLoad(this)
.onPageChange(this)
.load();
add this in your layout
<com.joanzapata.pdfview.PDFView
android:id="@+id/pdfview"
android:layout_width="match_parent"
android:layout_height="match_parent"/>