Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Offer comprehensive code samples and show how to integrate the ComPDFKit PDF SDK to build a PDF viewer and editor on Android.

License

NotificationsYou must be signed in to change notification settings

ComPDFKit/compdfkit-pdf-sdk-android

Repository files navigation

ComPDFKit PDF SDK for Android is developed and maintained byComPDF, enabling developers to quickly and seamlessly integrate advanced PDF functionalities—such as viewing, editing, annotating, and signing—into any Android application.The ComPDFKit Android PDF Library provides an easy-to-use Java API that allows direct access to a wide range of PDF features without the need for complex configurations. Byregistering for a free ComPDF API account, developers can process up to 1,000 PDF files monthly.More Information can be found at:https://www.compdf.com/guides/pdf-sdk/android/overview

Table of Content

Related

Requirements

ComPDFKit Android PDF SDK supports Android devices running API level 19 or newer and targets the latest stable Android 4.4 or later. In addition, it requires applications to be built with Java 8 language features enabled.

  • Android Studio 3.2 or newer (support AndroidX).
  • Project specifications.
    • AminSdkVersion of19 or higher.
    • AcompileSdkVersion of30 or higher.
    • AtargetSdkVersion of34 or higher.
    • Android ABI(s): x86, x86_64, armeabi-v7a, arm64-v8a.

How to Make an Android PDF Viewer in Java

This section will help you 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.

Video Guide:Build an Android PDF Editor in Java

image-youtube-20250515

Create a New Project

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

create_project

Installation

Integrate With Gradle

  1. Open thesettings.gradle file located in your project's root directory and add themavenCentral repository:
dependencyResolutionManagement {    repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS)    repositories {        google()+       mavenCentral()    }}
  1. Open thebuild.gradle file in the application module directory:

2.4.2.1-1

Edit it and add the completeComPDFKit SDK dependency:

dependencies {  implementation'com.compdf:compdfkit:2.4.3'  implementation'com.compdf:compdfkit-ui:2.4.3'}
  1. Apply for read and write permissions inAndroidManifest.xml:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permissionandroid: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.

  1. If you use an online license, please add network access permissions inAndroidManifest.xml:
<uses-permissionandroid:name="android.permission.INTERNET"/>

Integrate Manually

  1. Copy"ComPDFKit.aar" and"ComPDFKit-UI.aar" to the"libs" directory of theapp.

libs.png

  1. Add the following code into theapp dictionary's"build.gradle" file:
...dependencies {/*ComPDFKit SDK*/    implementation(fileTree('libs'))...}...
  1. AddComPDFKit PDF SDK for Android as a dependency to the project. Inside theapp dictionary's"build.gradle", add"ComPDFKit.aar","ComPDFKit-UI.aar", and the related support libraries to thedependencies. 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 inAndroidManifest.xml:
<uses-permissionandroid:name="android.permission.WRITE_EXTERNAL_STORAGE"/><uses-permissionandroid: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.

  1. If you use an online license, please add network access permissions inAndroidManifest.xml:
<uses-permissionandroid:name="android.permission.INTERNET"/>

Apply the License Key

Add this license in theAndroidManifest.xml of the main module. In version1.13.0, we introduced a brand-new online authentication license scheme for ComPDFKit SDK. By default, the SDK performs online authentication. If you are using a version prior to1.13.0, please refer to the following example to configure the SDK for offline authentication mode:

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

You can also initialize ComPDFKit SDK in code using:

CPDFSdk.init(context,"your compdfkit license",false);
  • Offline license
<!-- Each ComPDFKit license is bound to a specific applicationId--><!-- For example: com.compdfkit.pdfviewer--><meta-dataandroid:name="compdfkit_key"android:value="Your ComPDFKit Key" />

You can also initialize ComPDFKit SDK in code using:

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

Add Proguard Rules

In theproguard-rules.pro file, please add the obfuscation configuration information forcompdfkit as follows:

-keep class com.compdfkit.ui.** {*;}-keep class com.compdfkit.core.** {*;}

Display a PDF Document

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

structure.png

  1. Create a newEmpty Activity under your package, and set the activity name toMainActivity.

new_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.png

The layout file:

layout.png

  1. Create aCPDFReaderView 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.ConstraintLayoutxmlns: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.CPDFReaderViewandroid:id="@+id/readerview"android:layout_width="match_parent"android:layout_height="match_parent" /></androidx.constraintlayout.widget.ConstraintLayout>

Get theCPDFReaderView from the layout or create aCPDFReaderView directly in the code in the correspondingMainActivity.java file:

