Open a pdf file that is stored in Firebase storage.
I have uploaded the pdf file to firebase storage, after uploading the pdf file to firebase storage, I get the download url. Now I want to open a pdf file from this download url in my application.
Below is the URL I get after uploading the pdf file to firebase repository.
Now I want to open intent to view this pdf file, I used the following code to do this:
String url = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa";
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
startActivity(Intent.createChooser(intent, "Choose an Application:"));
My phone has apps that can open this pdf file, but it says there are no apps to view this file.
If I convert this url to a file and use the code below, then the app selector opens, but it gives an error that the file cannot be opened.
Intent intent = new Intent(android.content.Intent.ACTION_VIEW);
File file = new File(name);
intent.setDataAndType(Uri.fromFile(file), "aplication/pdf");
I have seen many answers that say download the file first and then open it, but I don't want to download the file, I just want to view it.
Please help me if anyone thinks about it.
Thanks a lot for the advanced one.
source to share
You have to use Intent Chooser
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(url), "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
Intent newIntent = Intent.createChooser(intent, "Open File");
try {
startActivity(newIntent);
} catch (ActivityNotFoundException e) {
// Instruct the user to install a PDF reader here, or something
}
source to share
Add the following files / methods to your project
- PdfDownloader.java
- PDFDownloaderAsyncTask.java
and then using the following handleViewPdf method to view the pdf:
private void handleViewPdf () {
File folder = getAppDirectory(context);
String fileName = "test.pdf";// getPdfFileName(pdfUrl);
File pdfFile = new File(folder, fileName);
if (pdfFile.exists () && pdfFile.length () > 0) {
openPDFFile (context, Uri.fromFile(pdfFile));
}
else {
if (pdfFile.length () == 0) {
pdfFile.delete ();
}
try {
pdfFile.createNewFile ();
}
catch (IOException e) {
e.printStackTrace ();
}
ArrayList<String> fileNameAndURL = new ArrayList<> ();
fileNameAndURL.add (pdfFile.toString ());
fileNameAndURL.add (pdfUrl);
fileNameAndURL.add (fileName);
if (pdfDownloaderAsyncTask == null) {
pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask (context, pdfFile);
}
if (hasInternetConnection (context)) {
if (!pdfDownloaderAsyncTask.isDownloadingPdf ()) {
pdfDownloaderAsyncTask = new PDFDownloaderAsyncTask (context, pdfFile);
pdfDownloaderAsyncTask.execute (fileNameAndURL);
}
}
else {
//show error
}
}
}
PDFDownloaderAsyncTask.java
import java.io.File;
import java.util.ArrayList;
import android.content.Context;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.text.TextUtils;
import android.widget.Toast;
public class PDFDownloaderAsyncTask extends AsyncTask<ArrayList<String>, Void, String> {
private boolean isDownloadingPdf = false;
private File file;
private Context context;
public PDFDownloaderAsyncTask (Context context, File file) {
this.file = file;
this.context = context;
this.isDownloadingPdf = false;
}
public boolean isDownloadingPdf () {
return this.isDownloadingPdf;
}
@Override
protected void onPreExecute () {
super.onPreExecute ();
//show loader etc
}
@Override
protected String doInBackground (ArrayList<String>... params) {
isDownloadingPdf = true;
File file = new File (params[0].get (0));
String fileStatus = PdfDownloader.downloadFile (params[0].get (1), file);
return fileStatus;
}
@Override
protected void onPostExecute (String result) {
super.onPostExecute (result);
Loader.hideLoader ();
if (!TextUtils.isEmpty (result) && result.equalsIgnoreCase (context.getString (R.string.txt_success))) {
showPdf ();
}
else {
isDownloadingPdf = false;
Toast.makeText (context, context.getString (R.string.error_could_not_download_pdf), Toast.LENGTH_LONG).show ();
file.delete ();
}
}
@Override
protected void onCancelled () {
isDownloadingPdf = false;
super.onCancelled ();
//Loader.hideLoader ();
}
@Override
protected void onCancelled (String s) {
isDownloadingPdf = false;
super.onCancelled (s);
//Loader.hideLoader ();
}
private void showPdf () {
new Handler ().postDelayed (new Runnable () {
@Override
public void run () {
isDownloadingPdf = false;
openPDFFile (context, Uri.fromFile (file));
}
}, 1000);
}
}
PdfDownloader.java
package com.pdf;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
public class PdfDownloader {
private static final int MEGABYTE = 1024 * 1024;
public static String downloadFile (String fileUrl, File directory) {
String downloadStatus;
try {
URL url = new URL (fileUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection ();
urlConnection.connect ();
InputStream inputStream = urlConnection.getInputStream ();
FileOutputStream fileOutputStream = new FileOutputStream (directory);
int totalSize = urlConnection.getContentLength ();
Log.d ("PDF", "Total size: " + totalSize);
byte[] buffer = new byte[MEGABYTE];
int bufferLength = 0;
while ((bufferLength = inputStream.read (buffer)) > 0) {
fileOutputStream.write (buffer, 0, bufferLength);
}
downloadStatus = "success";
fileOutputStream.close ();
}
catch (FileNotFoundException e) {
downloadStatus = "FileNotFoundException";
e.printStackTrace ();
}
catch (MalformedURLException e) {
downloadStatus = "MalformedURLException";
e.printStackTrace ();
}
catch (IOException e) {
downloadStatus = "IOException";
e.printStackTrace ();
}
Log.d ("PDF", "Download Status: " + downloadStatus);
return downloadStatus;
}
public static void openPDFFile (Context context, Uri path) {
Intent intent = new Intent (Intent.ACTION_VIEW);
intent.setDataAndType (path, "application/pdf");
intent.setFlags (Intent.FLAG_ACTIVITY_CLEAR_TOP);
try {
context.startActivity (intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText (context, context.getString (R.string.txt_no_pdf_available), Toast.LENGTH_SHORT).show ();
}
Loader.hideLoader ();
}
public static File getAppDirectory (Context context) {
String extStorageDirectory = Environment.getExternalStorageDirectory ().toString ();
File folder = new File (extStorageDirectory, context.getString (R.string.app_folder_name).trim ());
if (!folder.exists ()) {
boolean success = folder.mkdirs();
Log.d ("Directory", "mkdirs():" + success);
}
return folder;
}
}
source to share
Your phone is not detecting PDF because the url you are using is a String object, not a PDF object. Technically, it should never open from your phone in PDF format unless you download the PDF. Reading PDFs on the phone is only activated after the Android OS informs them that it has a valid PDF file. Please take a look at the source code of any of the PDF libraries to understand it better -> https://android-arsenal.com/tag/72?sort=created
However, to answer your problem, try opening the url as a url. It activates the browser on your phone, which in turn detects that it needs a PDF reader and activates the corresponding reader.
Something like
String url = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa";
public void openWebPage(String url) {
Uri webpage = Uri.parse(url);
Intent intent = new Intent(Intent.ACTION_VIEW, webpage);
if (intent.resolveActivity(getPackageManager()) != null) {
startActivity(intent);
}
}
However, I think you just want to check if the file uploaded successfully. And if there is a local copy on the phone, just open the local copy instead of downloading another copy. If so, then I recommend using file metadata to achieve this. Something like:
// Create file metadata including the content type
StorageMetadata metadata = new StorageMetadata.Builder()
.setCustomMetadata("myPDFfile", "localPDFfileName")
.build();
// Upload the file and metadata
uploadTask = storageRef.child("pdf/localPDFfileName.pdf").putFile(file, metadata);
And in your success listener, extract the file metadata. If it's downloaded and looks complete, open the PDF from your local phone. If not, try downloading from downloadURL as I mentioned at the beginning of the post. This should cover the checks you are trying to do.
Do more if I didn't understand your problem correctly. I will pick it up and modify my answer accordingly.
source to share
Use Webview to view the pdf file -
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "https://firebasestorage.googleapis.com/v0/b/realtime-chat-46f4c.appspot.com/o/documents%2Fbf307aa5-79ae-4532-8128-ee394537b357.pdf?alt=media&token=2d0c5329-4717-4adc-9418-6614913e5bfa";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
source to share