Reputation: 607
I am an iOS developer but have been tasked with updating our company's android apps also (so I have little android experience) The android app currently loads PDFs from raw and then displays them in another pdf reader application also installed on the android... however I would like to instead get the pdf's from the internet.
this is the code being using to show the pdf stored locally.
if (mExternalStorageAvailable==true && mExternalStorageWriteable==true)
{
// Create a path where we will place our private file on external
// storage.
Context context1 = getApplicationContext();
File file = new File(context1.getExternalFilesDir(null).toString() + "/pdf.pdf");
URL url = new URL("https://myurl/pdf.pdf");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
OutputStream os = new FileOutputStream(file);
try {
byte[] data = new byte[in.available()];
in.read(data);
os.write(data);
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
} catch (IOException e) {
// Unable to create file, likely because external storage is
// not currently mounted.
Log.w("ExternalStorage", "Error writing " + file, e);
Context context2 = getApplicationContext();
CharSequence text1 = "PDF File NOT Saved";
int duration1 = Toast.LENGTH_SHORT;
Toast toast = Toast.makeText(context2, text1, duration1);
toast.show();
} finally {
in.close();
os.close();
}
}
Eventually the pdf's will come from a website and the website will require an HTML post request sent to it before the PDF can be downloaded. I think I will be able to figure out the HTML post, but for now how can I download a PDF from the internet and have it display. I tried changing the URI to point to the location but that didn't work, or I structured it incorrectly.
Also keep in mind for security reasons I do not want to display this using google viewer and a webview
Upvotes: 1
Views: 3062
Reputation: 4585
You just need to read from a distant server. I'd try something like:
URL url = new URL("http://www.mydomain.com/slug");
URLConnection urlConnection = url.openConnection();
InputStream in = new BufferedInputStream(urlConnection.getInputStream());
try {
readStream(in); // Process your pdf
} finally {
in.close();
}
You may also want to checkout the AndroidHttpClient class to make http requests directly (GET or POST in your application).
Upvotes: 1