Open a External pdf file

Here is the code for open a external pdf file in android phone..

public void myClickHandler(View v) {
          try {
            String extStorageDirectory = Environment.getExternalStorageDirectory()
                    .toString();
                    File folder = new File(extStorageDirectory, "pdf");
                    folder.mkdir();
                    File file = new File(folder, "Read.pdf");
                    try {
                            file.createNewFile();
                    } catch (IOException e1) {
                            e1.printStackTrace();
                    }
                    Downloader.DownloadFile("http://www.google.com/test.pdf", file);
                    OpenPdf();
        } catch (Exception e) {
            //e.printStackTrace();
            alertbox("error",e.getMessage());
        }
    }

private void OpenPdf()
    {
         File file = new File(Environment.getExternalStorageDirectory()+"/pdf/Read.pdf");
                 Intent intent = new Intent();
                 intent.setAction(Intent.ACTION_VIEW);
                 Uri uri = Uri.fromFile(file);
                 intent.setDataAndType(uri, "application/pdf");
                 startActivity(intent);
    }
    
Here is the Downloader class which download the pdf content from web address 
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class Downloader {

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

1 comment:

  1. Nice post..But can tell me how we create a pdf in phone ..

    ReplyDelete