How to Build an Android PDF Viewer or Editor in Kotlin

Tutorials | Kotlin · Integration · PDF Viewer Fri. 21 Apr. 2023

In today's mobile-first world, creating an Android app is a must-have for businesses and developers alike. And, with the increasing need to work with PDF documents, building an Android PDF viewer and editor with ComPDFKit, a powerful PDF SDK, enable your end users to view and edit PDFs with ease.

 

In this blog, we'll start by exploring the necessary steps to integrate the ComPDFKit PDF SDK, and build an Android PDF Reader with ComPDFKit.

 

 

Get Started with ComPDFKit Android PDF SDK

 

ComPDFKit is a powerful PDF SDK. It is easy to embed ComPDFKit PDF SDK in your Android application with a few lines of Kotlin code. Take just a few minutes and get started.

 

The following sections introduce the requirements, structure of the installation package, and how to make an Android PDF Reader in Kotlin with ComPDFKit PDF SDK.

 

Requirements

 

ComPDFKit PDF SDK is supported on Android devices running API level 19 or newer and targeting the latest stable Android version 4.4 or higher. Furthermore, ComPDFKit PDF SDK requires apps to enable Java 8 language features to build.

         - Android Studio 3.2 or newer (support AndroidX).

         - Project specifications.

           A minSdkVersion of 19or higher.

           A compileSdkVersion of 30 or higher.

           A targetSdkVersion of 30 or higher.

           Android ABI(s): x86, x86_64, armeabi-v7a, arm64-v8a.

 

Android Package Structure

 

The package of ComPDFKit PDF SDK for Android includes the following files:

         - libs - A folder containing ComPDFKit.aar, ComPDFKit-UI.aar, and ComPDFKit-Utils.aar. ComPDFKit.aar is PDF Core API. ComPDFKit-UI.aar is the PDF View. ComPDFKit-Utils.aar includes UI extension components based on the fundamental layout classes: ReaderFragment or ReaderActivity.

         - PDFViewer - A folder containing Android sample projects.

         - api_reference_android - API reference.

         - developer_guide_android.pdf - Developer guide.

         - release_notes.txt - Release information.

         - legal.txt - Legal and copyright information.

 

Package Structure

 

 

Make an Android PDF Viewer in Kotlin

 

This section will help you to quickly get started with ComPDFKit PDF SDK to make an Android app in Kotlin with step-by-step instructions. Through the following steps, you will get a simple application that can display the contents of a specified PDF file:

 

Step 1: Create a New Project

 

1. Use Android Studio to create a Phone & Tablet project, here we create a No Activity project.

 

Create a New Project

 

Step 2: Add ComPDFKit PDF SDK Package

 

1. The first thing we need to do is to import ComPDFKit SDK. Copy ComPDFKit.aar and ComPDFKit-UI.aar to the libs directory of the app.

 

Add ComPDFKit PDF SDK Package 1

 

2. Add the following code into the app dictionary’s build.gradle file:

...
dependencies {
    /*ComPDFKit SDK*/
    implementation(fileTree('libs'))
    ...
}
...

 

3. Add ComPDFKit PDF SDK for Android as a dependency in the project. Inside the app dictionary’s build.gradle, add ComPDFKit.aar, ComPDFKit-UI.aar, and the related support libraries to the dependencies. For simplicity, update the dependencies as follows:

 

dependencies {
    ...
    // Add Kotlin coroutines dependencies
    implementation 'org.jetbrains.kotlinx:kotlinx-coroutines-android:1.6.1'

    // glide
    implementation 'com.github.bumptech.glide:glide:4.12.0'
    annotationProcessor 'com.github.bumptech.glide:compiler:4.12.0'

    implementation 'androidx.documentfile:documentfile:1.0.1'
}

 

4. Apply for read and write permissions in AndroidManifest.xml:

 

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>

 

Note: On your apps that target Android 6.0 or higher, make sure to check for and request read and write permissions to external storage at runtime.

 

Step 3: Apply the License Key

 

Add this license in the AndroidManifest.xml of the main module:

 

<meta-data
    android:name="compdfkit_key"
    android:value="{your ComPDFKit key}" />

 

Step 4: Display a PDF Document

 

1. Copy a PDF document into the assets directory of your Android project. For example, import the file Quick Start Guide.pdf to the path src/main/assets.

 

Display a PDF Document

 

2. Create a new Empty Activity under your package, and set the activity name to MainActivity.

 

Create a new Empty Activity

 

Android Studio will automatically generate a source file called MainActivity.kt and a layout file called activity_main.xml.

 

The source file:

 

The source file

 

The layout file:

 

The layout file

 

3. Create a CPDFReaderView in your activity_main.xml to display the contents of the PDF document:

 

<!-- Your activity_main.xml file -->

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <!-- Create a CPDFReaderView -->
    <com.compdfkit.ui.reader.CPDFReaderView
        android:id="@+id/readerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>



    
    

 

Get the CPDFReaderView from the layout or create a CPDFReaderView directly in the code in the corresponding MainActivity.kt file:

 

