There are a lot of ways to add PDF Viewer to your applications. But we are going to present one old but the simplest way to render your desired PDF Files into your Android applications. You may use to display files from assets which we are going to do in today’s post. Or you may download
Android PDF Viewer Library
The Library to render PDF files which we are going to use in our project is named as AndroidPDFViewer. This library is Licenced Under Apache Licence, Version 2.0. To add this library into your project you may import via
implementation 'com.github.barteksc:android-pdf-viewer:2.8.2'
Code language: JavaScript (javascript)
Asset Folder in Project
Now we will load a file from Assets folder. So go to your project and right click on app level src folder. There goto New Folder and then choose assets folder. This will create the folder named assets now paste any sample PDF file into this folder, Like this
Layout file
Now come to your activity layout file and create your XML layout file. In our example, we had used a full page pdf viewer with Linear Layout at TOP level parent of the layout. You may adjust your layout according to your need. The simple thing that you need to do is to add PDFView Widget to XML file like this
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.github.barteksc.pdfviewer.PDFView
android:id="@+id/pdfView"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>
Load PDF in Activity
Now come to your activity and load the PDF file via code. We had used Kotlin but the same thing apply with JAVA as well. We loaded the PDF file from assets in onCreate Function after setting the content view. We simply used following code to load the file.
pdfView.fromAsset("191_EE469.pdf")
.enableSwipe(true) /* allows to block changing pages using swipe*/
.swipeHorizontal(false)
.enableDoubletap(true)
.load()
because we named our widget as pdfView
ProGuard
If ProGaurd is enabled in your app then you should consider adding following line to your progaurd settings in progaurd-rules.pro file(according to Readme file from Github Repository).
-keep class com.shockwave.**
Code language: JavaScript (javascript)