Search code examples
androidweb-servicespdfbufferedreaderfilereader

Download and View PDF inside android application from Webservice


I am trying to download and open a PDF file inside android application i.e. without using any other application(pdf viewer,etc) installed on phone.

Please tell me is it possible??

So far What I have done is :

PdfViewerActivity.java

public class PDFViewerActivity extends Activity {
    private Button mDownLoadPdf;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.pdfviewer_activity);
    }

    public void downloadPDF(View v)
    {
//        new DownloadFile().execute("http://maven.apache.org/maven-1.x/maven.pdf", "maven.pdf");
        new DownloadFile().execute("http://dev-hop-docs.seechangehealth.com/SitePages/PDFLoader.aspx?test=abc");
        Toast.makeText(this,"Download finished,Viewing PDF...",Toast.LENGTH_SHORT).show();
        view();
    }

    public void view()
    {
        File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "privacy notice.pdf");  // -> filename = maven.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_VIEW);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(PDFViewerActivity.this, "No Application available to view PDF", Toast.LENGTH_SHORT).show();
        }
    }

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

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];   // -> http://maven.apache.org/maven-1.x/maven.pdf
//            String fileName = strings[1];  // -> maven.pdf
            String fileName = "privacy notice.pdf";
            String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
            File folder = new File(extStorageDirectory, "testthreepdf");
            folder.mkdir();

            File pdfFile = new File(folder, fileName);

            try{
                pdfFile.createNewFile();
            }catch (IOException e){
                e.printStackTrace();
            }
            FileLoader.downloadFile(fileUrl, pdfFile);
            return null;
        }
    }
}

And this is my FileLoader.java

public class FileLoader {
    private static final int  MEGABYTE = 1024 * 1024;

    public static void downloadFile(String fileUrl, File directory){
        try {

            URL url = new URL(fileUrl);
            HttpURLConnection urlConnection = (HttpURLConnection)url.openConnection();
            urlConnection.setRequestMethod("GET");
//            urlConnection.setDoOutput(true);
//            urlConnection.connect();

            InputStream inputStream = urlConnection.getInputStream();
            FileOutputStream fileOutputStream = new FileOutputStream(directory);
            int totalSize = urlConnection.getContentLength();

            byte[] buffer = new byte[MEGABYTE];
            int bufferLength = 0;
            while((bufferLength = inputStream.read(buffer))>0 ){
                fileOutputStream.write(buffer, 0, bufferLength);
            }
            fileOutputStream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

Using the above code , I am getting following error :

Invalid PDF Format.

But when i paste this webservice url on pc browser it opens a pdf.

Please tell me what I have done wrong. Or is there any other way to achieve it.


Solution

  • I am trying to download and open a PDF file inside android application i.e. without using any other application(pdf viewer,etc) installed on phone.

    Not according to the code in your question. You are specifically attempting to open the PDF file in "other application(pdf viewer,etc) installed on phone".

    Using the above code , I am getting following error : Invalid PDF Format.

    The file does not exist yet. You need to wait to do your view() logic until onPostExecute() of your AsyncTask. Right now, you are trying to view() the file while the download is going on in a background thread.

    I also would recommend that you call flush() and getFD().sync() on your FileOutputStream before you close() it, to ensure that all bytes are written to disk before you try launching the third-party PDF viewer.