Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to download a pdf file in Android?

I want to download a pdf file from an url. For viewing the pdf file I used the code below.

File file = new File("/sdcard/example.pdf");

if (file.exists()) {
    Uri path = Uri.fromFile(file);
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setDataAndType(path, "application/pdf");
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

    try {
        startActivity(intent);
    } 
    catch (ActivityNotFoundException e) {
        Toast.makeText(OpenPdf.this, "No Application Available to View PDF",
            Toast.LENGTH_SHORT).show();
    }
}

It is working but how do I get the pdf file from an url (e.g http://.../example.pdf). I want to download the pdf file from this url. Please help me. Thanks in advance.

like image 761
Ramakrishna Avatar asked Jun 16 '11 08:06

Ramakrishna


3 Answers

Download a pdf:

 startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("www.education.gov.yk.ca/pdf/pdf-test.pdf")));

Ah as I've just found out this is device dependent.

scenarios

  1. It will download the pdf to your browser/downloaded/ folder

  2. You have a google docs account - It will ask you to sign in then view the pdf in the browser

  3. You have a pdf reader installed - App dependent may catch it may not

In all scenarios though the user has access to the PDF with one line of code :-)

like image 96
Blundell Avatar answered Nov 14 '22 04:11

Blundell


Downloading a PDF works the same as downloading any other binary file.

  1. Open a HttpUrlConnection
  2. Use the connection's getInputStream() method to read the file.
  3. Create a FileOutputStream and write the inputstream.

Check this post for example source code.

like image 34
THelper Avatar answered Nov 14 '22 04:11

THelper


There is no need to put lengthy code to open and download pdf in android you can just use below code to open and download pdf

String URL ="http://worldhappiness.report/wp-content/uploads/sites/2/2016/03/HR-V1_web.pdf"

 startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(URL)));
like image 28
Deep Adhia Avatar answered Nov 14 '22 03:11

Deep Adhia