Downloading a PDF file

10,877

Solution 1

//use this method to download the pdf file

 public void downloadPdfContent(String urlToDownload){

             try {

                 String fileName="xyz";
             String fileExtension=".pdf";

//           download pdf file.

                URL url = new URL(urlToDownload);
                HttpURLConnection c = (HttpURLConnection) url.openConnection();
                c.setRequestMethod("GET");
                c.setDoOutput(true);
                c.connect();
                String PATH = Environment.getExternalStorageDirectory() + "/mydownload/";
                File file = new File(PATH);
                file.mkdirs();
                File outputFile = new File(file, fileName+fileExtension);
                FileOutputStream fos = new FileOutputStream(outputFile);
                InputStream is = c.getInputStream();
                byte[] buffer = new byte[1024];
                int len1 = 0;
                while ((len1 = is.read(buffer)) != -1) {
                    fos.write(buffer, 0, len1);
                }
                fos.close();
                is.close();

               System.out.println("--pdf downloaded--ok--"+urlToDownload);
            } catch (Exception e) {
                e.printStackTrace();

            }
    }

// for viewing the pdf use this method

private void onPdfClick()
    {

//      String pdfFile = Environment.getExternalStorageDirectory()+ File.separator + AstroManager.file.getName();

         Intent intent = new Intent(Intent.ACTION_VIEW);
         intent.setDataAndType(Uri.fromFile(new File("/sdcard/mydownload/xyz.pdf"), "application/*");

         startActivity(intent);
    }

Solution 2

If you have to open pdf file, pdf reader must have to be installed in your device.Otherwise it will show blank screen. Also here is good example to download pdf from server and view its contents.

Share:
10,877
Gaurav
Author by

Gaurav

Android Developer

Updated on November 21, 2022

Comments

  • Gaurav
    Gaurav over 1 year

    In my application, the user needs to download PDF file from an url and store it on sdcard. But the catch here is I can only use DefaultHttpClient to access the url. I found couple of solutions but none used DefaultHttpClient. After downloading the PDF, I would also likie to view the PDF in my application.

  • Gaurav
    Gaurav over 12 years
    As I mentioned in my question, I want to use DefaulthttpClient. In your answer, you have used HttpURLConnection
  • Padma Kumar
    Padma Kumar over 12 years
    ya you can change it to DefaulthttpClient, whats the problem.
  • Gaurav
    Gaurav over 12 years
    Thanks a lot man. Sorry I took time. Actually the problem was, my url was having some redirects so I had handle that aswell..But your code works well :)
  • Motassem Jalal
    Motassem Jalal over 7 years
    Hey, how to control the charset? I'm using the same method and some pdfs contain unknown characters and some not.