Create and Display PDF within Android Application

Embedding functionality to Create and Display PDF within Android Application can increase engagement of your user significantly. Rather than asking user to bounce off to other pdf viewer application, we will create an application with support of Pdf creation and viewing functionalities.

Sample Application For Creation and Display of Pdf

1. Create a new Android Application Project with Package name com.androidsrc.pdfdemo. Make sure to select API 21. As PdfRenderer was introduced in requires API level 21. If you are creating functionality of Pdf document creation only, you can opt for API 19 as well.

2. Preparing AndroidManifest.xml

Add permission into your manifest file to read and write from external storage. Ensure to add uses-sdk tag with minSdkVersion specified as 21.

3. Preparing UI Components

For our main view, we will use FrameLayout as parent view. It will have four child LinearLayout views for displaying pdf options, pdf document listing and reading pdf, creating pdf. We will navigate between these views intercepting back key and close option in menu. Final activity_main.xml will be as below after including views for above functionalities.

We will be using ListView for displaying list of Pdf document available. Create new layout file /res/layout/list_item.xml for list viw item. It will just have TextView which will display path for Pdf documents.

Create new menu file /res/menu/main.xml. It will have one menu item which will incorporate functionality to navigate between different views in layout.

4. Preparing Applicaiton Launcher Activity Source Code

Creating PDF Document

For creating PDF Document, we will use PdfDocument class which was added in API level 19. It prvoides api to create new PDF document, you can process content creation page by page using PdfDocument.Page. PDF page associates a canvas on which you can draw your content. For representing attributes of a page like height, width and page number etc PdfDocument.PageInfo is used.

Pretty cool, with just few lines of codes as above you can create new Pdf document. You can simply provide your user to share content of your application in form of Pdf document. For applications like billing, patient information etc, user can quickly opt to create Pdf and share.

Displaying PDF Document

For displaying PDF Document, we will use PdfRenderer class which was added in API level 21. With this you can render Pdf Document pages into native views of your android application. PdfRenderer.Page is used to open, render and closing page of particular index in Pdf document.

Complete code for MainActivity.java

5.Build and Run your Application

We are done. Build and run your application, you can read and create Pdf document within your application.

You may also like...

Leave a Reply

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