Friday, 11 September 2015

How to Download a PDF from URL in Android



          This Tutorial teach you  how to download a PDF file from URL

 private class LongOperation extends AsyncTask<String, Void, String> {

String Filepath;

@Override
protected String doInBackground(String... params) 
    { 
    try {
String extStorageDirectory=Environment.getExternalStorageDirectory().toString();
File folder = new File(extStorageDirectory, "IFIN-PDF");
folder.mkdir();
Filepath = "ISFL-" + new Date().getDate()+newDate().getMonth()+
                                        new Date().getYear()+".pdf";
   File file = new File(folder, Filepath);
   try {
  file.createNewFile();

    catch (IOException e1) 
   {
e1.printStackTrace();
}
     Downloader.DownloadFile
  ("http://xxxxxxxxxxxxx/pdffile.pdf", file);//Paste your url here
    }
    catch (Exception e) {}
    return Filepath;
   }

@Override
protected void onPostExecute(String result) {

ProgressClass.progressClose();

File file = new File(Environment.getExternalStorageDirectory()
+ "/IFIN-PDF/" + result);

PackageManager packageManager = getPackageManager();
Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
pdfIntent .setType("application/pdf");
List list = packageManager.queryIntentActivities(pdfIntent ,
PackageManager.MATCH_DEFAULT_ONLY);
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(file);
intent.setDataAndType(uri, "application/pdf");
startActivity(intent);

}

@Override
protected void onPreExecute() {

ProgressClass.progressShow(downloadPDF.this, "Connecting");
}

}

public static class Downloader {

public static void DownloadFile(String fileURL, File directory) {
try {
   FileOutputStream file = new FileOutputStream(directory);
  URL url = new URL(fileURL);
HttpURLConnection connection = (HttpURLConnection) url .openConnection();
  connection .setRequestMethod("GET");
connection .setDoOutput(true);
connection .connect();
   InputStream input connection .getInputStream();
   byte[] buffer = new byte[1024];
   int len = 0;
 while ((len input .read(buffer)) > 0) {
file .write(buffer, 0, len );
}
file .close();
} catch (Exception e) {
e.printStackTrace();
}

}
}

Happy Coding:)