1. Home
  2. Foxit MobilePDF SDK
  3. Developer Guide for Foxit MobilePDF SDK (Android)

Developer Guide for Foxit MobilePDF SDK (Android)

Introduction to Foxit MobilePDF SDK

Have you ever worried about the complexity of the PDF specification? Or have you ever felt lost when asked to build a full-featured PDF app within a limited time-frame? If your answer is “Yes”, then congratulations! You have just found the best solution in the industry for rapidly integrating PDF functionality into your apps.

Why Foxit MobilePDF SDK is your choice

Foxit is an Amazon-invested leading software provider of solutions for reading, editing, creating, organizing, and securing PDF documents. Foxit PDF SDK libraries have been used in many of today’s leading apps, and they are proven, robust, and battle-tested to provide the quality, performance, and features that the industry’s largest apps demand. Foxit MobilePDF SDK is a new SDK product which is developed for providing quick PDF viewing and manipulation support for mobile platforms. Customers choose it for the following reasons:

  • Easy to integrate
    Developers can seamlessly integrate Foxit MobilePDF SDK into their own apps with just a few lines of code.
  • Perfectly designed
    Foxit MobilePDF SDK is designed with a simple, clean, and friendly style, which provides the best user experience.
  • Flexible customization
    Foxit MobilePDF SDK provides the source code for the user interface which lets the developers have full control of the functionality and appearance of their apps.
  • Robust performance on mobile platforms
    Foxit MobilePDF SDK provides an OOM (out-of-memory) recovery mechanism to ensure the app has high robust performance when running the app on a mobile device which offers limited memory.
  • Powered by Foxit’s high fidelity rendering PDF engine
    The core technology of Foxit MobilePDF SDK is based on Foxit’s PDF engine, which is trusted by a large number of the world’s largest and well-known companies. Foxit’s powerful engine makes the app fast on parsing, rendering, and makes document viewing consistent on a variety of devices.
  • Premium World-side Support
    Foxit offers premium support for its developer products because when you are developing mission critical products you need the best support. Foxit has one of the PDF industry’s largest team of support engineers. Updates are released on a regular basis to improve user experience by adding new features and enhancements.

Foxit MobilePDF SDK

Foxit MobilePDF SDK is a Rapid Development Kit for mobile platforms which focuses on helping developers easily integrate powerful Foxit PDF technology into their own apps. With Foxit MobilePDF SDK, even developers with a limited knowledge of PDF can quickly build a professional PDF viewer with just a few lines of code on iOS and Android platforms.

Foxit MobilePDF SDK consists of three elements as shown in the following picture.

The three elements for FoxitMobilePDF SDK

  • PDF Core API
    The PDF Core API is the heart of this SDK and is built on Foxit’s powerful underlying technology. It provides the functionality for basic PDF operation features, and is utilized by the PDF View Control 0.and UI Extensions Component, which ensures the apps can achieve high performance and efficiency. The Core API can be used independently for document rendering, analysis, text extraction, text search, form filling, digital signatures, Pressure Sensitive Ink, certificate and password security,
    annotation creation and manipulation and much more.
  • PDF View Control
    The PDF View Control is a utility class that provides the functionality for developers to interact with rendering PDF documents per their requirements. With Foxit’s renowned and widely used PDF rendering technology at its core, the View Control provides fast and high quality rendering, zooming, scrolling and page navigation features. The View Control derives from platform related viewer classes (e.g. UIView on iOS and Android.View.ViewGroup on Android) and allows for extension to accommodate specific user needs.
  • UI Extensions Component
    The UI Extensions Component is an open source library that provides a customizable user interface with built-in support for text selection, markup annotation, outline navigation, reading bookmarks, full-text searching, form filling, text reflow, attachment, digital/handwritten signature, reflow, document editing and password encryption. These features in the UI Extensions Component are implemented using the PDF Core API and PDF View Control. Developers can utilize these ready-to-use UI implementations to build a PDF viewer quickly with the added benefit of complete flexibility and control to customize the UI design as desired.

From version 4.0, Foxit MobilePDF SDK makes a big change and optimization for the UI Extensions Component. It wraps the basic UI implementations to PDFReader class, such as panel controller, toolbar settings, and alert view, etc. Building a full-featured PDF Reader is getting simpler and easier. Furthermore, users can flexibly customize the features they want through a configuration file.

From version 5.0, every element in the built-in UI can be configurable through an API. Foxit MobilePDF SDK provides more advanced APIs in PDFReader class for developers to further customize the UI elements, such as adding/removing a button to/from the toolbar, showing/hiding a specific menu/function panel, and etc.

Key Features

Foxit MobilePDF SDK has several main features which help app developers quickly implement the functions that they really need and reduce the development cost.

Features

PDF Document: Open and close files, set and get metadata.

PDF Page: Parse, render, read, and edit PDF pages.

Render: Graphics engine created on a bitmap for platform graphics device.

Reflow: Rearrange page content.

Crop: Crop PDF pages for better reading.

Text Select: Select text in a PDF document.

Text Search: Search text in a PDF document.

Outline: Directly locate and link to point of interest within a document.

Reading Bookmark: Mark progress and interesting passages as users read.

Annotation: Create, edit and remove annotations.

Layers: Add, edit and remove optional content groups.

Attachments: Add, edit and remove document level attachments.

Form: Fill form with JavaScript support, export and import form data by XFDF/FDF/XML file.

Signature: Sign a PDF document, verify a signature, add or delete a signature field. Add and verify third-party digital signature.

Security: Protect PDFs with password or certificate.

Out of Memory: Recover from an OOM condition.

Note: Outline is the technical term used in the PDF specification for what is commonly known as bookmarks in traditional desktop PDF viewers. Reading bookmarks are commonly used on mobile and tablet PDF viewers to mark progress and interesting passages as users read but are not technically outline and are stored at app level rather than within the PDF itself.

Evaluation

Foxit MobilePDF SDK allows users to download trial version to evaluate SDK. The trial version has no difference from the standard licensed version except for the free 21-day trial limitation and the trial watermarks in the generated pages. After the evaluation period expires, customers should contact the Foxit sales team and purchase licenses to continue using Foxit MobilePDF SDK.

License

Developers should purchase licenses to use Foxit MobilePDF SDK in their solutions. Licenses grant developers permission to release their apps which utilize Foxit MobilePDF SDK. However, users are prohibited to distribute any documents, sample code, or source code in the released package of Foxit MobilePDF SDK to any third party without written permission from Foxit Software Incorporated.

About this Guide

Foxit MobilePDF SDK is currently available on iOS and Android platforms. This guide is intended for the developers who need to integrate Foxit MobilePDF SDK for Android into their own apps. It aims at introducing the following sections:

  • Introduction to Foxit Mobile PDF: gives an introduction of Foxit MobilePDF SDK.
  • Getting Started: illustrates the package structure, running demo, and adding PDF SDK into app.
  • Rapidly Building a full-featured PDF Reader: describes how to quickly create a full-featured PDF Reader.
  • Customizing the UI Implementation: introduces how to customize the UI implementation.
  • Creating a Custom Tool: shows how to create a custom tool.
  • Technical Support: provides support information.

Note:

  • In section 2, it shows you how to call Foxit MobilePDF SDK APIs to realize some specific features, which does not use the default reader provided in version 5.0. In this case, you should take a lot of effort to design the app’s UI and implement related functions.
  • In section 3, it shows you how to quickly build a full-featured PDF Reader with the default reader provided in version 5.0. In this case, you do not need to take much time to design the UI of your app, and you can flexibly customize the features you want through a configuration file.

Getting Started

It is very easy to setup Foxit MobilePDF SDK and see it in action! It takes just a few minutes and we will show you how to use it on the Android platform. The following sections introduce the structure of the installation package, how to run a demo, and how to create your own project in Android Studio.

Note: The following section 2.4 will show you how to make an Android app using Foxit MobilePDF SDK. It helps you to quickly get started to call the APIs to realize some specific features, which does not use the default reader provided in version 4.0. If you want to quickly build a full-featured PDF Reader, please see section Rapidly Building a full-featured PDF Reader directly.

System Requirements

Android device’s requirements:

  • Android 4.x
  • 32/64-bit ARM (armeabi-v7a/arm64-v8a) or 32-bit Intel x86 CPU

Android 2.1.1 or newer (Support AAR based build system: Gradle 2.1.0 or later)

The runtime environment for our demos:

  • Android Studio 2.2.3
  • JDK 1.8
  • Gradle Version 3.2
  • Gradle Build Tool 2.2.3

What’s in the package

Download the “foxit_mobile_pdf_sdk_android_en.zip” package, and extract it to a new directory like
“foxit_mobile_pdf_sdk_android_en” as shown in Figure 2-1. The package contains:

  • docs: A folder containing API references, developer guide.
  • libs: A folder containing license files, .so libraries, Jar, AAR files, and UI Extensions Component source code.
  • samples: A folder containing Android sample projects.
  • getting_started_android.pdf: A quick guide for Foxit MobilePDF SDK for Android.
  • legal.txt: Legal and copyright information.
  • release_notes.txt: Release information.

Figure 2-1

In the “libs” folder as shown in Figure 2-2, there are items that make up the core components of Foxit MobilePDF SDK for Android.

Figure 2-2

  • librdk.so (libs/armeabi-v7a, libs/arm64-v8a, libs/x86) – called by the Java APIs in the FoxitRDK.jar. It is the heart of the SDK and contains the core functionalities of Foxit MobilePDF SDK, and it is built separately for each architecture. Currently it is available for armeabi-v7a, arm64-v8a, and x86.
  • FoxitRDK.jar– used by the Java platform. It includes all the Java APIs of Foxit MobilePDF SDK.
  • FoxitRDKUIExtensions.aar – generated by the “uiextensions_src” project found in the “libs” folder. It includes the FoxitRDK.jar, built-in UI implementation, and resource files that are needed for the built-in UI implementations, such as images, strings, color values, layout files, and other Android UI resources.
  • uiextensions_src project – found in the “libs” folder. It is an open source library that contains some ready-to-use UI module implementations, which can help developers rapidly embed a fully functional PDF reader into their Android app. Of course, developers are not forced to use the default UI, they can freely customize and design the UI for their specific apps through the “uiextensions_src” project.

At this point you should just be getting a feel for what Foxit MobilePDF SDK package looks like, we’re going to cover everything in detail in a bit.

How to run a demo

Download and install Android Studio IDE (https://developer.android.com/studio/index.html).

Note: In this guide, we do not cover the installation of Android Studio, Android SDK, and JDK. You can refer to Android Studio’s developer site if you haven’t installed it already.

Foxit MobilePDF SDK provides three useful demos for developers to learn how to call the SDK as shown in Figure 2-3.

Figure 2-3

Function demo

The function demo is provided to show how to use Foxit MobilePDF SDK to realize some specific features related to PDF with PDF core API. This demo includes the following features:

  • pdf2txt: extract text from a PDF document to a TXT file.
  • outline: edit outline (aka bookmark) appearances and titles.
  • annotation: add annotations to a PDF page.
  • docinfo: export document information of a PDF to a TXT file.
  • render: render a specified page to Bitmap.
  • signature: add a signature to PDF, sign PDF and verify the signature.

To run it in Android Studio, follow the steps below:

a) Load the demo in Android Studio through “File ->; New ->; Import Project…” or “File ->; Open…”, and then navigate to where the function_demo project is stored and select the function_demo folder. Continue with “OK”.

b) Launch an Android device or an emulator (AVD). Open the Android Device Monitor, select the device or emulator that has just been launched and create a new folder named “input_files”under the “mnt/sdcard”(a soft link), then you can find the created folder under the “storage/sdcard”. Push the five test files found in the “samples/test_files” folder into this folder. In this guide, an AVD targeting 4.4.2 will be used as an example. Then, the added PDF files will be displayed in “storage/sdcard/input_files” (see Figure 2-4).
Note: For some Android device, maybe you can only find sdcard0, or sdcard1, such as these. The name of the sdcard is not important, just make sure you have created an “input_files” folder in your device’s storage card and pushed the test files into this folder.

Figure 2-4

c) Click on “Run ->; Run ‘app'” to run the demo. After building the demo successfully, the features are listed like Figure 2-5.
Note: when running the demo, if you encounter an error like “Error running app: Instant Run requires ‘Tools|Android|Enable ADB integration’ to be enabled”, just follow the prompt to enable the ADB integration in “Tools ->; Android ->; Enable ADB integration.

Figure 2-5

d) Click the feature buttons in the above picture to perform the corresponding actions. For example, click “pdf2txt”, and then a message box will be popped up as shown in Figure 2-6. It shows where the text file was saved to. Just run the demo and try the features.

Figure 2-6

Viewer control demo

The viewer control demo demonstrates how to implement the features related to the View Control feature level, such as performing annotations (note, highlight, underline, strikeout, squiggly, etc.), changing layout, text search, outline, and page thumbnail. The logical structure of the code is quite clear and simple so that developers can quickly find the detailed implementation of features which are used widely in PDF apps, such as a PDF viewer. With this demo, developers can take a closer look at the APIs provided in Foxit MobilePDF SDK.

To run the demo in Android Studio, please refer to the setup steps outlined in the Function demo.

This demo will use the “Sample.pdf” (found in the “samples/test_files” folder) as the test file, please make sure you have pushed this file into the created folder “input_files” of Android device or emulator before running this demo.

Figure 2-7 shows what the demo looks like after it was built successfully. Here, an AVD targeting 4.4.2 will be used as an example to run the demo.

Figure 2-7

Click anywhere in the page, then the Contextual Action bar will appear, you can click at the actions items menu button:And see more action items as shown in Figure 2‑8.

Figure 2-8

Now we can choose one item to perform the action and see the result. For example, click “Outline”, then you will see the outline (outline is the technical term for bookmark in the PDF specification) of the document as shown in Figure 2-9. Try using the other features to see it in action.

Figure 2-9

Complete PDF viewer demo

