Tutorials

Build an Android PDF Viewer or Editor in Java

By ComPDFKit | 2024 Jul 25
Android Java

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 in Java, enables your end users to view and edit PDFs with ease.

 

In this blog, we'll take ComPDFKit, a powerful Java PDF SDK, as an example to explore the necessary steps to build an Android PDF Viewer or editor.

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free

 

 

Requirements for Building Android PDF Viewer or Editor

 

For building Android PDF apps with ComPDFKit for Java, make sure you have downloaded or know the following information. 

 

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.



Download ComPDFKit Java PDF Library

 

Find and Download the Java PDF Library of ComPDFKit. You will get the package of ComPDFKit PDF SDK for Android as shown below:

 

 

Android PDF Library Package Structure



Get a Trial License for Your Android PDF Program

 

License for ComPDFKit Java PDF library could obtained on the Website directly. No need for the help of sales.

 



Step 1: Create a New Android Project for a PDF Viewer or Editor

 

Use Android Studio to create a Phone & Tablet project. Here we create a No Activity project.

 



Step 2: Add ComPDFKit Android PDF SDK Package

 

This is the guide for adding Android PDF SDK manually. More methods to add the package are given on the documentation page.

 

  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.

 

Copy ComPDFKit.aar and ComPDFKit-UI.aar to the libs directory

 

  1. Add the following code to the app dictionary’s build.gradle file:

...
dependencies {
    /*ComPDFKit SDK*/
    implementation(fileTree('libs'))
    ...
}
...
  1. 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'
}
  1. 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 for Android PDF Reader

 

Copying the License Key

Accurately obtaining the license key is crucial for the application of the license.

  1. In the email you received, locate the XML file containing the license key.

  2. Open the XML file and determine the license type through the <type> field. If <type>online</type> is present, it is an online license; if absent or <type>offline</type> is present, it is an offline license.

 

  • Online License:
xmlCopy code
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<license version="1">
    <platform>android</platform>
    <starttime>xxxxxxxx</starttime>
    <endtime>xxxxxxxx</endtime>
    <type>online</type>
    <key>LICENSE_KEY</key>
</license>

 

  • Offline License:
xmlCopy code
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<license version="1">
    <platform>android</platform>
    <starttime>xxxxxxxx</starttime>
    <endtime>xxxxxxxx</endtime>
    <key>LICENSE_KEY</key>
</license>

 

  1. Copy the LICENSE_KEY from the <key>LICENSE_KEY</key> field.

 

Apply the License Key

You can get a trial license for Android without sales (On the website directly). Before using any ComPDFKit PDF SDK classes, you must perform the following steps to apply the license to your application:

 

  1. Open your project's app/src/main/AndroidManifest.xml file.

  2. Initialize the license based on your requirements, either through online or offline authentication obtained in the previous step.

  3. Initialize the license as follows:

 

  • Online license:
<!-- Each ComPDFKit license is bound to a specific applicationId -->
<!-- For example: com.compdfkit.pdfviewer -->
<meta-data
    android:name="compdfkit_key_online"
    android:value="Your ComPDFKit Key" />

You can also initialize the ComPDFKit SDK and perform online authentication in your code as follows:

CPDFSdk.init(context, "your compdfkit license", false);

 

  • Offline license:
<!-- Each ComPDFKit license is bound to a specific applicationId -->
<!-- For example: com.compdfkit.pdfviewer -->
<meta-data
    android:name="compdfkit_key"
    android:value="Your ComPDFKit Key" />

You can also initialize the ComPDFKit SDK and perform offline authentication in your code as follows:

CPDFSdk.init(context, "your compdfkit license");



Step 4: Display a PDF Document with the Android PDF Viewer

 

Follow this step to build an Android PDF Viewer like the following. ComPDFKit also provides the guides to build an Android PDF Editor.

 

Android PDF Library Demo of ComPDFKit

 

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.

 

import the file Quick Start Guide.pdf

 

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.java 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.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();
    }
}

 

<!-- 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.

Now, with the help of ComPDFKit, you can get a simple application to display a PDF file like we displayed at the beginning of Step 4.



Troubleshooting about Integrating Java PDF Library

 

  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.

 

  1. Other Problems

If you encounter some other problems when integrating our ComPDFKit PDF SDK for Android, there are several ways to solve your problems:

 

 

  1. More Resources About ComPDFKit for Android

 

 

 

Windows   Web   Android   iOS   Mac   Server   React Native   Flutter   Electron
30-day Free