I am working on pdf. I am trying to open a pdf file from my application using the code below. But I failed to open.
private void openPdf() {
File file = new File("mnt/sdcard.test.pdf");
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
intent.setAction(Intent.ACTION_VIEW);
intent.setData(path);
intent.setType("application/pdf");
try {
startActivity(intent);
} catch (ActivityNotFoundException e) {
Toast.makeText(getActivity(), "No application found",
Toast.LENGTH_SHORT).show();
}
}
When I tried this code in emulator,it shows a toast saying "No application found"(bcoz,normally no pdf viewing application are installed in emulator). When I tested the same thing in device (specifically in funbook tab and in sony tab), it neither showed the Toast message nor it opened the pdf file. Can anybody point out the mistake in my code. Actually I am working with pdf for the first time. So my question is,
I got solution of above problem, so try once;
Steps:-
create assets folder in src under your app name.
In this assets folder keep your pdf files e.g. schedule1.pdf.
now come your activity i.e MainActivity.java
setListener on any UI component what you want i.e (Button
, ImageView
, ImageButton
);
In this listener call one user defined method i.e. openPDFFiles()
the openPDFFiles() method have below code:
private void openPDFFiles() {
AssetManager assetManager = getAssets();
InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), “schedule1.pdf”);//here schedule1.pdf is the pdf file name which is keep in assets folder.
try {
in = assetManager.open(“schedule1.pdf”);
out = openFileOutput(file.getName(), Context.MODE_WORLD_READABLE);
copyFile(in, out);
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
Log.e(“tag”, e.getMessage());
}
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse(“file://” + getFilesDir() + “/schedule1.pdf”), “application/pdf”);
startActivity(intent);
}
private void copyFile(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With