The complete PDF viewer demo demonstrates how to use Foxit MobilePDF SDK to realize a completely full-featured PDF viewer which is almost ready-to-use as a real world mobile PDF reader. This demo utilizes all of the features and built-in UI implementations which are provided in Foxit MobilePDF SDK.

To run the demo in Android Studio, please refer to the setup steps outlined in the Function demo. Here, an AVD targeting 4.4.2 will also be used as an example to run the demo. After building the demo successfully, on the start screen, it lists the “complete_pdf_viewer_guide_android.pdf” and
“Sample.pdf” documents (see Figure 2-10).

Note: The “complete_pdf_viewer_guide_android.pdf” and “Sample.pdf” documents will be automatically deployed to your device so that you don’t need to push them into the device manually. But if you want to use some other PDF files to test this demo, you should push them into the device’s SD card.

Figure 2-10

Click the “complete_pdf_viewer_guide_android.pdf” document, and then it will be opened and displayed as shown in Figure 2-11.

Figure 2-11

This demo realizes a completely full-featured PDF viewer, please feel free to run it and try it.

For example, it provides the page thumbnail feature. You can click the View menu, choose the Thumbnail as shown in Figure 2-12, and then the thumbnail of the document will be displayed as shown in Figure 2-13.

 

Figure 2-12

Figure 2-13

How to make an Android app with Foxit MobilePDF SDK

This section will help you to quickly get started with using Foxit MobilePDF SDK to make an Android app with step-by-step instructions provided. From now, you can get familiar with Foxit MobilePDF SDK and create your first PDF Android app in Android Studio. This section includes the following steps:

a) Create a new Android project
b) Integrate Foxit MobilePDF SDK into your apps
c) Apply the license key
d) Display a PDF document
e) Add support for Form Filling
f) Add support for Text Search
g) Add support for Outline
h) Add support for Annotations

Create a new Android project

In this guide, we use Android Studio 2.1.1, along with Android API revision 23.

Open Android Studio, choose File -> New -> New Project… to start the Create New Project wizard, and then fill the New Project dialog as shown in Figure 2-14. After filling, click Next.

Figure 2-14

In the Target Android Devices dialog, select “Phone and Tablet” to run your app, and set the Minimum SDK to API 8, which is shown in Figure 2-15. Then, click Next.

Figure 2-15

In the Add an activity to Mobile dialog, select “Empty Activity” (for some other Android Studio versions, it might be “Blank Activity”) as shown in Figure 2-16, and then click Next.

Figure 2-16

In the Customize the Activity dialog, customize your activity as desired, here, we use the default setting as shown in Figure 2-17, and then click Finish.

Figure 2-17

Integrate Foxit MobilePDF SDK into your apps

Note: In this section, we will use the default built-in UI implementation to develop the app, for simplicity and convenience, we only need to add the following files to the Test_android project.

  • FoxitRDKUIExtensions.aar – generated by the “uiextensions_src” project found in the “libs”folder. It includes the FoxitRDK.jar, built-in UI implementations, and resource files that are needed for the built-in UI implementations, such as images, strings, color values, layout files, and other Android UI resources.
  • librdk.so (libs/armeabi-v7a, libs/arm64-v8a, libs/x86) – called by Java APIs in the FoxitRDK.jar. It is the heart of the SDK containing the core functionalities of Foxit MobilePDF SDK, and built separately for each architecture. Currently it is available for armeabi-v7a, arm64-v8a, and x86.

Note: For this project, we will run the project on an emulator with x86 architecture, so we just add the “x86/librdk.so” library into the project. If you are not clear about the architecture of the device you want to use, you can add all of the “.so” libraries, because the linker can distinguish the device’s architecture and then choose the proper library.

To add the above two files into Test_android project, please switch to the “Project” view panel and then follow the steps below:

a) Copy and paste the “FoxitRDKUIExtensions.aar” file from the “libs” folder of the download package to “Test_android\app\libs” folder.

b) Copy and paste the “librdk.so” file from the “libs\x86” folder of the download package to “Test_android\app\libs\x86” (note that you might need to create this folder by yourself).

Then, the project should look like Figure 2-18.

Figure 2-18

c) Add a reference to the “librdk.so”. Inside the app’s “build.gradle” file, add the following configuration:

build.gradle:

android {
 
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}

d) Include Foxit MobilePDF SDK as a dependency in the project by setting up the App module in the”build.gradle” file as follows:

First, define the “libs” directory as a repository in the app’s “build.gradle” repositories section.

build.gradle:

repositories {
 
    flatDir {
        dirs 'libs'
    }
}

And then, add “FoxitRDKUIExtensions.aar” to the dependencies.

dependencies {
 
    compile (name:'FoxitRDKUIExtensions', ext:'aar')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
}

After setting the app’s “build.gradle” file, sync it, then the “FoxitRDKUIExtensions” will appear in External Libraries as shown in Figure 2-19.

Note: Foxit MobilePDF SDK has a dependency on recyclerview support library, so you should add it to the dependencies. Here, ‘com.android.support:design:23.4.0’ has already included the recyclerview package. Or you can add “compile ‘com.android.support:recyclerview-v7:23.4.0’” directly.

Figure 2-19

The following code shows “build.gradle” in its entirety.

build.gradle:

apply plugin: 'com.android.application'
 
android {
    compileSdkVersion 23
    buildToolsVersion "23.0.2"
 
    defaultConfig {
        applicationId "com.foxit.test_android"
        minSdkVersion 16
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}
 
repositories {
 
    flatDir {
        dirs 'libs'
    }
}
 
dependencies {
 
    compile (name:'FoxitRDKUIExtensions', ext:'aar')
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:design:23.4.0'
    compile 'com.android.support:appcompat-v7:23.4.0'
}

 

Note: So far, we set the compileSdkVersion and targetSdkVersion to API 23. If you also want to use API 23, please make sure you have already installed the SDK Platform Android 6.0, API 23. If you have not already done this, open the Android SDK Manager to download and install it first.

Apply the license key

It is necessary for apps to initialize and unlock Foxit MobilePDF SDK using a license before calling any APIs. The function Library.init (sn, key) is provided to initialize Foxit MobilePDF SDK. The trial license files can be found in the “libs” folder of the download package. After the evaluation period expires, you should purchase an official license to continue using it. Below you can see an example of how to unlock the SDK library. The next section will show where to include this code in the Test_android project.

import com.foxit.sdk.common.Library;
import com.foxit.sdk.common.PDFException;
static {
    System.loadLibrary("rdk");
}
...
 
try {
    Library.init("sn", "key");
 
} catch (PDFException e) {
    e.printStackTrace();
    return;
}

Note: The parameter “sn” can be found in the “rdk_sn.txt” (the string after “SN=”) and the “key” can be found in the “rdk_key.txt” (the string after “Sign=”).

Display a PDF document

So far, we have just created an Android app with a blank activity. Now, let’s start building a simple PDF viewer with just a few lines of code.

Note: The UI Extensions Component is not required if you only want to display a PDF document.

To display a PDF document, you should add the PDF View Control to show the PDF in the “activity_main.xml” found in the “app/src/main/res/layout”.

Update activity_main.xml as follows:

< ?xml version="1.0" encoding="utf-8"?>

In the “MainActivity.java”, instantiate a PDFDoc object to load an existing PDF document (“/mnt/sdcard/input_files/Sample.pdf“); and instantiate a PDFViewCtrl object to show the document.

Note: By default, the MainActivity extends AppCompatActivity. We change it to extend FragmentActivity, because the UI Extensions Component which will be utilized in the next section has used the features in the FragmentActivity. In addition, please make sure you have pushed the “Sample.pdf” document into the created folder “input_files” of the Android device or emulator that will be used to run this project.

Update MainActivity.java as follows:

package com.foxit.test_android;
 
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
 
import com.foxit.sdk.common.Library;
import com.foxit.sdk.common.PDFException;
 
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.pdf.PDFDoc;
 
public class MainActivity extends FragmentActivity {
 
    private PDFViewCtrl pdfViewCtrl = null;
 
    // Load "librdk.so" library.
    static {
        System.loadLibrary("rdk");
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // The value of "sn" can be found in the "rdk_sn.txt".
        // The value of "key" can be found in the "rdk_key.txt".
        String sn = " ";
        String key = " ";
 
        try {
            // initialize the library
            Library.init(sn, key);
        } catch (PDFException e) {
            e.printStackTrace();
            return;
        }
 
        // Inflate the view and get a reference to PDFViewCtrl
        setContentView(R.layout.activity_main);
        pdfViewCtrl = (PDFViewCtrl) findViewById(R.id.pdfviewer);
 
        // Load a document
        String path = "/mnt/sdcard/input_files/Sample.pdf";
        try {
            PDFDoc document = PDFDoc.createFromFilePath(path);
            document.load(null);
            pdfViewCtrl.setDoc(document);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            Library.release();
        } catch (PDFException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onResume() {
    super.onResume();
    if(pdfViewCtrl != null)
        pdfViewCtrl.requestLayout();
    }
}

Set the “users-permission” in the “AndroidManifest.xml” found in the “app/src/main” to give the project permission to write and read the SD card of the Android devices or emulators.

Update the AndroidManifest.xml as follows:

< ?xml version="1.0" encoding="utf-8"?>

 

Note: If you want to run this project on an Android 6.0 (API 23) or higher devices/emulators, you need to write some additional code to require the authorization of runtime permissions, or you can change the targetSdkVersion in app’s “build.gradle” from 23 to the SDK version that is just less than 23, such as 21.

The following code snippets can be used as a reference for you to require the authorization of runtime permissions:

// Check whether the device or emulator has the permission to access the external storage.
    if (ContextCompat.checkSelfPermission(this,
            Manifest.permission.READ_EXTERNAL_STORAGE)
            != PackageManager.PERMISSION_GRANTED) {
 
        // If has no permission, then request the permission.
        ActivityCompat.requestPermissions(this,
                new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
                REQUEST_CODE);
    } else {
        viewDoc();
    }
}
 
// Define a request code.
private static final int REQUEST_CODE = 1;
 
// Handle the request after user responds to the request in the dialog.
@Override
public void onRequestPermissionsResult(int requestCode,
                                       String permissions[], int[] grantResults) {
    switch (requestCode) {
        case REQUEST_CODE: {
            // 1.If the request is cancelled, the result array is empty.
 
            // 2.The permission was granted.
            if (grantResults.length > 0
                    && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
 
                //  Do the task you need to do.
 
            } else {
 
                // permission was denied. Disable the functionality that depends on this permission.
            }
            return;
        }
    }
}

Fantastic! We have now finished building a simple Android app which uses Foxit MobilePDF SDK to display a PDF document with just a few lines of code. The next step is to run the project on a device or emulator.

In this section, we build and run the project on an AVD targeting Android 4.4.2 (API 19), and you will see that the “Sample.pdf” document is displayed as shown in Figure 2-20. Now, this sample app has some basic PDF features, such as zooming in/out and page turning. Just have a try!

Figure 2-20

Add support for Form Filling

Foxit MobilePDF SDK comes with built-in support for features such as annotations, text search, outline and form filling. These visual features are implemented using Foxit MobilePDF SDK API and are shipped in the UI Extensions Component.

The form filling feature is already provided in the UI Extensions Component. It’s simple and easy to integrate it into your app. For annotations, text search and outline support, you can refer to the following sections.

In the previous sections, we have introduced how to add Foxit MobilePDF SDK to a project and how to  build a simple Android app for displaying a PDF document. Now, let’s extend the simple app (Test_android) further to learn how to add support for form filling.

First, let’s do a test. Prepare a PDF form file, and push it into the created folder “input_files” of the emulator’s SD card. For example, we use a PDF form file called “FoxitForm.pdf” found in the “samples/test_files” folder of the download package.

Open “MainActivity.java”, only change the file name from “Sample.pdf” to “FoxitForm.pdf” as follows:

String path = “/mnt/sdcard/input_files/FoxitForm.pdf”;

Then rebuild and run the project, and you will see that the “FoxitForm.pdf” is displayed as shown in Figure 2-21. Now, it is just like a normal PDF file, in which the form fields cannot be edited.

Figure 2-21

Next, let’s add support for form filling. It’s extremely easy! The key point is to instantiate a
UIExtensionsManager object and set it to PDFViewCtrl.

Add code to instantiate a UIExtensionsManager object and set it to PDFViewCtrl

Just follow the steps below:

a) In the “activity_main.xml” file, add an “id” to the layout like below:

activity_main.xml:

< ?xml version="1.0" encoding="utf-8"?>

b) In the “MainActivity.java” file, we are now going to add the code necessary for including the UIExtensionsManager. The required code additions are shown below and further down you will find  a full example of what the “MainActivity.java” file should look like.

Import the following classes

import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
 
import com.foxit.uiextensions.UIExtensionsManager;

Instantiate a RelativeLayout object to get the parent layout.

private RelativeLayout parent = null;
...
parent = (RelativeLayout) findViewById(R.id.parentLayout);

Instantiate a UIExtensionsManager object and set it to PDFViewCtrl.

private UIExtensionsManager uiextensionsManager = null;
...
uiextensionsManager = new UIExtensionsManager (this.getApplicationContext(),parent, pdfViewCtrl);
uiextensionsManager.setAttachedActivity(this);
pdfViewCtrl.setUIExtensionsManager(uiextensionsManager);

The whole update of “MainActivity.java” is as follows:

package com.foxit.test_android;
 
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
 
import com.foxit.sdk.common.Library;
import com.foxit.sdk.common.PDFException;
 
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.pdf.PDFDoc;
 
import com.foxit.uiextensions.UIExtensionsManager;
 
public class MainActivity extends FragmentActivity {
 
    private PDFViewCtrl pdfViewCtrl = null;
    private RelativeLayout parent = null;
    private UIExtensionsManager uiextensionsManager = null;
 
