Reputation: 1
In the application I receive a PDF from an API call so it is inside a byte array and I would like to display it inside the application without having to save it in the user's phone. I have tried a WebView but it has not worked. Seems like a WebView will display a PDF from an url but will not render it if you give it the PDF as a string.
I was wondering if there was a way to display a PDF inside an android application without having to save it in the user's phone?
Upvotes: 0
Views: 146
Reputation: 3809
I am doing this by writing the received bytes of the pdf file to a temporary cache DIR and then open it with an intent. So for example in an async task I download the file in the doInBackground
method and do this in the onPostExecute
.
@Override
protected void onPostExecute(byte[] result) {
final File reportFile = new File(context.getExternalCacheDir(), "pdf-file.pdf");
final BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(reportFile));
output.write(result);
output.close();
Uri path = FileProvider.getUriForFile(getActivity(), BuildConfig.APPLICATION_ID + ".fileprovider", reportFile);
final Intent intent = new Intent(Intent.ACTION_VIEW);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setDataAndType(path, "application/pdf");
startActivity(intent);
}
This is working quite well. The only thing you have to do is to check if the user has a PDF reader installed that is working. The advantage I see with this solution is that you provide the user the opportunity to further do with the pdf what he or she wants (e.g. print, store, share, ...). If you just display it within a frame in your app you would quite limit the interaction possibilities (or would have to implement them all by your self).
Upvotes: 1