Rendering/Viewing PDF File by using PdfRenderer API in Android Lollipop

    Have you event wondered opening a PDF file in your own application without using third-party viewer? If you’re on Android 4.4 or below, try opening a PDF in the Drive app – you’ll be sent to whatever your native PDF viewing tool happens to be.
   Okey, Android Lollipop, finally, there is an API supports rendering PDF file. In this example I will present the way to use PdfRenderer to display PDF documents on the device screen, very convenient to preview it's content.

More about PdfRender API class

    Like Google developer docs say: "This class enables rendering a PDF document. This class is not thread safe.
    If you want to render a PDF, you create a renderer and for every page you want to render, you open the page, render it, and close the page. After you are done with rendering, you close the renderer. After the renderer is closed it should not be used anymore. Note that the pages are rendered one by one, i.e. you can have only a single page opened at any given time".

Coding sample project

    Launch Android Studio and create a new project, min sdk is 21 for using this API.
    Create assets folder and put a sample pdf file to this. In this project, we will render it from assets resource to a native view, show it's content to screen.
    Declare a layout for our screen (Activity) simple like this:
    In activity, after click button, we will replace a fragment to show PDF file content, full code for MainActivity.java:
    In our fragment:
- Open PDF file and create a new PdfRenderer object in onAttach() method.
- show each page of file as a Bitmap image into an ImageView after locate all views elements in showPage() method.
- set event for 2 buttons (Next and Previous) to change current page.
- Close PdfRenderer stream after destroy Fragment object (onDestroy() method).
Code for PDFRenderFragment.java:
 Layout for our fragment:
   For avoid "This file can not be opened as a file descriptor; it is probably compressed" error, you must add aaptOptions in your local build.gradle file. Here it's is noCompress "pdf" option.
    Your build.gradle file in app module will be like this:
Running application, we'll have this output:


(Sorry for having ads)

Share


Previous post
« Prev Post
Next post
Next Post »