    // Load "librdk.so" library.
    static {
        System.loadLibrary("rdk");
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // The value of "sn" can be found in the “rdk_sn.txt”.
        // The value of "key" can be found in the “rdk_key.txt”.
        String sn = " ";
        String key = " ";
 
        try {
            // initialize the library.
            Library.init(sn, key);
        } catch (PDFException e) {
            e.printStackTrace();
            return;
        }
 
        // Inflate the view and get a reference to PDFViewCtrl.
        setContentView(R.layout.activity_main);
        pdfViewCtrl = (PDFViewCtrl) findViewById(R.id.pdfviewer);
 
        parent = (RelativeLayout) findViewById(R.id.parentLayout);
 
    	// Instantiate a UIExtensionsManager object and set it to PDFViewCtrl.
        uiextensionsManager = new UIExtensionsManager(this.getApplicationContext(), parent, pdfViewCtrl);
	uiextensionsManager.setAttachedActivity(this);
        pdfViewCtrl.setUIExtensionsManager(uiextensionsManager);
        // Load a document.
        String path = "/mnt/sdcard/input_files/FoxitForm.pdf";
        try {
            PDFDoc document = PDFDoc.createFromFilePath(path);
            document.load(null);
            pdfViewCtrl.setDoc(document);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            Library.release();
        } catch (PDFException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        if (pdfViewCtrl != null)
            pdfViewCtrl.requestLayout();
    }
}

Now let’s rebuild and run the project, and the “FoxitForm.pdf” will be displayed as shown in Figure 2-22. You can find that the Figure 2-22 is already different from the Figure 2-21. It means the form filling feature is available at present. Feel free to edit the form, such as Figure 2-23.

Figure 2-22

Figure 2-23

Amazing! We have realized the form filling feature in the test_android project without adding any extra code related to forms. Alright, it is just a simple example which allows you to fill a PDF Form file, for further research about form, you can refer to the “complete_pdf_viewer” demo.

Text search, outline, annotations and related features are associated more closely with the user interface and as such require a slightly different approach from the form filling feature. We need to write some extra code to load the feature module and trigger the feature.

In this section, we will add support for text search and also extend the simple Android app in the section “Displaying a PDF document“. For outline and annotations, you can refer to the “Add support for Outline” and “Add support for Annotations” sections.

For simplicity, we will add a button on the main interface and use the button click event to quickly experience the text search feature. Just follow the steps below:

a) Refer to “Add code to instantiate a UIExtensionsManager object and set it to PDFViewCtrl” in the section “Add support for Form Filling” to add the same code in the Test_android project.

b) In the “activity_main.xml” file, add a button like below:

activity_main.xml:

< ?xml version="1.0" encoding="utf-8"?>
 
 
 
<button></button>

c) In the “MainActivity.java” file, implement the text search feature in the button click event.

First, set the system theme to “No Title” mode and set the window to Fullscreen.

Note: The UI Extensions Component has customized the user interface, so you need to set the system theme to “No Title” mode and set the window to Fullscreen. Otherwise, the layout of the built-in features might be affected.

// Turn off the title at the top of the screen.
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the window to Fullscreen.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

Import the following classes:

import android.view.View;
import android.widget.Button;
import com.foxit.uiextensions.modules.SearchModule;
import com.foxit.uiextensions.modules.SearchView;

Instantiate a Button object and add the click event. Then, instantiate a SearchModule object to load a search module, and instantiate a SearchView object to start a search.

private Button btn_search = null;
private SearchModule searchModule = null;
private SearchView searchView = null;
...
btn_search = (Button) findViewById(R.id.search_button);
...
// Search button click event
public void Search_Click(View view) {
    searchModule = (SearchModule)uiextensionsManager.getModuleByName(Module.MODULE_NAME_SEARCH);
    if (searchModule == null) {
        searchModule = new SearchModule(this, parent, pdfViewCtrl, uiextensionsManager);
        searchModule.loadModule();
    }
    searchView = searchModule.getSearchView();
    searchView.show();
}

The whole update of “MainActivity.java” is as follows:

package com.foxit.test_android;
 
import android.support.v4.app.FragmentActivity;
import android.os.Bundle;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.view.View;
import android.widget.Button;
 
import com.foxit.sdk.common.Library;
import com.foxit.sdk.common.PDFException;
 
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.pdf.PDFDoc;
 
import com.foxit.uiextensions.UIExtensionsManager;
import com.foxit.uiextensions.modules.SearchModule;
import com.foxit.uiextensions.modules.SearchView;
 
public class MainActivity extends FragmentActivity {
 
    private PDFViewCtrl pdfViewCtrl = null;
    private RelativeLayout parent = null;
    private UIExtensionsManager uiextensionsManager = null;
    private SearchModule searchModule = null;
    private SearchView searchView = null;
    private Button btn_search = null;
 
    // Load "librdk.so" library.
    static {
        System.loadLibrary("rdk");
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // The value of "sn" can be found in the “rdk_sn.txt”.
        // The value of "key" can be found in the “rdk_key.txt”.
        String sn = " ";
        String key = " ";
 
        try {
            // initialize the library.
            Library.init(sn, key);
        } catch (PDFException e) {
            e.printStackTrace();
            return;
        }
 
        // Turn off the title at the top of the screen.
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // Set the window to Fullscreen.
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
 
        // Inflate the view and get a reference to PDFViewCtrl.
        setContentView(R.layout.activity_main);
        pdfViewCtrl = (PDFViewCtrl) findViewById(R.id.pdfviewer);
 
        parent = (RelativeLayout) findViewById(R.id.parentLayout);
        btn_search = (Button) findViewById(R.id.search_button);
 
    	// Instantiate a UIExtensionsManager object and set it to PDFViewCtrl.
        uiextensionsManager = new UIExtensionsManager(this.getApplicationContext(), parent, pdfViewCtrl);
	uiextensionsManager.setAttachedActivity(this);
        pdfViewCtrl.setUIExtensionsManager(uiextensionsManager);
 
        // Load a document.
        String path = "/mnt/sdcard/input_files/Sample.pdf";
        try {
            PDFDoc document = PDFDoc.createFromFilePath(path);
            document.load(null);
            pdfViewCtrl.setDoc(document);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    // Search button click event
    public void Search_Click(View view) {
searchModule = (SearchModule)uiextensionsManager.getModuleByName(Module.MODULE_NAME_SEARCH);
        if (searchModule == null) {
            searchModule = new SearchModule(this, parent, pdfViewCtrl, uiextensionsManager);
            searchModule.loadModule();
        }
        searchView = searchModule.getSearchView();
        searchView.show();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            Library.release();
        } catch (PDFException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        if (pdfViewCtrl != null)
            pdfViewCtrl.requestLayout();
    }
}

Note: For this project, we use “Sample.pdf” as the test file. You can use any PDF file, just remember to push it onto the Android device or Emulator, and change the file path in “MainActivity.java”.

Now that we have finished adding support for text search into the project, let’s build and run it. You will see that the “Sample.pdf” document is automatically displayed (see Figure 2-24).

Note: when running the project, if you encounter an error like “Error running app: Instant Run requires ‘Tools|Android|Enable ADB integration’ to be enabled”, just follow the prompt to enable the ADB integration in “Tools -> Android -> Enable ADB integration“.

Figure 2-24

Click the “Search” button, you can search anything you like. For example, input “Foxit”, press “Enter”, and then all of the search results will be listed as shown in Figure 2-25.

Figure 2-25

Click any result or any page entry in the list to jump to the specific location. Here, we click the “Page 2″entry in the list, and then it will jump to the corresponding page and the first matched word will be highlighted as shown in Figure 2-26. You can click the previous or next button to find the previous or next search result.

Figure 2-26

Add support for Outline

Adding support for outline is similar to the previous section “Add support for Text Search”. In this section, we will still extend the simple Android app in the “Displaying a PDF document“.

For simplicity, we will also add a button on the main interface and use the button click event to quickly experience the outline feature. Just follow the steps below:

a) Refer to “Add code to instantiate a UIExtensionsManager object and set it to PDFViewCtrl” in the section “Add support for Form Filling” to add the same code in the Test_android project.

b) In the “activity_main.xml” file, add a button like below:

activity_main.xml:

&lt; ?xml version="1.0" encoding="utf-8"?&gt;
 
 
 
<button></button>

 

c) In the “MainActivity.java” file, implement the outline feature in the button click event.

First, set the system theme to “No Title” mode and set the window to Fullscreen.

Note: The UI Extensions Component has customized the user interface, so you need to set the system theme to “No Title” mode and set the window to Fullscreen. Otherwise, the layout of the built-in features might be affected.

// Turn off the title at the top of the screen.
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the window to Fullscreen.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

Import the following classes:

import android.view.View;
import android.widget.Button;
 
import com.foxit.uiextensions.modules.OutlineModule;

Instantiate a Button object and add the click event. Then, instantiate an OutlineModule object to load the outline module.

private Button btn_outline = null;
private OutlineModule outlineModule = null;
...
btn_search = (Button) findViewById(R.id.search_button);
 
outlineModule = (OutlineModule) uiextensionsManager.getModuleByName(Module.MODULE_NAME_OUTLINE);
if (outlineModule == null){
    outlineModule = new OutlineModule(this, parent, pdfViewCtrl, uiextensionsManager);
    outlineModule.loadModule();
}
...
// Outline button click event
public void Outline_Click(View view) {
    btn_search.setVisibility(view.GONE);
    if (outlineModule != null)
        outlineModule.show();
}

The whole updated of “MainActivity.java” is as follows:

package com.foxit.test_android;
 
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.view.View;
import android.widget.Button;
 
import com.foxit.sdk.common.Library;
import com.foxit.sdk.common.PDFException;
 
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.pdf.PDFDoc;
import com.foxit.uiextensions.UIExtensionsManager;
import com.foxit.uiextensions.modules.OutlineModule;
 
public class MainActivity extends FragmentActivity {
 
    private PDFViewCtrl pdfViewCtrl = null;
    private RelativeLayout parent = null;
    private UIExtensionsManager uiextensionManager = null;
    private OutlineModule outlineModule = null;
    private Button btn_outline = null;
 
    // Load "librdk.so" library.
    static {
        System.loadLibrary("rdk");
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // The value of "sn" can be found in the “rdk_sn.txt”.
        // The value of "key" can be found in the “rdk_key.txt”.
        String sn = " ";
        String key = " ";
 
        try {
            // initialize the library
            Library.init(sn, key);
        } catch (PDFException e) {
            e.printStackTrace();
            return;
        }
 
        // Turn off the title at the top of the screen.
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // Set the window to FullScreen.
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
 
        // Inflate the view and get a reference to PDFViewCtrl.
        setContentView(R.layout.activity_main);
        pdfViewCtrl = (PDFViewCtrl) findViewById(R.id.pdfviewer);
 
        parent = (RelativeLayout) findViewById(R.id.parentLayout);
        btn_outline = (Button) findViewById(R.id.outline_button);
 
        // Initialize a UIExtensionsManager object and set it to PDFViewCtrl.
        uiextensionsManager = new UIExtensionsManager(this.getApplicationContext(), parent, pdfViewCtrl);
	uiextensionsManager.setAttachedActivity(this);
        pdfViewCtrl.setUIExtensionsManager(uiextensionsManager);
 
        // Initialize an OutlineModule object to load the outline module.
        outlineModule = (OutlineModule) uiextensionsManager.getModuleByName(Module.MODULE_NAME_OUTLINE);
        if (outlineModule == null){
            outlineModule = new OutlineModule(this, parent, pdfViewCtrl, uiextensionsManager);
            outlineModule.loadModule();
        }
 
        // Load a document.
        String path = "/mnt/sdcard/input_files/Sample.pdf";
        try {
            PDFDoc document = PDFDoc.createFromFilePath(path);
            document.load(null);
            pdfViewCtrl.setDoc(document);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    // Outline button click event
    public void Outline_Click(View view) {
       btn_outline.setVisibility(view.GONE);
        if (outlineModule != null)
            outlineModule.show();
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            Library.release();
        } catch (PDFException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        if (pdfViewCtrl != null)
            pdfViewCtrl.requestLayout();
    }
}

Note: For this project, we use “Sample.pdf” as the test file. You can use any PDF file, just remember to push it onto the Android device or Emulator, and change the file path in “MainActivity.java”.

Now that we have finished adding support for outline into the project, let’s build and run it. You will see that the “Sample.pdf” document is automatically displayed (see Figure 2-27).

Note: when running the project, if you encounter an error like “Error running app: Instant Run requires ‘Tools|Android|Enable ADB integration’ to be enabled”, just follow the prompt to enable the ADB integration in “Tools -> Android -> Enable ADB integration”.

Figure 2-27

Click the “Outline” button, you can see the outline (outline is the technical term for bookmark in the PDF specification) of the document as shown in Figure 2-28. Now, you can tap the outline to jump to the specific chapter.

Note: From version 5.0, the “Reading Bookmarks”, “Outline”, “Annotations” and “Attachments” panels are grouped together. If you want to remove one of the panels, you should use a configuration file to initialize UIExtensionsManager and in the configuration file, you can customize to show or hide a specific panel (See section “Build a full-featured PDF Reader” and “Customizing to show/hide a specific Panel” for more details).

Figure 2-28

Add support for Annotations

Foxit MobilePDF SDK includes a wide variety of standard annotations, and each of them uses the similar way to be added into the project. In this section, we will show you how to add support for the common used annotations which are provided in the Complete PDF Viewer demo, and will take the highlight annotation as an example to set forth the steps in detail. For other common used annotations, we only list the core code, for more details, please refer to the highlight section.

Highlight

We will add the highlight feature to the simple Android app in the section “Displaying a PDF document“, and like previous added features, we also add a button on the main interface and use the button click event to quickly experience the highlight feature. Just follow the steps below:

a) Refer to “Add code to instantiate a UIExtensionsManager object and set it to PDFViewCtrl” in the section “Add support for Form Filling” to add the same code in the Test_android project.

b) In the “activity_main.xml” file, add a button like below:

activity_main.xml;

&lt; ?xml version="1.0" encoding="utf-8"?&gt;
 
 
 
<button></button>

