Pages

Thursday, June 26, 2014

Show or Read PDF in Android


To Show PDF file in your android phone first save it in your assets folder than read PDF file by using below two methods.
These methods first store your pdf in local storage than show it from local storage.

private void CopyReadAssets(String fileName) {
AssetManager assetManager = getAssets();

InputStream in = null;
OutputStream out = null;
File file = new File(getFilesDir(), fileName);
try {
in = assetManager.open(fileName);
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() + "/" + fileName),
"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);
}
}

No comments:

Post a Comment