How to Download a PDF File and open it in Android using an installed PDF Reader?

By | March 6, 2013

Actually this is fairly simple.

This simple code does this.

Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					setError("PDF Reader application is not installed in your device");
				}

Here is the complete program that shows how to download a PDF File and open it in Android using an installed PDF Reader.

package com.example.openpdf;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;

import android.app.Activity;
import android.content.ActivityNotFoundException;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.view.Gravity;
import android.widget.TextView;

public class MainActivity extends Activity {

	TextView tv_loading;
	String dest_file_path = "test.pdf";
	int downloadedSize = 0, totalsize;
	String download_file_url = "http://ilabs.uw.edu/sites/default/files/sample_0.pdf";
	float per = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		tv_loading = new TextView(this);
		setContentView(tv_loading);
		tv_loading.setGravity(Gravity.CENTER);
		tv_loading.setTypeface(null, Typeface.BOLD);
		downloadAndOpenPDF();
	}

	void downloadAndOpenPDF() {
		new Thread(new Runnable() {
			public void run() {
				Uri path = Uri.fromFile(downloadFile(download_file_url));
				try {
					Intent intent = new Intent(Intent.ACTION_VIEW);
					intent.setDataAndType(path, "application/pdf");
					intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
					startActivity(intent);
					finish();
				} catch (ActivityNotFoundException e) {
					tv_loading
							.setError("PDF Reader application is not installed in your device");
				}
			}
		}).start();
  
	}

	File downloadFile(String dwnload_file_path) {
		File file = null;
		try {

			URL url = new URL(dwnload_file_path);
			HttpURLConnection urlConnection = (HttpURLConnection) url
					.openConnection();

			urlConnection.setRequestMethod("GET");
			urlConnection.setDoOutput(true);

			// connect
			urlConnection.connect();

			// set the path where we want to save the file
			File SDCardRoot = Environment.getExternalStorageDirectory();
			// create a new file, to save the downloaded file
			file = new File(SDCardRoot, dest_file_path);

			FileOutputStream fileOutput = new FileOutputStream(file);

			// Stream used for reading the data from the internet
			InputStream inputStream = urlConnection.getInputStream();

			// this is the total size of the file which we are
			// downloading
			totalsize = urlConnection.getContentLength();
			setText("Starting PDF download...");

			// create a buffer...
			byte[] buffer = new byte[1024 * 1024];  
			int bufferLength = 0;

			while ((bufferLength = inputStream.read(buffer)) > 0) {
				fileOutput.write(buffer, 0, bufferLength);
				downloadedSize += bufferLength;
				per = ((float) downloadedSize / totalsize) * 100;
				setText("Total PDF File size  : "
						+ (totalsize / 1024)
						+ " KB\n\nDownloading PDF " + (int) per
						+ "% complete");
			}
			// close the output stream when complete //
			fileOutput.close();
			setText("Download Complete. Open PDF Application installed in the device.");

		} catch (final MalformedURLException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final IOException e) {
			setTextError("Some error occured. Press back and try again.",
					Color.RED);
		} catch (final Exception e) {
			setTextError(
					"Failed to download image. Please check your internet connection.",
					Color.RED);
		}
		return file;
	}

	void setTextError(final String message, final int color) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setTextColor(color);
				tv_loading.setText(message);
			}
		});

	}

	void setText(final String txt) {
		runOnUiThread(new Runnable() {
			public void run() {
				tv_loading.setText(txt);
			}
		});

	}

}

14 thoughts on “How to Download a PDF File and open it in Android using an installed PDF Reader?

  1. Pingback: download and open PDF file on android | Unlimitedtricks

  2. Nirav

    Every time I got 0 size file ? and not able to download file why ??

    Reply
    1. arihant

      Every time I got 0 size file ? and not able to download file why ??

      Reply
      1. James Post author

        arihant,

        please check your file path in the server and make sure you have a working internet connection.

        Reply
  3. Pardeep Patel

    I want to create an android app of PDF Reader and have functionality like display PDF files available on the server and with click download files and saved in a folder offline and display in pdf reader

    Reply
  4. Anonymous

    Every time it is showing “App stopped working”
    is there any permission and gradle links we need to give?

    Reply
  5. anthony

    where do you put this code?

    Uri path = Uri.fromFile(downloadFile(download_file_url));
    try {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(path, “application/pdf”);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();
    } catch (ActivityNotFoundException e) {
    setError(“PDF Reader application is not installed in your device”);
    }

    Reply
  6. Raj thakur

    it shows..file no longer exists.the file may be renamed like that..please give me solution..

    Reply
    1. James Post author

      You should check the file path is correct or not.

      Reply
  7. IIie

    I get an error on this line
    Uri path = Uri.fromFile(downloadFile(download_file_url));
    errors are:
    E/AndroidRuntime: FATAL EXCEPTION: Thread-6
    Process: com.example.recyclerview_ass3, PID: 19626
    java.lang.NullPointerException: file
    at android.net.Uri.fromFile(Uri.java:473)
    at com.example.recyclerview_ass3.AdapterBooks$2.run(AdapterBooks.java:95)
    at java.lang.Thread.run(Thread.java:919)

    Can you tell what dest_file_path shows in this statement??
    file = new File(SDCardRoot, dest_file_path);

    Reply
  8. Mansoor Nisar

    android.os.FileUriExposedException: file:///storage/emulated/0/test.pdf exposed beyond app through Intent.getData()
    at android.os.StrictMode.onFileUriExposed(StrictMode.java:2083)
    at android.net.Uri.checkFileUriExposed(Uri.java:2388)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:11478)
    at android.content.Intent.prepareToLeaveProcess(Intent.java:11428)
    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1711)
    at android.app.Activity.startActivityForResult(Activity.java:5250)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:675)
    at android.app.Activity.startActivityForResult(Activity.java:5208)
    at androidx.fragment.app.FragmentActivity.startActivityForResult(FragmentActivity.java:662)
    at android.app.Activity.startActivity(Activity.java:5579)
    at android.app.Activity.startActivity(Activity.java:5547)
    at com.example.sampledownloadkt.MainActivity$downloadAndOpenPDF$1.run(MainActivity.kt:68)
    at java.lang.Thread.run(Thread.java:919)

    val intent = Intent(Intent.ACTION_VIEW)
    intent.setDataAndType(path, “application/pdf”)
    intent.flags = Intent.FLAG_GRANT_READ_URI_PERMISSION
    intent.flags = Intent.FLAG_ACTIVITY_CLEAR_TOP
    startActivity(intent)
    finish()

    App crashed on startActivity()

    Reply

Leave a Reply to arihant Cancel reply

Your email address will not be published. Required fields are marked *