c)  In the “MainActivity.java” file, implement the highlight feature in the button click event.

First, set the system theme to “No Title” mode and set the window to Fullscreen.

Note: The UI Extensions Component has customized the user interface, so you need to set the system theme to “No Title” mode and set the window to Fullscreen. Otherwise, the layout of the built-in features might be affected.

// Turn off the title at the top of the screen.
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
 
// Set the window to Fullscreen.
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

Import the following classes:

import android.view.View;
import android.widget.Button;
import com.foxit.uiextensions.Module;
import com.foxit.uiextensions.annots.textmarkup.highlight.HighlightModule;

Instantiate a Button object and add the click event. Then, get a HighlightModule object from UIExtensionManager (the HighlightModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler.

private Button btn_highlight = null;
private HighlightModule highlightModule = null;
...
btn_highlight = (Button) findViewById(R.id.Highlight_button);
...
// Highlight button click event
public void Highlight_Click(View view) {
if (highlightModule == null)
        highlightModule = (HighlightModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_HIGHLIGHT);
        uiextensionManager.setCurrentToolHandler(highlightModule.getToolHandler());
}

The whole update of “MainActivity.java” is as follows:

package com.foxit.test_android;
 
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Window;
import android.view.WindowManager;
import android.widget.RelativeLayout;
import android.view.View;
import android.widget.Button;
 
import com.foxit.sdk.common.Library;
import com.foxit.sdk.common.PDFException;
 
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.pdf.PDFDoc;
import com.foxit.uiextensions.UIExtensionsManager;
import com.foxit.uiextensions.Module;
import com.foxit.uiextensions.annots.textmarkup.highlight.HighlightModule;
 
public class MainActivity extends FragmentActivity {
 
    private PDFViewCtrl pdfViewCtrl = null;
    private RelativeLayout parent = null;
    private UIExtensionsManager uiextensionManager = null;
    private HighlightModule highlightModule = null;
    private Button btn_highlight = null;
    // Load "librdk.so" library.
    static {
        System.loadLibrary("rdk");
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // The value of "sn" can be found in the “rdk_sn.txt”.
        // The value of "key" can be found in the “rdk_key.txt”.
        String sn = " ";
        String key = " ";
 
        try {
            // initialize the library
            Library.init(sn, key);
        } catch (PDFException e) {
            e.printStackTrace();
            return;
        }
 
        // Turn off the title at the top of the screen.
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // Set the window to FullScreen.
        getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
 
        // Inflate the view and get a reference to PDFViewCtrl.
        setContentView(R.layout.activity_main);
        pdfViewCtrl = (PDFViewCtrl) findViewById(R.id.pdfviewer);
 
        parent = (RelativeLayout) findViewById(R.id.parentLayout);
        btn_highlight = (Button) findViewById(R.id.Highlight_button);
 
        // Initialize a UIExtensionsManager object and set it to PDFViewCtrl.
        uiextensionManager = new UIExtensionsManager(this, parent, pdfViewCtrl);
        pdfViewCtrl.setUIExtensionsManager(uiextensionManager);
        // Load a document.
        String path = "/mnt/sdcard/input_files/Sample.pdf";
        try {
            PDFDoc document = PDFDoc.createFromFilePath(path);
            document.load(null);
            pdfViewCtrl.setDoc(document);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
 
    // Highlight button click event
    public void Highlight_Click(View view) {
        if (highlightModule == null)
            highlightModule = (HighlightModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_HIGHLIGHT);
        uiextensionManager.setCurrentToolHandler(highlightModule.getToolHandler());
    }
 
    @Override
    protected void onDestroy() {
        super.onDestroy();
        try {
            Library.release();
        } catch (PDFException e) {
            e.printStackTrace();
        }
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        if (pdfViewCtrl != null)
            pdfViewCtrl.requestLayout();
    }
}

Note: For this project, we use “Sample.pdf” as the test file. You can use any PDF file, just remember topush it onto the Android device or Emulator, and change the file path in “MainActivity.java”.

Now that we have finished adding support for highlight into the project, let’s build and run it. You will see that the “Sample.pdf” document is automatically displayed (see Error! Reference source not found.).

Note: when running the project, if you encounter an error like “Error running app: Instant Run require ‘Tools|Android|Enable ADB integration’ to be enabled”, just follow the prompt to enable the ADB integration in “Tools -> Android -> Enable ADB integration”.

Figure 2-29

In order to see the highlight result clearly, swipe right to the next page, click the “Highlight” button, and drag over text to highlight the selected text (see Figure 2-30).

Figure 2-30

Underline

Adding support for underline is similar to add support for highlight. The core point is to get an UnderlineModule object from UIExtensionManager (the UnderlineModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for underline. The core code is below:

import com.foxit.uiextensions.annots.textmarkup.underline.UnderlineModule;
...
private UnderlineModule underlineModule = null;
...
public void Underline_Click(View view) {
  if (underlineModule == null)
      underlineModule = (UnderlineModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_UNDERLINE);
  uiextensionManager.setCurrentToolHandler(underlineModule.getToolHandler());
}
Squiggly

Adding support for squiggly is similar to add support for highlight. The core point is to get a SquigglyModule object from UIExtensionManager (the SquigglyModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for squiggly. The core code is below:

import com.foxit.uiextensions.annots.textmarkup.squiggly.SquigglyModule;
...
private SquigglyModule squigglyModule = null;
...
public void Squiggly_Click(View view) {
  if (squigglyModule == null)
      squigglyModule = (SquigglyModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_SQUIGGLY);
  uiextensionManager.setCurrentToolHandler(squigglyModule.getToolHandler());
}
Strikeout

Adding support for strikeout is similar to add support for highlight. The core point is to get a StrikeoutModule object from UIExtensionManager (the StrikeoutModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for strikeout. The core code is below:

import com.foxit.uiextensions.annots.textmarkup.strikeout.StrikeoutModule;
...
private StrikeoutModule strikeoutModule = null;
...
public void Strikeout_Click(View view) {
  if (strikeoutModule == null)
      strikeoutModule = (StrikeoutModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_STRIKEOUT);
  uiextensionManager.setCurrentToolHandler(strikeoutModule.getToolHandler());
}
Insert text

Insert and replace text tools are implemented in CaretModule. So, the core point to add support for insert text is to get a CaretModule object from UIExtensionManager (the CaretModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for insert text. The core code is below:

import com.foxit.uiextensions.annots.caret.CaretModule;
...
private CaretModule caretModule = null;
...
public void Insert_Click(View view) {
  if (caretModule == null)
      caretModule = (CaretModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_CARET);
  uiextensionManager.setCurrentToolHandler(caretModule.getISToolHandler());
}
Replace text

Insert and replace text tools are implemented in CaretModule. So, the core point to add support for replace text is to get a CaretModule object from UIExtensionManager (the CaretModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for replace text. The core code is below:

import com.foxit.uiextensions.annots.caret.CaretModule;
...
private CaretModule caretModule = null;
...
public void Replace_Click(View view) {
  if (caretModule == null)
      caretModule = (CaretModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_CARET);
  uiextensionManager.setCurrentToolHandler(caretModule.getRPToolHandler());
}
Line

Line and arrow tools are implemented in LineModule. So, the core point to add support for line is to get a LineModule object from UIExtensionManager (the LineModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for line. The core code is below:

import com.foxit.uiextensions.annots.line.LineModule;
...
private LineModule lineModule = null;
...
public void Line_Click(View view) {
  if (lineModule == null)
      lineModule = (LineModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_LINE);
  uiextensionManager.setCurrentToolHandler(lineModule.getLineToolHandler());
}
Arrow

Line and arrow tools are implemented in LineModule. So, the core point to add support for arrow is to get a LineModule object from UIExtensionManager (the LineModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for arrow. The core code is below:

import com.foxit.uiextensions.annots.line.LineModule;
...
private LineModule lineModule = null;
...
public void Line_Click(View view) {
  if (lineModule == null)
      lineModule = (LineModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_LINE);
  uiextensionManager.setCurrentToolHandler(lineModule.getArrowToolHandler());
}
Square

Adding support for square is similar to add support for highlight. The core point is to get a SquareModule object from UIExtensionManager (the SquareModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for square. The core code is below:

import com.foxit.uiextensions.annots.square.SquareModule;
...
private SquareModule squareModule = null;
...
public void Square_Click(View view) {
  if (squareModule == null)
      squareModule = (SquareModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_SQUARE);
  uiextensionManager.setCurrentToolHandler(squareModule.getToolHandler());
}
Circle

Adding support for circle is similar to add support for highlight. The core point is to get a CircleModule object from UIExtensionManager (the CircleModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for circle. The core code is below:

import com.foxit.uiextensions.annots.circle.CircleModule;
...
private CircleModule circleModule = null;
...
public void Circle_Click(View view) {
  if (circleModule == null)
      circleModule = (CircleModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_CIRCLE);
  uiextensionManager.setCurrentToolHandler(circleModule.getToolHandler());
}
Pencil

Pencil is also called ink in the PDF specification. The core point to add support for pencil is to get an InkModule object from UIExtensionManager (the InkModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for pencil. The core code is below:

import com.foxit.uiextensions.annots.ink.InkModule;
...
private InkModule inkModule = null;
...
public void Pencil_Click(View view) {
  if (inkModule == null)
      inkModule = (InkModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_INK);
  uiextensionManager.setCurrentToolHandler(inkModule.getToolHandler());
}
Eraser

Eraser tool is generally used in combination with the pencil tool. The core point to add support for eraser is to get an EraserModule object from UIExtensionManager (the EraserModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for eraser. The core code is below:

import com.foxit.uiextensions.annots.ink.EraserModule;
...
private EraserModule eraserModule = null;
...
public void Eraser_Click(View view) {
  if (eraserModule == null)
      eraserModule = (EraserModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_ERASER);
  uiextensionManager.setCurrentToolHandler(eraserModule.getToolHandler());
}
Typewriter

Adding support for typewriter is similar to add support for highlight. The core point is to get a TypewriterModule object from UIExtensionManager (the TypewriterModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for typewriter. The core code is below:

import com.foxit.uiextensions.annots.freetext.typewriter.TypewriterModule;
...
private TypewriterModule typewriterModule = null;
...
public void Typewriter_Click(View view) {
  if (typewriterModule == null)
      typewriterModule = (TypewriterModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_TYPEWRITER);
  uiextensionManager.setCurrentToolHandler(typewriterModule.getToolHandler());
}
Note

Adding support for note is similar to add support for highlight. The core point is to get a NoteModule object from UIExtensionManager (the NoteModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for note. The core code is below:

import com.foxit.uiextensions.annots.note.NoteModule;
...
private NoteModule noteModule = null;
...
public void Note_Click(View view) {
  if (noteModule == null)
      noteModule = (NoteModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_NOTE);
  uiextensionManager.setCurrentToolHandler(noteModule.getToolHandler());
}
Stamp

Adding support for stamp is similar to add support for highlight. The core point is to get a StampModule object from UIExtensionManager (the StampModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for stamp. The core code is below:

import com.foxit.uiextensions.annots.stamp.StampModule;
...
private StampModule stampModule = null;
...
public void Stamp_Click(View view) {
  if (stampModule == null)
      stampModule = (StampModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_STAMP);
  uiextensionManager.setCurrentToolHandler(stampModule.getToolHandler());
}
Attachment

Adding support for attachment is similar to add support for highlight. The core point is to get a FileAttachmentModule object from UIExtensionManager (the FileAttachmentModule is already instantiated in UIExtensionManager), and set its tool handler as the current tool handler. You can refer to “Highlight” to see the detailed process to add support for attachment. The core code is below:

import com.foxit.uiextensions.annots.fileattachment.FileAttachmentModule;
...
private FileAttachmentModule fileAttachmentModule = null;
...
public void Attachment_Click(View view) {
  if (fileAttachmentModule == null)
      fileAttachmentModule = (FileAttachmentModule) uiextensionManager.getModuleByName(Module.MODULE_NAME_FILEATTACHMENT);
  uiextensionManager.setCurrentToolHandler(fileAttachmentModule.getToolHandler());
}

The previous section introduces how to make an Android app with Foxit MobilePDF SDK. It mainly describes how to call the APIs to realize some specific features provided by Foxit MobilePDF SDK, but it is still a little complicated for developers to build a full-featured PDF Reader, because they need to take much time to design the UI of their app and learn the details about our SDK.

From version 4.0, Foxit MobilePDF SDK makes a big change and optimization that wraps all of the basic UI implementations including the UI design of app to PDFReader class, and provides a more convenient way to flexibly control and customize the features through a configuration file, which means developers can easily build a full-featured PDF app with several lines of code. The following section will show you how to take several minutes to build a PDF Reader like Complete PDF viewer demo.

Create a PDF Reader app

From version 3.0, the demos provided by Foxit MobilePDF SDK are built in Android Studio 2.2.3, so we will use Android Studio 2.2.3 to create a PDF Reader app in this section.

a) Open Android Studio, choose File -> New -> New Project… to start the Create New Project wizard, and then fill the New Project Set the App’s name to “PDFReader” (you can set the name as you like). Then, click Next.

b) In the Target Android Devices dialog, select “Phone and Tablet” to run your app, and set the Minimum SDK to API 16 (default). Click Next.

c) In the Add an activity to Mobile dialog, select “Empty Activity”, and then click Next.

d) In the Customize the Activity dialog, customize your activity as desired, here, we use the default setting, and then click Finish.

You can refer to the section “Create a new Android project” which uses Android Studio 2.1.1 and lists the detailed screenshots.

Note: In this project, we use the default Gradle version 3.3, Gradle Build Tool 2.3.0, and along with Android API revision 25.

Integrate Foxit MobilePDF SDK

Please refer to the section “Integrate Foxit MobilePDF SDK into your apps” to integrate the SDK library into the created PDFReader application for details. Following just explains the key steps.

Note: We will use the default built-in UI implementation including the UI design of the app to create a PDF Reader. So, just use FoxitRDKUIExtensions.aar file for simplicity.

a) Copy and paste the “aar” file from the “libs” folder of the download package to “PDFReader\app\libs” folder.

b) Copy and paste the “so” file from the “libs\x86” folder of the download package to “PDFReader\app\libs\x86” (note that you might need to create this folder by yourself).

c) Inside the app’s “build.gradle” file, add a reference to “so“, define the “libs” directory as a repository and add “FoxitRDKUIExtensions.aar” to the dependencies.

The following code shows “build.gradle” in its entirety.

apply plugin: 'com.android.application'
 
android {
    compileSdkVersion 25
    buildToolsVersion "25.0.3"
    defaultConfig {
        applicationId "com.foxit.pdfreader"
        minSdkVersion 16
        targetSdkVersion 21
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    sourceSets {
        main {
            jniLibs.srcDirs = ['libs']
        }
    }
}
repositories {
    flatDir {
        dirs 'libs'
    }
}
 
dependencies {
    compile(name: 'FoxitRDKUIExtensions', ext: 'aar')
    compile 'com.android.support:appcompat-v7:25.3.1'
    compile 'com.android.support.constraint:constraint-layout:1.0.0-alpha7'
    compile 'com.android.support:recyclerview-v7:25.3.1'
    testCompile 'junit:junit:4.12'
}

Note In order to run this project on an Andorid 6.0 (API 23) or higher devices/emulators without requiring authorization of runtime permissions, we set targetSdkVersion to API 21, otherwise you need to write some additional code to require the permissions. About the code, you can refer to the section “Display a PDF document“.

Foxit MobilePDF SDK has a dependency on recyclerview support library, so you should add it to the dependencies, such as “compile ‘com.android.support:recyclerview-v7:25.3.1’“.

After setting the app’s “build.gradle” file, sync it, then the “FoxitRDKUIExtensions” and “recyclerview” will appear in External Libraries as shown in Figure 3‑1.

Figure 3‑1

Now, we will try to get started with experiencing the new improved spotlight in version 5.0. The UI Extensions Component wraps all of the basic UI implementations including the UI design of app to PDFReader class, and provides a configuration file to flexibly control and customize the features without needing to write any additional code or redesign the app’s UI.

First, you should unlock Foxit MobilePDF SDK library, you can see section “Apply the license key” or further down you will find it in the “MainActivity.java” file.

In “MainActivity.java“, we are now going to add the code necessary for building a full-featured PDF Reader with the default reader provided in version 5.0. The required code additions are shown below and further down you will find a full example of what the “MainActivity.java” file should look like.

Add a configuration file

A configuration file is required if you want to use the default PDFReader which contains all of the basic UI implementations including the UI design of app. It can be provided as a JSON file or implemented directly in the code.

The first format, use a JSON file named “uiextensions_config.json” which should look like as follows:

{
     "defaultReader": true,
     "modules": {
         "readingbookmark": true,
         "outline": true,
         "annotations": true,
         "thumbnail" : true,
         "attachment": true,
         "signature": true,
         "search": true,
         "pageNavigation": true,
         "form": true,
         "selection": true,
         "encryption" : true
     }
 }

Note: The “defaultReader” and all “modules” should be set to “true”, which ensures that all of the features are enabled. For more details about the configuration file, please see section “Configuration file“.

You should prepare the JSON configuration file, and then put it to “PDFReader\app\src\main\res\raw” (note that you need to create the “raw” folder by yourself).

Then, use the following code to get the configuration file and set it to UIExtensions:

import java.io.InputStream;
 
...
 
InputStream stream = 
this.getApplicationContext().getResources().openRawResource(R.raw.uiextensions_config);
 UIExtensionsManager.Config config = new UIExtensionsManager.Config(stream);

The second format, implement it in the code instead of a JSON file as follows:

import java.io.ByteArrayInputStream;
 import java.io.InputStream;
 import java.nio.charset.Charset;
 
...
 
String UIExtensionsConfig = "{\n" +
         "    \"defaultReader\": true,\n" +
         "    \"modules\": {\n" +
         "        \"readingbookmark\": true,\n" +
         "        \"outline\": true,\n" +
         "        \"annotations\": true,\n" +
         "        \"thumbnail\" : true,\n" +
         "        \"attachment\": true,\n" +
         "        \"signature\": true,\n" +
         "        \"search\": true,\n" +
         "        \"pageNavigation\": true,\n" +
         "        \"form\": true,\n" +
         "        \"selection\": true,\n" +
         "        \"encryption\" : true\n" +
         "    }\n" +
         "}\n";
 
InputStream stream = new 
ByteArrayInputStream(UIExtensionsConfig.getBytes(Charset.forName("UTF-8")));
 UIExtensionsManager.Config config = new UIExtensionsManager.Config(stream);

Initialize UIExtensionsManager with a configuration file

In section “Add support for Form Filling“, we have already introduced a way to initialize UIExtensionsManager as follows:

Instantiate a UIExtensionsManager object and set it to PDFViewCtrl.

private UIExtensionsManager uiextensionsManager = null;
 
...
 
uiextensionsManager = new UIExtensionsManager(this.getApplicationContext(), null, pdfViewCtrl);
 
uiextensionsManager.setAttachedActivity(this);
 
pdfViewCtrl.setUIExtensionsManager(uiextensionsManager);

Yes. You can use the above method to initialize UIExtensionsManager, but in this way, you will not be able to use the default PDFReader, which means you should take a lot of effort to design the app’s UI and implement related functions.

PDFReader is a class that includes all of the basic UI implementations, such as feature panels, menus, toolbars, and so on. Using it, developers can build a full-featured PDF Reader app with just several minutes.

Following is the core code to initialize a UIExtensionsManager object with a configuration file, get current PDFReader, and set it to PDFViewCtrl.

In “MainActivity.java“:

private PDFViewCtrl pdfViewCtrl = null;
 private UIExtensionsManager uiextensionsManager = null;
 private PDFReader mPDFReader = null;
 
...
 
// Instantiate a PDFViewCtrl object.
 pdfViewCtrl = new PDFViewCtrl(this.getApplicationContext());
 
 // Get the config file, and set it to UIExtensionsManager.
 InputStream stream = this.getApplicationContext().getResources().openRawResource(R.raw.uiextensions_config);
 UIExtensionsManager.Config config = new UIExtensionsManager.Config(stream);
 
 // Instantiate a UIExtensionsManager object and set it to PDFViewCtrl.
 uiextensionsManager = new UIExtensionsManager(this.getApplicationContext(), null, pdfViewCtrl, config); 
 uiextensionsManager.setAttachedActivity(this);
 pdfViewCtrl.setUIExtensionsManager(uiextensionsManager);
 
 // Get current PDFReader, and set it to PDFViewCtrl.
 mPDFReader = (PDFReader) uiextensionsManager.getPDFReader();
 mPDFReader.onCreate(this, pdfViewCtrl, savedInstanceState);

Note: Here, we uses a JSON file to configure the UIExtensions. If you do not want to use JSON file, please refer to the previous section to implement it in the code.

Update MainActivity.java as follows:

Note: The Activity Lifecycle Events should be handled as below, otherwise some features may not work correctly.

package com.foxit.pdfreader;
 
import android.content.Intent;
import android.content.res.Configuration;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.Menu;
import android.view.WindowManager;
 
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.common.Library;
import com.foxit.sdk.common.PDFException;
import com.foxit.uiextensions.UIExtensionsManager;
import com.foxit.uiextensions.home.IHomeModule;
import com.foxit.uiextensions.pdfreader.impl.MainFrame;
import com.foxit.uiextensions.pdfreader.impl.PDFReader;
import com.foxit.uiextensions.utils.AppFileUtil;
 
import java.io.InputStream;
 
public class MainActivity extends AppCompatActivity {
 
    private PDFViewCtrl pdfViewCtrl = null;
    private UIExtensionsManager uiextensionsManager = null;
    private PDFReader mPDFReader = null;
    // Load "librdk.so" library.
    static {
        System.loadLibrary("rdk");
    }
 
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
 
        // The value of "sn" can be found in the “rdk_sn.txt”.
        // The value of "key" can be found in the “rdk_key.txt”.
        String sn = " ";
        String key = " ";
 
        try {
            // initialize the library.
            Library.init(sn, key);
        } catch (PDFException e) {
            e.printStackTrace();
            return;
        }
 
        // Instantiate a PDFViewCtrl object.
        pdfViewCtrl = new PDFViewCtrl(this.getApplicationContext());
 
        // Get the config file, and set it to UIExtensionsManager.
        InputStream stream = this.getApplicationContext().getResources().openRawResource(R.raw.uiextensions_config);
        UIExtensionsManager.Config config = new UIExtensionsManager.Config(stream);
 
        // Instantiate a UIExtensionsManager object and set it to PDFViewCtrl.
        uiextensionsManager = new UIExtensionsManager(this.getApplicationContext(), null, pdfViewCtrl, config);
        uiextensionsManager.setAttachedActivity(this);
        pdfViewCtrl.setUIExtensionsManager(uiextensionsManager);
 
        // Get current PDFReader, and set it to PDFViewCtrl.
        mPDFReader = (PDFReader) uiextensionsManager.getPDFReader();
        mPDFReader.onCreate(this, pdfViewCtrl, savedInstanceState);
 
        // load a document
        String path = "mnt/sdcard/Foxitsdk/Sample.pdf";
 
        mPDFReader.openDocument(path, null);
        setContentView(mPDFReader.getContentView());
    }
 
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (mPDFReader == null)
            return;
        if (mPDFReader.getMainFrame().getAttachedActivity() != this)
            return;
        setIntent(intent);
        String path = AppFileUtil.getFilePath(this, intent, IHomeModule.FILE_EXTRA);
        if (path != null) {
            mPDFReader.openDocument(path, null);
        }
    }
 
    @Override
    protected void onStart() {
        super.onStart();
        if (mPDFReader == null)
            return;
        mPDFReader.onStart(this);
    }
 
    @Override
    protected void onPause() {
        super.onPause();
        if (mPDFReader == null)
            return;
        mPDFReader.onPause(this);
    }
 
    @Override
    protected void onResume() {
        super.onResume();
        if (mPDFReader == null)
            return;
        mPDFReader.onResume(this);
    }
 
    @Override
    protected void onStop() {
        super.onStop();
        if (mPDFReader == null)
            return;
        mPDFReader.onStop(this);
    }
 
    @Override
    protected void onDestroy() {
        this.getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        if (mPDFReader != null)
            mPDFReader.onDestroy(this);
        super.onDestroy();
    }
 
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (mPDFReader != null)
            mPDFReader.onActivityResult(this, requestCode, resultCode, data);
    }
 
    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        if (mPDFReader == null)
            return;
        ((MainFrame) mPDFReader.getMainFrame()).updateSettingBar();
        mPDFReader.onConfigurationChanged(this, newConfig);
    }
 
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (mPDFReader != null &amp;&amp; mPDFReader.onKeyDown(this, keyCode, event))
            return true;
        return super.onKeyDown(keyCode, event);
    }
 
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        if (mPDFReader != null &amp;&amp; !mPDFReader.onPrepareOptionsMenu(this, menu))
            return false;
        return super.onPrepareOptionsMenu(menu);
    }
}

Add permissions settings and android:configChanges property

This project loads a specific PDF file (“mnt/sdcard/Foxitsdk/Sample.pdf”), you can change it as desired. In order to give the project permissions to access the camera and to write/read the SD card of the Android devices or emulators, set the “users-permission” in “AndroidManifest.xml” found in the “app\src\main”.

Add “android:configChanges=”keyboardHidden|orientation|screenSize”>” property to make sure that the project will only execute the onConfigurationChanged() function without recalling the activity lifecycle when rotating the screen. If you do not add this property, the signature feature will not work correctly.

Update the AndroidManifest.xml as follows:

&lt; ?xml version="1.0" encoding="utf-8"?&gt;
 
 
 
 
 
 
 
 
	   android:configChanges="keyboardHidden|orientation|screenSize"&gt;

Run the project

In this section, we build and run the project on an AVD targeting Android 6.0 (API 23), and you will see that the “Sample.pdf” document is displayed as shown in Figure 3 2. Up to now, we have completed a full-featured PDF Reader which includes all of the features in Complete PDF viewer demo. Feel free to try it.

Figure 3-2

Configuration file

From version 4.0, Foxit MobilePDF SDK provides a more convenient way to flexibly control and customize the features through a configuration file. Developers can easily choose the features that they want without needing to write any additional code or redesign the app’s UI. If you do not use a configuration file, then you need to take much time to design your app’s UI, please refer to “How to make and Android app with Foxit MobilePDF SDK.

The configuration file can be provided as a JSON file or implemented directly in the code. It controls which feature modules are enabled. Now, we will introduce the configuration file using the JSON file format. For code implementation, you can refer to section “Add a configuration file”.

The JSON configuration file can be written by yourself. There are some situations for it when you are writing. Following lists some typical examples:

Note: From version 5.0, the “defaultReader” field has been removed from the configuration file. Now, if you use configuration file to initialize UIExtensionsManager, it is equivalent to setting “defaultReader” to “true“. If you do not use configuration file, it is equivalent to setting “defaultReader” to “false“.

1)      All of the items in “modules” are set to “true”, in this case, all of the feature modules will be enabled.

{
     "modules": {
         "readingbookmark": true,
         "outline": true,
         "annotations": true,
         "thumbnail" : true,
         "attachment": true,
         "signature": true,
         "search": true,
         "pageNavigation": true,
         "form": true,
         "selection": true,
         "encryption": true
     }
 }

2)      Some items in “modules” are set to “false”. For example, “annotations” and “thumbnail” modules are set to “false”, in this case, only the “annotations” and “thumbnail” feature modules are disabled, the others are all enabled.

{
    "modules": {
        "readingbookmark": true,
        "outline": true,
        "annotations": false,
        "thumbnail" : false,
        "attachment": true,
        "signature": true,
        "search": true,
        "pageNavigation": true,
        "form": true,
        "selection": true,
        "encryption": true
    }
}

3)     Some items in “modules” are not set. For example, “annotations” and “thumbnail” modules are not set in the configuration file, in this case, the “annotations” and “thumbnail” feature modules are enabled, because the default settings are “true”. It means if some features modules are not in the configuration file, they will also be available.

{
    "modules": {
        "readingbookmark": true,
        "outline": true,
        "attachment": true,
        "signature": true,
        "search": true,
        "pageNavigation": true,
        "form": true,
        "selection": true,
        "encryption": true
    }
}

From version 5.0, Foxit MobilePDF SDK supports customizing the annotations in the built-in Annotation setting bar through a configuration file, so that developers can choose the annotations that they want without needing to write any additional code. Rewrite the JSON file as follows:

{
     "modules": {
         "readingbookmark": true,
         "outline": true,
         // "annotations": true,
         "annotations": {
           "highlight": true,
           "underline": true,
           "squiggly": true,
           "strikeout": true,
           "inserttext": true,
           "replacetext": true,
           "line"" true,
           "rectangle": true,
           "oval": true,
           "arrow": true,
           "pencil": true,
           "eraser": true,
           "typewriter": true,
           "note": true,
           "stamp": true
         },
         "thumbnail" : true,
         "attachment": true,
         "signature": true,
         "search": true,
         "pageNavigation": true,
         "form": true,
         "selection": true,
         "encryption": true
     }
 }

Please comment out “”annotations“: true,”, and set the types of annotations that you want to “true”. If you want to remove a specific type of the annotations, just set it to “false”.
Note: If some types of annotations are not in the configuration file, they are also enabled, because the default setting is “true”. For example, if you comment out “”highlight“: true,”, it is still available.

How to customize feature modules in your project

In this section, we will show you how to customize feature modules in your project. You will find it is extremely easy!

You just need to modify the configuration file. Let’s try it in the created PDFReader project (See sections from “Create a PDF Reader App” to Configuration file”). Below you can see an example of how to customize feature modules.

For example, you do not want the “readingbookmark“, “annotations” and “attachment” features. What should you do?

You only need to update the configuration file as follows:

{
     "modules": {
         "readingbookmark": false,
         "outline": true,
         "annotations": false,
         "thumbnail" : true,
         "attachment": false,
         "signature": true,
         "search": true,
         "pageNavigation": true,
         "form": true,
         "selection": true,
         "encryption": true
     }
 }

Then, rebuild the project, and you will see that the “Sample.pdf” document is displayed as shown in Figure 3‑3. Now, the “readingbookmark“,”annotations” and “attachment” features are removed. Cannot believe it, right? But, it is really so easy!

Note: From version 5.0, “”attachment“: true,” controls the attachments panel and attachment annotation. If you set it to “false”, both of them will be disabled, and if you want to hide “Comment” in the bottom bar, you should set both “annotations” and “attachment” to “false”.

Figure 3-3

Customizing the UI

Customizing the UI  is straightforward. Foxit MobilePDF SDK provides the source code of the UI Extensions Component that contains ready-to-use UI module implementations, which lets the developers have full control of styling the appearance as desired.

From version 5.0, Foxit MobilePDF SDK supports customizing UI elements (except the elements in the Annotation setting bar) through APIs, which is convenient for developers to modify the UI elements in the context of the built-in UI framework, such as adding/removing a button to/from the toolbar, showing/hiding a specific panel, and the items in the View setting bar and More Menu view. For the UI elements in the Annotation setting bar, you can customize them in the configuration file (see Configuration file to know more details about it). If you do not want to use the built-in UI framework, you can redesign it through modifying the source code of the UI Extensions Component.

Customize UI elements through APIs

From version 5.0, Foxit MobilePDF SDK provides APIs to customize the top/bottom bar, show or hide a specific panel, and show or hide the items in the View setting bar and More Menu View.

Note: For your convenience, we will show you how to customize UI elements through APIs in the “complete_pdf_viewer” demo found in the “samples” folder.

Customizing top/bottom bar

In the top/bottom bar, you can do the following operations:

  1. Add a custom item at any position
  2. Remove a specific item
  3. Remove all of the items in the toolbar
  4. Show or hide a specific item
  5. Add a custom toolbar
  6. Remove a specific toolbar
  7. Set background color for the toolbar
  8. Get the number of the items in a specific location of the toolbar.

Table 4-1 lists the related APIs which are used to customize the top/bottom bar

boolean addItem(BarName barName,BaseBar.TB_Position gravity, BaseItem item, int index);Add a custom item to the toolbar. The item will be inserted before any previous element at the specified location.
boolean addItem(BarName barName, BaseBar.TB_Position gravity, int textId, int resId, int index, IItemClickListener clickListener);
Add a default item to the toolbar. The item is inserted before any previous element at the specified location.
int getItemsCount(BarName barName, BaseBar.TB_Position gravity);Get the items count by IBarsHandler.BarName and BaseBar.TB_Position.
boolean removeItem(BarName barName, BaseBar.TB_Position gravity, int index);Remove the item by IBarsHandler.BarName, BaseBar.TB_Position and the specified index.
boolean removeItem(BarName barName, BaseBar.TB_Position gravity, BaseItem item);Removes the item by IBarsHandler.BarName, BaseBar.TB_Position and the specified item.
void removeAllItems(BarName barName); Remove all items from the toolbar.
boolean addCustomToolBar(BarName barName, View view);Add custom toolbar by BarName.
boolean removeToolBar(BarName barName); Remove toolbar by BarName.
void setBackgroundColor(BarName barName, int color);
Set background color for the toolbar.
void setBackgroundResource(BarName barName, int resid);Set background to a given resource.
BaseItem getItem(BarName barName, BaseBar.TB_Position gravity, int tag);Get the item by tag, but if you remove this item before you get it, it will return null.

There are two important enumerations which are defined to locate the position that you want to add a new item or remove an existing item.

enum BarName { 
    TOP_BAR, 
    BOTTOM_BAR; 
} 
 
enum TB_Position { 
    Position_LT, 
    Position_CENTER, 
    Position_RB; 
}

Note:

  1. The top bar or bottom bar can only add up to 7 items.
  2. To add an item to the top bar, please set the BaseBar.TB_Position to Position_LT or Position_RB. To add an item to the bottom bar, please set the BaseBar.TB_Position to Position_CENTER. Otherwise, the items may overlap.
  3. The bottom bar is only one part, and the top bar is divided into two parts, so that there are three parts for the toolbar, and each part has a separate index.(See Figure 4-1)
  4. The top bar can only display a maximum of 15 characters, and the bottom bar can only display a maximum of 8 characters. So, it’s better to set the character number of the text within the maximum number. Please note that the character length does not distinguish between Chinese and English.

Figure 4-1

In the following examples, we will show you how to customize the top/bottom bar through APIs in the “complete_pdf_viewer” demo found in the “samples” folder.

Load the “complete_pdf_viewer” demo in Android Studio. Add the sample code to the “PDFReaderFragment.java” file (after the code “mPDFReader = (PDFReader)uiExtensionsManager.getPDFReader();”).

Example1: Add an item in the left top bar at the second position.

BaseItemImpl mTopItem1 = new BaseItemImpl(getContext()); 
mTopItem1.setImageResource(R.drawable.rd_annot_item_delete_selector); 
mTopItem1.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        UIToast.getInstance(getActivity()).show("Add an item in the left top bar at the second position."); 
    } 
}); 
mPDFReader.getBarManager().addItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_LT, mTopItem1, 1);

