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
It will download the pdf to your browser/downloaded/ folder
You have a google docs account - It will ask you to sign in then view the pdf in the browser
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.
- Open a
HttpUrlConnection
- Use the connection's
getInputStream()
method to read the file. - 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)));
精彩评论