开发者

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开发者_StackOverflow",
            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.


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


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.


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)));
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