Android: Display PDF using PdfRenderer

In Android there was one much needed missing area i.e., displaying a pdf document within an Android app which currently solves with the introduction of PdfRenderer api from Api level 21 onwards.  I have added the source code link at the bottom of the article to try it out.

Display Pdf using PdfRenderer in Android apps

API’s needed to render PDF

Below is the list of bare minimum api’s needed to display a pdf document.

Steps to render PDF

There are three important steps to display a pdf document, these are as follows –

  • Step 1 : Initialization of PdfRenderer

The first and foremost step is to initialize PdfRenderer by opening the pdf file and passing FileDescriptor object to PdfRenderer  constructor.

/**
     * Sets up a {@link android.graphics.pdf.PdfRenderer} and related resources.
     */
    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);
        }
    }
  • Step 2: Show a Page

Next step is to show a particular page by getting Bitmap for that page and showing in an ImageView.

/**
 * Shows the specified page of PDF to the screen.
 *
 * @param index The page index.
 */
private void showPage(int index) {
    if (mPdfRenderer.getPageCount() <= index) {
        return;
    }
    // Make sure to close the current page before opening another one.
    if (null != mCurrentPage) {
        mCurrentPage.close();
    }
    // Use `openPage` to open a specific page in PDF.
    mCurrentPage = mPdfRenderer.openPage(index);
    // Important: the destination bitmap must be ARGB (not RGB).
    Bitmap bitmap = Bitmap.createBitmap(mCurrentPage.getWidth(), mCurrentPage.getHeight(),
            Bitmap.Config.ARGB_8888);
    // Here, we render the page onto the Bitmap.
    // To render a portion of the page, use the second and third parameter. Pass nulls to get
    // the default result.
    // Pass either RENDER_MODE_FOR_DISPLAY or RENDER_MODE_FOR_PRINT for the last parameter.
    mCurrentPage.render(bitmap, null, null, PdfRenderer.Page.RENDER_MODE_FOR_DISPLAY);
    // We are ready to show the Bitmap to user.
    mImageView.setImageBitmap(bitmap);
    updateUi();
}
  • Step 3: Closing PdfRenderer

This is the last step that is once your fragment or activity get killed, make sure the renderer and related objects also get released from the memory.

/**
 * Closes the {@link android.graphics.pdf.PdfRenderer} and related resources.
 *
 * @throws java.io.IOException When the PDF file cannot be closed.
 */
private void closeRenderer() throws IOException {
    if (null != mCurrentPage) {
        mCurrentPage.close();
    }
    mPdfRenderer.close();
    mFileDescriptor.close();
}

If you also want to try, Google has already created a sample for it.

I hope this will be useful to all of you for displaying a pdf document in your respective Android app. So do not forget to share this with Android developers in your circle.

 

Happy coding!

Leave a Reply

Your email address will not be published. Required fields are marked *