The result after running the demo:

 

 

Example 2: Add an item in the right top bar at the first position.

BaseItemImpl mTopItem2 = new BaseItemImpl(getContext()); 
mTopItem2.setImageResource(R.drawable.annot_fileattachment_selector); 
mTopItem2.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        UIToast.getInstance(getActivity()).show("Add an item in the right top bar at the first position"); 
    } 
}); 
mPDFReader.getBarManager().addItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_RB, mTopItem2, 0);

The result after running the demo:

 

 

Example 3: Add an item to the bottom bar at the first position.

mPDFReader.getBarManager().addItem(IBarsHandler.BarName.BOTTOM_BAR, 
BaseBar.TB_Position.Position_CENTER, 
    R.string.action_more, R.drawable.rd_bar_more_selector, 0, new 
IBarsHandler.IItemClickListener() { 
    @Override 
    public void onClick(View v) { 
        UIToast.getInstance(getActivity()).show("Add an item to the bottom bar at the first position."); 
    } 
});

The result after running the demo:

 

 

Example 4: Add an item with custom style to the bottom bar at the second position.

int circleResId = R.drawable.rd_bar_circle_bg_selector; 
int textSize = getResources().getDimensionPixelSize(R.dimen.ux_text_height_toolbar); 
int textColorResId = R.color.ux_text_color_button_colour; 
int interval = getResources().getDimensionPixelSize(R.dimen.ux_toolbar_button_icon_text_vert_interval); 
CircleItemImpl mSettingBtn = new CircleItemImpl(this.getContext()); 
mSettingBtn.setImageResource(R.drawable.rd_annot_create_ok_selector); 
mSettingBtn.setText("style"); 
mSettingBtn.setRelation(BaseItemImpl.RELATION_BELOW); 
mSettingBtn.setCircleRes(circleResId); 
mSettingBtn.setInterval(interval); 
mSettingBtn.setTextSize(AppDisplay.getInstance(getContext()).px2dp(textSize)); 
mSettingBtn.setTextColorResource(textColorResId); 
mSettingBtn.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        UIToast.getInstance(getActivity()).show("Add an item with custom style to the bottom bar at the second position."); 
} 
}); 
mPDFReader.getBarManager().addItem(IBarsHandler.BarName.BOTTOM_BAR, 
BaseBar.TB_Position.Position_CENTER, mSettingBtn, 1);