// Your MainActivity.java filepackagecom.compdfkit.pdfviewer;importandroidx.appcompat.app.AppCompatActivity;importandroid.os.Bundle;importcom.compdfkit.ui.reader.CPDFReaderView;publicclassMainActivityextendsAppCompatActivity {@OverrideprotectedvoidonCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// Get CPDFReaderView from xml.CPDFReaderViewreaderView =findViewById(R.id.readerview);// Code to create CPDFReaderView.// CPDFDocument readerView = new CPDFReaderView(content);    }}
  1. Open the document. This is a time-consuming process, so it needs to be executed in asub-thread. After the document is opened successfully, the UI that renders the PDF is initiated:
// Your MainActivity.java file...//importspublicclassMainActivityextendsAppCompatActivity {// Copy the PDF file from the assets folder to the cache folder.privatevoidcopyPdfFromAssetsToCache(StringfileName) {try {InputStreaminputStream =getAssets().open(fileName);FileoutputFile =newFile(getCacheDir(),fileName);FileOutputStreamoutputStream =newFileOutputStream(outputFile);byte[]buffer =newbyte[1024];intbytesRead;while ((bytesRead =inputStream.read(buffer)) != -1) {outputStream.write(buffer,0,bytesRead);            }inputStream.close();outputStream.flush();outputStream.close();        }catch (IOExceptione) {e.printStackTrace();        }    }@OverrideprotectedvoidonCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);CPDFReaderViewreaderView =findViewById(R.id.readerview);// Code to create CPDFReaderView.// CPDFDocument readerView = new CPDFReaderView(content);//Create a document object.CPDFDocumentdocument =newCPDFDocument(this);newThread(() -> {StringfileName ="Quick Start Guide.pdf";copyPdfFromAssetsToCache(fileName);Filefile =newFile(getCacheDir(),fileName);StringfilePath =file.getAbsolutePath();//Open document.CPDFDocument.PDFDocumentErrorerror =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();    }}
  1. Set the basic properties ofCPDFReaderView :
// Your MainActivity.java file...// importspublicclassMainActivityextendsAppCompatActivity {// Create a handler to run the code on the main thread.privateHandlermainThreadHandler =newHandler(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    }...}
  1. Your code may resemble the following at this stage:
// Your MainActivity.java file...// importspublicclassMainActivityextendsAppCompatActivity {// Create a handler to run the code on the main thread.privateHandlermainThreadHandler =newHandler(Looper.getMainLooper());// Copy the PDF file from the assets folder to the cache folder.privatevoidcopyPdfFromAssetsToCache(StringfileName) {try {InputStreaminputStream =getAssets().open(fileName);FileoutputFile =newFile(getCacheDir(),fileName);FileOutputStreamoutputStream =newFileOutputStream(outputFile);byte[]buffer =newbyte[1024];intbytesRead;while ((bytesRead =inputStream.read(buffer)) != -1) {outputStream.write(buffer,0,bytesRead);            }inputStream.close();outputStream.flush();outputStream.close();        }catch (IOExceptione) {e.printStackTrace();        }    }@OverrideprotectedvoidonCreate(BundlesavedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);CPDFReaderViewreaderView =findViewById(R.id.readerview);//Create a document object.CPDFDocumentdocument =newCPDFDocument(this);newThread(() -> {StringfileName ="Quick Start Guide.pdf";copyPdfFromAssetsToCache(fileName);Filefile =newFile(getCacheDir(),fileName);StringfilePath =file.getAbsolutePath();//Open document.CPDFDocument.PDFDocumentErrorerror =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.ConstraintLayoutxmlns: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.CPDFReaderViewandroid:id="@+id/readerview"android:layout_width="match_parent"android:layout_height="match_parent" /></androidx.constraintlayout.widget.ConstraintLayout>
  1. Run the application.

screen_shot.png

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

Support

ComPDF offers professional technical support and 5*24 responsive service.

  • For detailed information, please visit ourGuides page.

  • Stay updated with the latest improvements through ourChangelog.

  • For technical assistance, please reach out to ourTechnical Support.

  • To get more details and an accurate quote, please contact ourSales Team orSend an Email to us.

License

ComPDF offers developers a30-day free trial license for free testing your Android projects. Additionally, you'll have access to a fully-featured product with no limitations on file or user count.

About

Offer comprehensive code samples and show how to integrate the ComPDFKit PDF SDK to build a PDF viewer and editor on Android.

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published

[8]ページ先頭

©2009-2025 Movatter.jp