Wednesday 8 July 2015

share pdf from url in android

Now you can share pdf from url ,its quiet easy 


check out the code

1. the async task to be performmed
private class DownloadFile extends AsyncTask<String, Void, Void>{

        @Override
        protected Void doInBackground(String... strings) {
            String fileUrl = strings[0];  //YOUR_URL_PDF.pdf
            String fileName = strings[1];  //ANY_NAME.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();
            }
            FileDownloader.downloadFile(fileUrl, pdfFile);
            return null;
        }

@Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
  File pdfFile = new File(Environment.getExternalStorageDirectory() + "/testthreepdf/" + "ANY_NAME.pdf");  // -> filename = ANY_NAME.pdf
        Uri path = Uri.fromFile(pdfFile);
        Intent pdfIntent = new Intent(Intent.ACTION_SEND);
        pdfIntent.setDataAndType(path, "application/pdf");
        pdfIntent.putExtra(Intent.EXTRA_SUBJECT"subject");
        pdfIntent.putExtra(Intent.EXTRA_TEXT,     "your text");
        pdfIntent.putExtra(Intent.EXTRA_STREAM, path );
        pdfIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

        try{
            startActivity(pdfIntent);
        }catch(ActivityNotFoundException e){
            Toast.makeText(MainActivity.this, "Pdf could not be shared", Toast.LENGTH_SHORT).show();
           
          
        }
}
    }



2.call the async task in your share button

 new DownloadFile().execute("YOUR_URL_PDF.pdf", "ANY_NAME.pdf"); 




Thats it !!!!Enjoy

No comments:

Post a Comment