How to Render a Pdf File in Android

How to render a pdf in android using pdf renderer

startActivity(new Intent(getActivity(), PdfActivity.class).putExtra("filePath", file.getAbsoluteFile()));

Change to:

startActivity(new Intent(getActivity(), PdfActivity.class).putExtra("filePath", file.getAbsolutePath()));

How to render PDF in Android

Some phones (like the Nexus One) come with a version of Quickoffice pre-installed so it may be as easy as sending the appropriate Intent once you've saved the file to the SD card.

public class OpenPdf extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

Button button = (Button) findViewById(R.id.OpenPdfButton);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
File file = new File("/sdcard/example.pdf");

if (file.exists()) {
Uri path = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(path, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);

try {
startActivity(intent);
}
catch (ActivityNotFoundException e) {
Toast.makeText(OpenPdf.this,
"No Application Available to View PDF",
Toast.LENGTH_SHORT).show();
}
}
}
});
}
}

Show PDF file in App

Android provides PDF API now with which it is easy to present pdf content inside application.

you can find details here

Below is the sample snippet to render from a pdf file in assets folder.

    private void openRenderer(Context context) throws IOException {
// In this sample, we read a PDF from the assets directory.
File file = new File(context.getCacheDir(), FILENAME);
if (!file.exists()) {
// Since PdfRenderer cannot handle the compressed asset file directly, we copy it into
// the cache directory.
InputStream asset = context.getAssets().open(FILENAME);
FileOutputStream output = new FileOutputStream(file);
final byte[] buffer = new byte[1024];
int size;
while ((size = asset.read(buffer)) != -1) {
output.write(buffer, 0, size);
}
asset.close();
output.close();
}
mFileDescriptor = ParcelFileDescriptor.open(file, ParcelFileDescriptor.MODE_READ_ONLY);
// This is the PdfRenderer we use to render the PDF.
if (mFileDescriptor != null) {
mPdfRenderer = new PdfRenderer(mFileDescriptor);
}
}

update: This snippet is from google developers provided samples.

Display PDF file inside my android application

Maybe you can integrate MuPdf in your application. Here is I've described how to do this: Integrate MuPDF Reader in an app



Related Topics



Leave a reply



Submit