The result after running the demo:

 

 

Example 5: Remove an item by index (remove the first item in the bottom bar).

mPDFReader.getBarManager().removeItem(IBarsHandler.BarName.BOTTOM_BAR, 
BaseBar.TB_Position.Position_CENTER,0);

The result after running the demo:

 

 

Example 6: Remove an item by BaseItem object (remove a custom item from the top bar that you added before).

mPDFReader.getBarManager().removeItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_LT, mTopItem1);

Before: (See Example 1)

 

 

After:

 

 

Example 7: Remove all the items in the bottom bar.

mPDFReader.getBarManager().removeAllItems(IBarsHandler.BarName.BOTTOM_BAR);

Before:

 

 

After:

 

 

Example 8: Add two items in the left top bar to control to show and hide the “more menu” item.

// Get and save the item that you want to show or hide. 
BaseBarManager baseBarManager = (BaseBarManager) mPDFReader.getBarManager(); 
final BaseItemImpl moreItem = (BaseItemImpl) 
baseBarManager.getItem(IBarsHandler.BarName.TOP_BAR, BaseBar.TB_Position.Position_RB, 
ToolbarItemConfig.ITEM_TOPBAR_MORE_TAG); 
 
// Add a buttom in the left top bar to hide the "moreItem" item. 
BaseItemImpl mTopItem = new BaseItemImpl(getContext()); 
mTopItem.setImageResource(R.drawable.rd_annot_item_delete_selector); 
mTopItem.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        // Hide the "moreItem" item. 
        mPDFReader.getBarManager().removeItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_RB, moreItem); 
    } 
}); 
mPDFReader.getBarManager().addItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_LT, mTopItem, 1); 
 
// Add a buttom in the left top bar to show the "moreItem" item. 
BaseItemImpl mTopItem2 = new BaseItemImpl(getContext()); 
mTopItem2.setImageResource(R.drawable.annot_reply_item_add_selector); 
mTopItem2.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        // Show the "moreItem" item. 
        mPDFReader.getBarManager().addItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_RB, moreItem ,2); 
    } 
}); 
mPDFReader.getBarManager().addItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_LT, mTopItem2, 2);

The result after running the demo, the top bar will look like as follows:

 

 

Click on the trash icon,and the “more menu” will be hidden as follows:

 

 

Click on the plus icon,

and the “more menu” will appear as follows:

 

 

Example 9: Remove the whole bottom bar

mPDFReader.getBarManager().removeToolBar(IBarsHandler.BarName.BOTTOM_BAR);

Example 10: Add a custom toolbar. (add a custom layout file “test_top_layout”)

View topView = View.inflate(getContext(), R.layout.test_top_layout, null); 
mPDFReader.getBarManager().addCustomToolBar(IBarsHandler.BarName.TOP_BAR, topView);

Customizing to show/hide a specific Panel

To show or hide a specific panel (See Figure 4-2, includes “Reading Bookmarks”, “Outline”, “Annotations” and “Attachments” panels, just clicks List at the bottom bar to find it), you can use the following APIs listed in the Table 4-2.

Table 4-2

public void setPanelHidden(boolean isHidden, PanelSpec.PanelType panelType)
To show or hide a panel according to the
PanelType
public boolean isHiddenPanel(PanelSpec.PanelType panelType) RReturn the current value in setPanelHidden.

Figure 4-2

Note: To show or hide a specific panel through APIs, please mark sure the corresponding features in the configuration file is set to “true“. Otherwise, the API settings will not have any effect.

In this section, we only give an example to show you how to show or hide a specific panel through APIs in the “complete_pdf_viewer” demo found in the “samples” folder. Just take the “Outline” panel as an example, and for others panels, you only need to change the PanelType. The corresponding relation between panels and PanelType are as follows:

PanelPanelType
Reading Bookmarks PanelSpec.PanelType.ReadingBookmarks
OutlinePanelSpec.PanelType.Outline
AnnotationsPanelSpec.PanelType.Annotations
Attachments PanelSpec.PanelType.Attachments

Load the “complete_pdf_viewer” demo in Android Studio. Add the sample code to the “PDFReaderFragment.java” file (after the code “mPDFReader = (PDFReader) uiExtensionsManager.getPDFReader();”).