// Your MainActivity.java file
package com.compdfkit.pdfviewer
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.compdfkit.ui.reader.CPDFReaderView
class MainActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Get CPDFReaderView from xml.
        val readerView : CPDFReaderView = findViewById(R.id.readerview)
        // Code to create CPDFReaderView.
        // val readerView : CPDFReaderView = CPDFReaderView(content)
    }
}

 

4. Open the document. This is a time-consuming process, so it needs to be executed in a sub-thread. After the document is opened successfully, the UI that renders the PDF is initiated:

 

// Your MainActivity.java file
... //imports
class MainActivity : AppCompatActivity() {
    // Copy the PDF file from the assets folder to the cache folder.
    private fun copyPdfFromAssetsToCache(fileName: String) {
        try {
            val inputStream: InputStream = assets.open(fileName)
            val outputFile = File(cacheDir, fileName)
            val outputStream = FileOutputStream(outputFile)
            val buffer = ByteArray(1024)
            var bytesRead: Int
            while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                outputStream.write(buffer, 0, bytesRead)
            }
            inputStream.close()
            outputStream.flush()
            outputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val readerView : CPDFReaderView = findViewById(R.id.readerview)
        
        CoroutineScope(Dispatchers.Main).launch {
            withContext(Dispatchers.IO) {
                val fileName = "Quick Start Guide.pdf"
                copyPdfFromAssetsToCache(fileName)
                val file = File(cacheDir, fileName)
                val filePath = file.absolutePath
                //Open document.
                var error : CPDFDocument.PDFDocumentError = document.open(filePath)
                if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorPassword) {
                    //The document is encrypted and requires a password to open.
                    error = document.open(filePath, "password")
                }
                if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
                    //The document is opened successfully and data can be parsed and manipulated.
                } else {
                    //The PDF file failed to open. You can refer to the API file for specific error
                }
            }
        }
    }
}

 

5. Set the basic properties of CPDFReaderView:

// Your MainActivity.java file
...
//Create a document object.
val document : CPDFDocument = CPDFDocument(this)
var success = false
...
        if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
            success = true
            //The document is opened successfully and data can be parsed and manipulated.
        } else {
            //The PDF file failed to open. You can refer to the API file for specific error
        }
    }
    
    if (success)
        readerView.pdfDocument = document
}
...

 

6. Your code may resemble the following at this stage:

// Your activity class
class MainActivity : AppCompatActivity() {
    // Copy the PDF file from the assets folder to the cache folder.
    private fun copyPdfFromAssetsToCache(fileName: String) {
        try {
            val inputStream: InputStream = assets.open(fileName)
            val outputFile = File(cacheDir, fileName)
            val outputStream = FileOutputStream(outputFile)
            val buffer = ByteArray(1024)
            var bytesRead: Int
            while (inputStream.read(buffer).also { bytesRead = it } != -1) {
                outputStream.write(buffer, 0, bytesRead)
            }
            inputStream.close()
            outputStream.flush()
            outputStream.close()
        } catch (e: IOException) {
            e.printStackTrace()
        }
    }
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        val readerView : CPDFReaderView = findViewById(R.id.readerview)
        
        //Create a document object.
        val document : CPDFDocument = CPDFDocument(this)
        var success = false
        CoroutineScope(Dispatchers.Main).launch {
            withContext(Dispatchers.IO) {
                val fileName = "Quick Start Guide.pdf"
                copyPdfFromAssetsToCache(fileName)
                val file = File(cacheDir, fileName)
                val filePath = file.absolutePath
                //Open document.
                var error : CPDFDocument.PDFDocumentError = document.open(filePath)
                if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorPassword) {
                    //The document is encrypted and requires a password to open.
                    error = document.open(filePath, "password")
                }
                if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
                    success = true
                    //The document is opened successfully and data can be parsed and manipulated.
                } else {
                    //The PDF file failed to open. You can refer to the API file for specific error
                }
            }
            if (success)
                readerView.pdfDocument = document
        }
    }
}

 

<!-- Your activity_main.xml file -->
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <com.compdfkit.ui.reader.CPDFReaderView
        android:id="@+id/readerview"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</androidx.constraintlayout.widget.ConstraintLayout>



    

 

7. Run the application:

 

Run the application

 

Now, with the help of ComPDFKit, you can create a simple application to display a PDF file.

 

Troubleshooting

 

1. Unable to Open the PDF Files

The license we provide to you is tied to your application ID, so ensure that the license acquired matches your application ID.

 

2. Other Problems

If you meet some other problems when integrating our ComPDFKit PDF SDK for Android, feel free to contact ComPDFKit team.

 

Read More

 

. How to build an Android PDF Viewer or Editor in Java

 

. How to build an iOS PDF Viewer or Editor in Swift

 

. How to build an iOS PDF Viewer or Editor in Objective-C

 

. How to build an Web PDF Viewer with JavaScript

 

. How to build an Windows PDF Viewer in C#

Ready to Get Started?

Download our all-in-one ComPDFKit for free and run it to your project within minutes!