DEV Community

Cover image for How to Build an Android PDF Viewer or Editor in Java
Youna
Youna

Posted on

How to Build an Android PDF Viewer or Editor in Java

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 Java 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 Java 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 19 or 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.

 

Android Package Structure

 

 

Make an Android PDF Viewer in Java

 

This section will help you to quickly get started with ComPDFKit PDF SDK to make an Android app in Java 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 PDF SDK. Copy ComPDFKit.aar and ComPDFKit-UI.aar to the libs directory of the app.

 

Libs

 

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 to 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 {
    ...
    //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:

Image description

 

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:

Image description

 

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.

 

Empty Activity

 

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

 

The source file:

 

Activity Java

 

The layout file:

 

Layout

 

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

 

Image description

 

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

 

// Your MainActivity.java file
package com.compdfkit.pdfviewer;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
import com.compdfkit.ui.reader.CPDFReaderView;
public class MainActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Get CPDFReaderView from xml.
        CPDFReaderView readerView = findViewById(R.id.readerview);
        // Code to create CPDFReaderView.
        // CPDFDocument readerView = new 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
public class MainActivity extends AppCompatActivity {
    // Copy the PDF file from the assets folder to the cache folder.
    private void copyPdfFromAssetsToCache(String fileName) {
        try {
            InputStream inputStream = getAssets().open(fileName);
            File outputFile = new File(getCacheDir(), fileName);
            FileOutputStream outputStream = new FileOutputStream(outputFile);
            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        CPDFReaderView readerView = findViewById(R.id.readerview);
        // Code to create CPDFReaderView.
        // CPDFDocument readerView = new CPDFReaderView(content);
        //Create a document object.
        CPDFDocument document = new CPDFDocument(this);
        
        new Thread(() -> {
            String fileName = "Quick Start Guide.pdf";
            copyPdfFromAssetsToCache(fileName);
            File file = new File(getCacheDir(), fileName);
            String filePath = file.getAbsolutePath();
            //Open document.
            CPDFDocument.PDFDocumentError error = 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
            }
        }).start();
    }
}

 

5. Set the basic properties of CPDFReaderView:

// Your MainActivity.java file
... // imports
public class MainActivity extends AppCompatActivity {
    // Create a handler to run the code on the main thread.
    private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
...
    if (error == CPDFDocument.PDFDocumentError.PDFDocumentErrorSuccess) {
        // The document is opened successfully and data can be parsed and manipulated.
        mainThreadHandler.post(() -> {
            // Set the document content for UI.
            readerView.setPDFDocument(document);
        });
    } else {
        // The PDF file failed to open. You can refer to the API file for specific error
    }
...
}

 

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

// Your MainActivity.java file

... // imports

public class MainActivity extends AppCompatActivity {
    // Create a handler to run the code on the main thread.
    private Handler mainThreadHandler = new Handler(Looper.getMainLooper());
    // Copy the PDF file from the assets folder to the cache folder.
    private void copyPdfFromAssetsToCache(String fileName) {
        try {
            InputStream inputStream = getAssets().open(fileName);
            File outputFile = new File(getCacheDir(), fileName);
            FileOutputStream outputStream = new FileOutputStream(outputFile);

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }

            inputStream.close();
            outputStream.flush();
            outputStream.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        CPDFReaderView readerView = findViewById(R.id.readerview);

        //Create a document object.
        CPDFDocument document = new CPDFDocument(this);

        new Thread(() -> {
            String fileName = "Quick Start Guide.pdf";
            copyPdfFromAssetsToCache(fileName);

            File file = new File(getCacheDir(), fileName);
            String filePath = file.getAbsolutePath();

            //Open document.
            CPDFDocument.PDFDocumentError error = 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.
                mainThreadHandler.post(() -> {
                    //Set the document to the reader view.
                    readerView.setPDFDocument(document);
                });
            } else {
                //The PDF file failed to open. You can refer to the API file for specific error
            }
        }).start();
    }
}

Image description

 

7. Run the application.

 

demo

 

Now, with the help of ComPDFKit, you can get 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.

Top comments (0)