24

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.

Bobrovsky
  • 13,789
  • 19
  • 80
  • 130
Ramakrishna
  • 4,066
  • 16
  • 48
  • 72

3 Answers3

28

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 :-)

rmtheis
  • 5,992
  • 12
  • 61
  • 78
Blundell
  • 75,855
  • 30
  • 208
  • 233
9

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.

Community
  • 1
  • 1
THelper
  • 15,333
  • 6
  • 64
  • 104
  • 2
    But in Blundell answer the file will not be downloaded if pdf is not available in mobile.But i want to download pdf file from url and then the pdf will be show in webview. So this is the right answer for me. – Ramakrishna Jun 16 '11 at 10:54
  • Any plugin that does that? Sound like something generic – Vlado Pandžić Aug 07 '17 at 21:33
0

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)));
Deep Adhia
  • 382
  • 4
  • 11
  • 3
    This is basically the same answer as [this](https://stackoverflow.com/a/6369390/3908170) one... do you have anything to add to make yours different? – DarkCygnus May 09 '18 at 22:18