Example: Add an item in the left top bar at the second position to control whether to show or hide the “Outline” panel.

BaseItemImpl mTopItem = new BaseItemImpl(getActivity()); 
mTopItem.setImageResource(R.drawable.rd_annot_item_delete_selector); 
mTopItem.setOnClickListener(new View.OnClickListener() { 
    @Override 
    public void onClick(View v) { 
        if (uiExtensionsManager.isHiddenPanel(PanelSpec.PanelType.Outline)){ 
            uiExtensionsManager.setPanelHidden(false, PanelSpec.PanelType.Outline); 
            UIToast.getInstance(getActivity()).show("show Outline"); 
        } else { 
            uiExtensionsManager.setPanelHidden(true, PanelSpec.PanelType.Outline);  
            UIToast.getInstance(getActivity()).show("hide outline"); 
        } 
    } 
}); mPDFReader.getBarManager().addItem(IBarsHandler.BarName.TOP_BAR, 
BaseBar.TB_Position.Position_LT, mTopItem, 1);

Note: In the above example, the “uiExtensionsManager” variable in “PDFReaderFragment.java” needs to be declared final.

Here, we add a button in the top bar to try this function. Click the button, if the “Outline” panel exists, then hides it, otherwise shows it.

After running the demo, click the “delete” button, it will pop up “hide Outline” as follows:

Then, tap List in the bottom bar, and you will see the “Outline” panel has been hidden (See Figure 4-3 ).

Figure 4-3

For Reading Bookmarks, Annotations, and Attachments panels, you only need to change the PanelType. Just try it.

Customizing to show/hide the UI elements in the View seting bar

To show or hide the UI elements in the View setting bar (See Figure 4-4, just clicks View at the bottom bar to find it), you only need to use the following API:

public void setVisibility(int type, int visibility)

Figure 4-4

The value of the parameter “type” can be set as follows, which maps the items in the View setting bar

typeinteger
IMultiLineBar.TYPE_LIGHT1
IMultiLineBar.TYPE_DAYNIGHT2
IMultiLineBar.TYPE_SYSLIGHT4
IMultiLineBar.TYPE_SINGLEPAGE8
IMultiLineBar.TYPE_CONTINUOUSPAGE16
IMultiLineBar.TYPE_THUMBNAIL32
IMultiLineBar.TYPE_LOCKSCREEN64
IMultiLineBar.TYPE_REFLOW 128
IMultiLineBar.TYPE_CROP 256
IMultiLineBar.TYPE_FACING288

The value of the parameter “visibility” can be set as follows:

visibilityintegerdescription
View.VISIBLE0The view is visible.
View.INVISIBLE4This view is invisible, but it still takes up space for layout purposes.
View.GONE 8This view is invisible, and it doesn't take any space for layout

In this section, we only take “Reflow” item as an example to show you how to show or hide the UI elements in the View setting bar through APIs in the “complete_pdf_viewer” demo found in the “samples” folder. For other UI elements, you only need to change the type.

Load the “complete_pdf_viewer” demo in Android Studio. Add the sample code to the “PDFReaderFragment.java” file (after the code “mPDFReader = (PDFReader) uiExtensionsManager.getPDFReader();”).

Example 1: To hide the Reflow item in the View setting bar without changing the layout.

mPDFReader.getSettingBar().setVisibility(IMultiLineBar.TYPE_REFLOW, View.INVISIBLE);

Before:

After:

Example 2: To hide the Reflow item in the View setting bar with changing the layout.

mPDFReader.getSettingBar().setVisibility(IMultiLineBar.TYPE_REFLOW, View.GONE);

Before:

After:

For other items in the View setting bar, you can refer to the above example, and just need to change the value of the parameter “type” in setVisibility interface.

To show one of the UI elements in the View setting bar, just set the value of the parameter “visibility” in setVisibility interface to “View.VISIBLE“.

Customizing to show/hide the UI elements in the More Menu view

To show or hide the More Menu item, please see “Customizing top/bottom bar” (see example 8).

To show or hide the UI elements in the More Menu view (See Figure 4-4, just click at the menu icon at the right top bar to find it), you can use the following APIs listed in the Table 4-3.

Table 4-3

void setGroupVisibility(int visibility, int tag)Set the enabled state of group according to "tag".
void setItemVisibility(int visibility, int groupTag, int itemTag);Set the enabled state of item according to "groupTag" and "itemTag".

Figure 4-5

The value of the parameter “tag” in the setGroupVisibility interface or the “groupTag” in the setItemVisibility interface can be set as follows:

taginteger
GROUP_FILE100
GROUP_PROTECT101
GROUP_FORM102

The value of the parameter “itemTag” in the setItemVisibility interface can be set as follows:

groupTagitemTaginteger
GROUP_FILEITEM_DOCINFO0
GROUP_FILEITEM_REDUCE_FILE_SIZE 1
GROUP_PROTECTITEM_PASSWORD0
GROUP_PROTECTITEM_REMOVESECURITY_PASSWORD 4
GROUP_FORMITEM_RESET_FORM0
GROUP_FORMITEM_IMPORT_FORM1
GROUP_FORMITEM_EXPORT_FORM2

The value of the parameter “visibility” in the setGroupVisibility and setItemVisibility interfaces can be set as follows:

void setGroupVisibility(int visibility, int tag)Set the enabled state of group according to "tag".
void setItemVisibility(int visibility, int groupTag, int itemTag);Set the enabled state of item according to "groupTag" and "itemTag".

Note: For setItemVisibility interface, if you want to show or hide an itemTag, please make sure the corresponding groupTag has been set to “View.VISIBLE“. Otherwise, the settings will not have any effect.

In this section, we only take “GROUP_FILE” (File in the view) and “ITEM_DOCINFO” (Properties in the view) as an example to show you how to show or hide the UI elements in the More Menu view through APIs in the “complete_pdf_viewer” demo found in the “samples” folder. For other UI elements, you can refer to the following examples and only need to change the parameter value in the setGroupVisibility and setItemVisibility interfaces.

Load the “complete_pdf_viewer” demo in Android Studio. Add the sample code to the “PDFReaderFragment.java” file (after the code “mPDFReader = (PDFReader) uiExtensionsManager.getPDFReader();”).

Example 1: Hide the “File” in the More Menu view without changing the layout.

// Get MenuViewImpl from MoreMenuModule. 
MoreMenuModule moreMenuModule = (MoreMenuModule) 
uiExtensionsManager.getModuleByName(Module.MODULE_MORE_MENU);
final MenuViewImpl menuView = (MenuViewImpl) moreMenuModule.getMenuView(); 
 
menuView.setGroupVisibility(View.INVISIBLE, MoreMenuConfig.GROUP_FILE);

Before:

After:

Example 2: Hide the “File” in the More Menu view with changing the layout.

// Get MenuViewImpl from MoreMenuModule. 
MoreMenuModule moreMenuModule = (MoreMenuModule) 
uiExtensionsManager.getModuleByName(Module.MODULE_MORE_MENU); 
final MenuViewImpl menuView = (MenuViewImpl) moreMenuModule.getMenuView(); 
 
menuView.setGroupVisibility(View.GONE, MoreMenuConfig.GROUP_FILE);

Before:

After:

Example 3: Hide the “Properties” in the More Menu view without changing the layout.

// Get MenuViewImpl from MoreMenuModule. 
MoreMenuModule moreMenuModule = (MoreMenuModule) 
uiExtensionsManager.getModuleByName(Module.MODULE_MORE_MENU); 
final MenuViewImpl menuView = (MenuViewImpl) moreMenuModule.getMenuView(); 
 
menuView.setItemVisibility(View.INVISIBLE, MoreMenuConfig.GROUP_FILE, 
MoreMenuConfig.ITEM_DOCINFO);

Before:

After:

Example 4: Hide the “Properties” in the More Menu view with changing the layout.

// Get MenuViewImpl from MoreMenuModule. 
MoreMenuModule moreMenuModule = (MoreMenuModule) 
uiExtensionsManager.getModuleByName(Module.MODULE_MORE_MENU); 
final MenuViewImpl menuView = (MenuViewImpl) moreMenuModule.getMenuView(); 
 
menuView.setItemVisibility(View.GONE, MoreMenuConfig.GROUP_FILE, MoreMenuConfig.ITEM_DOCINFO);

Before:

After:

For other items in the More Menu view, you can refer to the above examples, and just need to change the parameter value in the setGroupVisibility and setItemVisibility interfaces.

To show one of the UI elements in the More Menu view, just set the value of the parameter “visibility” in setVisibility and setItemVisibility interfaces to “View.VISIBLE“.

Customize UI elements through a configuration file

From version 5.0, Foxit MobilePDF SDK supports customizing the annotations in the built-in Annotation setting bar (See Figure 4-6) through a configuration file. For more details about the configuration file, you can see “Configuration file”.

Note: To find the Annotation setting bar, just click Comment at the bottom bar, and then click the menu button:

Figure 4-6

The configuration file looks like as follows:

{ 
    "modules": { 
        "readingbookmark": true, 
        "outline": true, 
// "annotations":true, 
        "annotations": { 
            "highlight": true, 
            "underline": true, 
            "squiggly": true, 
            "strikeout": true, 
            "inserttext": true, 
            "replacetext": true, 
            "line": true, 
            "rectangle": true, 
            "oval": true,
            "arrow": true, 
            "pencil": true, 
            "eraser": true, 
            "typewriter": true, 
            "note": true, 
            "stamp": true 
        }, 
    "thumbnail" : true, 
    "attachment": true, 
    "signature": true, 
    "search": true, 
    "pageNavigation": true, 
    "form": true, 
    "selection": true, 
    "encryption" : true 
    }
}

Please note that only the attachement annotation in the Annotation setting bar is not controlled by the subitems in “annotation“. “”attachment“: true,” controls the attachments panel and attachment annotation. If you set it to “false”, both of them will be disabled.

To customize the UI elements in the Annotation setting bar, please make sure to comment out “”annotations“: true,”. Then set the types of annotations that you want to “true”, if you want to remove a specific type of the annotations, just set it to “false”.

Note: If all types of the annotations in the configuration file are set to “false”, it is equal to “”annotations“: false,”. If some types of annotations are not in the configuration file, they are also enabled, because the default setting is “true”. For example, if you comment out “”highlight“: true,”, it is still available.

In this section, we will change the configuration file to show you how to customize the UI elements in the Annotation setting bar. For your convenience, we will try it in the “complete_pdf_viewer” demo found in the “samples” folder.

Load the “complete_pdf_viewer” demo in Android Studio. Find the configuration file “uiextensions_config.json” under “complete_pdf_viewer\app\src\main\res\raw”.

Example: Remove “highlight” “eraser” and “stamp” annotations.

Change the JSON file as follows:

{ 
    "modules": { 
        "readingbookmark": true, 
        "outline": true, 
// "annotations":true, 
        "annotations": { 
            "highlight": false, 
            "underline": true, 
            "squiggly": true, 
            "strikeout": true, 
            "inserttext": true, 
            "replacetext": true, 
            "line": true, 
            "rectangle": true, 
            "oval": true, 
            "arrow": true, 
            "pencil": true, 
            "eraser": false, 
            "typewriter": true, 
            "note": true, 
            "stamp": false 
        }, 
    "thumbnail" : true, 
    "attachment": true, 
    "signature": true, 
    "search": true, 
    "pageNavigation": true, 
    "form": true, 
    "selection": true, 
    "encryption" : true 
    } 
}

Then, rebuild and run the demo to see the result. Following lists the comparison diagrams:

Before:

After:

Customize UI implementation through source code

In the previous sections, we have introduced how to customize the UI elements through APIs or configuration file in detail. Those changes are in the context of the built-in UI framework of Foxit MobilePDF SDK. If you do not want to use the ready-made UI framework, you can redesign it through modifying the source code of the UI Extensions Component.

To customize the UI implementation through source code, you need to follow these steps:

First, add the following files into your app. They are all found in the “libs” folder.

  • uiextensions_src project – It is an open source library that contains some ready-to-use UI module implementations, which can help developers rapidly embed a fully functional PDF reader into their Android app. Of course, developers are not forced to use the default UI, they can freely customize and design the UI for their specific apps through the “uiextensions_src” project.
  • FoxitRDK.jar – used by the Java platform. It includes all the Java APIs of Foxit MobilePDF SDK.
  • librdk.so (libs/armeabi-v7a, libs/arm64-v8a, libs/x86) – called by the Java APIs in the FoxitRDK.jar. It is the heart of the SDK and contains the core functionalities of Foxit MobilePDF SDK, and it is built separately for each architecture. Currently it is available for armeabi-v7a, arm64-v8a, and x86.

Note: The uiextensions_src project has a dependency on FoxitRDK.jar. It is best to put them in the same directory. If they are not in the same directory, you will need to modify the reference path in the “build.gradle” file of the uiextensions_src project manually.

Second, find the specific layout XML files that you want to customize in the uiextensions_src project, then modify them based on your requirements.

Now, for your convenience, we will show you how to customize the UI implementation in the “viewer_ctrl_demo” project found in the “samples” folder.

UI Customization Example

Step 1:

Add the uiextensions_src project into the demo making sure that it is in the same folder as the FoxitRDK.jar file. This folder should already be in the right location if you have not changed the default folder hierarchy.

Note: The demo already includes references to the FoxitRDK.jar and librdk.so files, so we just need to add the uiextensions_src project through configuring the “settings.gradle” file. When to include the uiextensions_src project as a dependency, the reference to the FoxitRDKUIExtensions.aar needs to be removed.

Load the “viewer_ctrl_demo” in Android Studio. Then, follow the steps below:

a) In the “settings.gradle” file, add the following code to include the uiextensions_src project.

settings.gradle:

include ':app'
include ':uiextensions_src'
project(':uiextensions_src').projectDir = new File('../../libs/uiextensions_src/')

Rebuild the gradle, then the uiextensions_src project will be added as shown in Figure 4-7.

Figure 4-7

b) Include the uiextensions_src project as a dependency into the demo. Inside the app’s “build.gradle” file, add the compile project(“:uiextensions_src”) line and comment out the compile(name:’FoxitRDKUIExtensions’, ext:’aar’) line as follows:

dependencies {
    compile 'com.google.android:multidex:0.1'
    compile 'com.android.support:appcompat-v7:23.4.0'
    compile 'com.android.support:design:23.4.0'
    compile project(":uiextensions_src")
    //compile(name:'FoxitRDKUIExtensions', ext:'aar')
}

After making the change, rebuild this gradle. Then, select “File -> Project Structure…” to open the Project Structure dialog. In the dialog click “Modules -> app“, and select the Dependencies option, then you can see that the demo has a dependency on the uiextensions_src project as shown in Figure 4-8.

Figure 4-8

Congratulations! You have completed the first step.
Step 2:
Find and modify the layout files related to the UI that you want to customize.

Now we will show you a simple example that changes one button’s icon in the search panel as shown in Figure 4-9.

Figure 4-9

To replace the icon we only need to find the place which stores the icon for this button, then use another icon with the same name to replace it.

In the project, click “uiextensions_src -> src -> main -> res -> layout” as shown in Figure 4-10.

Figure 4-10

In the layout list, find the “search_layout.xml” file, and double-click it. Find the button in the Preview window, and click it to navigate to the related code as shown in Figure 4-11.

Figure 4-11

After finishing the three steps described in the above picture, go to “search_result_selector.xml” as shown in Figure 4-12. We can see that the icon is stored in the “drawable-xxx” folder with the name of “search_result.png” by holding Ctrl and left-clicking on “search_result”. Just replace it with your own icon.

Note: Foxit MobilePDF SDK provides three sets of icons for devices with different DPI requirements to make sure that your apps can run smoothly on every device.

Figure 4-12

For example, we use the icon of the search next button (“search_next.png” stored in the same folder with “search_result.png”) to replace it. Then, rerun the demo, try the search feature and we can see that the icon of the bottom search button has changed as shown in Figure 4-13.

Figure 4-13

This is just a simple example to show how to customize the UI implementation. You can refer to it and feel free to customize and design the UI for your specific apps through the uiextensions_src project.

Creating a custom tool

With Foxit MobilePDF SDK, creating a custom tool is a simple process. There are several tools implemented in the UI Extensions Component already. These tools can be used as a base for developers to build upon or use as a reference to create a new tool. In order to create your own tool quickly, we suggest you take a look at the uiextensions_src project found in the “libs” folder.

To create a new tool, the most important step is to create a Java class that implements the “ToolHandler.java” interface.

In this section, we will make a Regional Screenshot Tool to show how to create a custom tool with Foxit MobilePDF SDK. This tool can help the users who only want to select an area in a PDF page to capture, and then save it as an image. Now, let’s do it.

For convenience, we will build this tool based on the “viewer_ctrl_demo” project found in the “samples” folder. Steps required for implementing this tool are as follows:

  • Create a Java class named ScreenCaptureToolHandler that implements the “ToolHandler.java” interface.
  • Handle the onTouchEvent and onDraw events.
  • Instantiate a ScreenCaptureToolHandler object, and then register it to the tool manager.
  • Set the ScreenCaptureToolHandler object as the current tool handler.

Step 1:
Create a Java class named ScreenCaptureToolHandler that implements the “ToolHandler.java” interface.

a) Load the “viewer_ctrl_demo” project in Android Studio. Create a Java class named “ScreenCaptureToolHandler” in the “com.foxit.pdf.viewctrl” package.

b) Let the ScreenCaptureToolHandler.java class implement the ToolHandler interface as shown in Figure 5-1.

Figure 5-1

Step 2:
Handle the onTouchEvent and onDraw events.

Update ScreenCaptureToolHandler.java as follows:

package com.foxit.pdf.pdfviewer;
 
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PointF;
import android.graphics.Rect;
import android.graphics.RectF;
import android.view.MotionEvent;
import android.view.ViewGroup;
import android.widget.Toast;
 
import com.foxit.sdk.PDFViewCtrl;
import com.foxit.sdk.common.CommonDefines;
import com.foxit.sdk.common.PDFException;
import com.foxit.sdk.pdf.PDFPage;
import com.foxit.sdk.pdf.Renderer;
import com.foxit.uiextensions.ToolHandler;
import com.foxit.uiextensions.UIExtensionsManager;
 
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
 
public class ScreenCaptureToolHandler implements ToolHandler {
 
    private Context mContext;
    private PDFViewCtrl mPdfViewCtrl;
    private ViewGroup mParent;
 
    public ScreenCaptureToolHandler(Context context, ViewGroup parent, PDFViewCtrl pdfViewCtrl) {
        mPdfViewCtrl = pdfViewCtrl;
        mContext = context;
        mParent = parent;
    }
 
    @Override
    public String getType() {
        return "";
    }
 
    @Override
    public void onActivate() {
 
    }
 
    @Override
    public void onDeactivate() {
 
    }
 
    private PointF mStartPoint = new PointF(0, 0);
    private PointF mEndPoint = new PointF(0, 0);
    private PointF mDownPoint = new PointF(0, 0);
    private Rect mRect = new Rect(0, 0, 0, 0);
    private RectF mNowRect = new RectF(0, 0, 0, 0);
    private int mLastPageIndex = -1;
 
    // Handle OnTouch event
    @Override
    public boolean onTouchEvent(int pageIndex, MotionEvent motionEvent) {
 
        // Get the display view point in device coordinate system
        PointF devPt = new PointF(motionEvent.getX(), motionEvent.getY());
        PointF point = new PointF();
        // Convert display view point to page view point.
        mPdfViewCtrl.convertDisplayViewPtToPageViewPt(devPt, point, pageIndex);
        float x = point.x;
        float y = point.y;
 
        switch (motionEvent.getAction()) {
            // Handle ACTION_DOWN event: get the coordinates of the StartPoint.
            case MotionEvent.ACTION_DOWN:
                if (mLastPageIndex == -1 || mLastPageIndex == pageIndex) {
                    mStartPoint.x = x;
                    mStartPoint.y = y;
                    mEndPoint.x = x;
                    mEndPoint.y = y;
                    mDownPoint.set(x, y);
                    if (mLastPageIndex == -1) {
                        mLastPageIndex = pageIndex;
                    }
                }
                return true;
 
            // Handle ACTION_Move event.
            case MotionEvent.ACTION_MOVE:
                if (mLastPageIndex != pageIndex)
                    break;
                if (!mDownPoint.equals(x, y)) {
                    mEndPoint.x = x;
                    mEndPoint.y = y;
 
                    // Get the coordinates of the Rect.
                    getDrawRect(mStartPoint.x, mStartPoint.y, mEndPoint.x, mEndPoint.y);
 
                    // Convert the coordinates of the Rect from float to integer.
                    mRect.set((int) mNowRect.left, (int) mNowRect.top, (int) mNowRect.right, (int) mNowRect.bottom);
 
                    // Refresh the PdfViewCtrl, then the onDraw event will be triggered.
                    mPdfViewCtrl.refresh(pageIndex, mRect);
                    mDownPoint.set(x, y);
                }
                return true;
 
            // Save the selected area as a bitmap.
            case MotionEvent.ACTION_UP:
                if (mLastPageIndex != pageIndex)
                    break;
                if (!mStartPoint.equals(mEndPoint.x, mEndPoint.y)) {
                    renderToBmp(pageIndex, "/mnt/sdcard/ScreenCapture.bmp");
                    Toast.makeText(mContext, "The selected area was saved as a bitmap stored in the /mnt/sdcard/ScreenCapture.bmp", Toast.LENGTH_LONG).show();
                }
                mDownPoint.set(0, 0);
                mLastPageIndex = -1;
                return true;
            default:
                return true;
        }
        return true;
    }
 
    // Save a bimap to a specified path.
    public static void saveBitmap(Bitmap bm, String outPath) throws IOException {
        File file = new File(outPath);
        file.createNewFile();
 
        FileOutputStream fileout = null;
        try {
            fileout = new FileOutputStream(file);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
 
        bm.compress(Bitmap.CompressFormat.JPEG, 100, fileout);
        try {
            fileout.flush();
            fileout.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
 
    // Render the selected area to a bitmap.
    private void renderToBmp(int pageIndex, String filePath) {
        try {
            PDFPage page = mPdfViewCtrl.getDoc().getPage(pageIndex);
 
            mPdfViewCtrl.convertPageViewRectToPdfRect(mNowRect, mNowRect, pageIndex);
            int width = (int) page.getWidth();
            int height = (int) page.getHeight();
 
            Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
            bmp.eraseColor(Color.WHITE);
 
            // Create a Renderer object
            Renderer renderer = Renderer.create(bmp);
 
            // Get the display matrix.
            Matrix matrix = page.getDisplayMatrix(0, 0, width, height, 0);
            int progress = renderer.startRender(page, matrix, null);
            while (progress == CommonDefines.e_progressToBeContinued) {
                progress = renderer.continueRender();
            }
            // Create a bitmap with the size of the selected area.
            bmp = Bitmap.createBitmap(bmp, (int) mNowRect.left, (int) (height - mNowRect.top), (int) mNowRect.width(), (int) Math.abs(mNowRect.height()));
            try {
                saveBitmap(bmp, filePath);
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (PDFException e) {
            e.printStackTrace();
        }
    }
 
    //Get the coordinates of a Rect.
    private void getDrawRect(float x1, float y1, float x2, float y2) {
        float minx = Math.min(x1, x2);
        float miny = Math.min(y1, y2);
        float maxx = Math.max(x1, x2);
        float maxy = Math.max(y1, y2);
 
        mNowRect.left = minx;
        mNowRect.top = miny;
        mNowRect.right = maxx;
        mNowRect.bottom = maxy;
    }
 
    @Override
    public boolean onLongPress(int i, MotionEvent motionEvent) {
        return false;
    }
 
    @Override
    public boolean onSingleTapConfirmed(int i, MotionEvent motionEvent) {
        return false;
    }
 
    //Handle the drawing event.
    @Override
    public void onDraw(int pageIndex, Canvas canvas) {
        if (((UIExtensionsManager) mPdfViewCtrl.getUIExtensionsManager()).getCurrentToolHandler() != this)
            return;
        if (mLastPageIndex != pageIndex) {
            return;
        }
        canvas.save();
        Paint mPaint = new Paint();
        mPaint.setStyle(Paint.Style.STROKE);
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setColor(Color.BLUE);
        mPaint.setAlpha(200);
        mPaint.setStrokeWidth(3);
        canvas.drawRect(mNowRect, mPaint);
        canvas.restore();
    }
}

Step 3:
Instantiate a ScreenCaptureToolHandler object and then register it to the UIExtensionsManager.

private ScreenCaptureToolHandler screenCapture = null;
...
screenCapture = new ScreenCaptureToolHandler(mContext, parent, pdfViewCtrl);
uiExtensionsManager.registerToolHandler(screenCapture);

Step 4:

Set the ScreenCaptureToolHandler object as the current tool handler.

uiExtensionsManager.setCurrentToolHandler(screenCapture);

Now, we have really finished creating a custom tool. In order to see what the tool looks like, we need to make it run. Just add an action item and add the code referred in Step 3 and Step 4 to MainActivity.java.

First, add an action item in Main.xml found in “app/src/main/res/menu” as follows.

 

In “app/src/main/res/values/strings.xml”, add the following string:

ScreenCapture

Then, add the following code to the onActionItemClicked() function in MainActivity.java.

if (itemId == R.id.ScreenCapture) {
    if (screenCapture == null) {
        screenCapture = new ScreenCaptureToolHandler(mContext, parent, pdfViewCtrl);
        uiExtensionsManager.registerToolHandler(screenCapture);
    }
    uiExtensionsManager.setCurrentToolHandler(screenCapture);
}

Please remember to instantiate a ScreenCaptureToolHandler object at first, like (private ScreenCaptureToolHandler screenCapture = null;).

After finishing all of the above work, build and run the demo.

Note Here, we run the demo on an AVD targeting 4.4.2. Please make sure you have pushed the “Sample.pdf” document into the created folder “input_files” of the emulator’s SD card.

After building the demo successfully, click anywhere to display the Contextual Action bar, and click the action items menu button below:

And find the ScreenCapture action button as shown in Figure 5-2.

Figure 5-2

Click ScreenCapture, long press and select a rectangular area, and then a message box will be popped up as shown in Figure 5-3. It shows where the bitmap (selected area) was saved to.

Figure 5-3

In order to verify whether the tool captures the selected area successfully, we need to find the screenshot. Open the Android Device Monitor, we can see the screenshot named “ScreenCapture.bmp” in the SD card as shown in Figure 5-4.

Figure 5-4

Pull the ScreenCapture.bmp from the emulator, we can see the image as shown in Figure 5-5.

Figure 5-5

As you can see we have successfully created a Regional Screenshot Tool. This is just an example to show how to create a custom tool with Foxit MobilePDF SDK. You can refer to it or our demos to develop the tools you want.

Technical Support

Reporting Problems

Foxit offers 24/7 support for its products and are fully supported by the PDF industry’s largest development team of support engineers. If you encounter any technical questions or bug issues when using Foxit MobilePDF SDK, please submit the problem report to the Foxit support team at http://tickets.foxitsoftware.com/create.php. In order to better help you solve the problem, please provide the following information:

  • Contact details
  • Foxit MobilePDF SDK product and version
  • Your Operating System and IDE version
  • Detailed description of the problem
  • Any other related information, such as log file or error screenshot

Contact Information

You can contact Foxit directly, please use the contact information as follows:

Foxit Support:

Sales Contact:

  • Phone: 1-866-680-3668
  •  Email: sales@foxitsoftware.com

Support & General Contact:

  • Phone: 1-866-MYFOXIT or 1-866-693-6948
  • Email: support@foxitsoftware.com
Updated on October 19, 2017

Was this article helpful?

Related Articles