139

Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Embed Size (px)

Citation preview

Page 1: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project
Page 2: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

TABLE OF CONTENTS

1 Introduction to Foxit MobilePDF SDK ...........................................................................................1

1.1 Why Foxit MobilePDF SDK is your choice ............................................................................................. 1

1.2 Foxit MobilePDF SDK ............................................................................................................................ 2

1.3 Key Features ......................................................................................................................................... 3

1.4 Evaluation ............................................................................................................................................. 5

1.5 License .................................................................................................................................................. 5

1.6 About this Guide ................................................................................................................................... 5

2 Getting Started ...........................................................................................................................7

2.1 System Requirements ........................................................................................................................... 7

2.2 What is in the Package ......................................................................................................................... 7

2.3 How to run a demo ............................................................................................................................... 9

2.3.1 Function demo .............................................................................................................................................. 10

2.3.2 Viewer control demo .................................................................................................................................... 13

2.3.3 Multiple documents demo ............................................................................................................................ 16

2.3.4 Complete PDF viewer demo.......................................................................................................................... 18

2.4 How to make an Android app with Foxit MobilePDF SDK .................................................................. 22

2.4.1 Create a new Android project ....................................................................................................................... 23

2.4.2 Integrate Foxit MobilePDF SDK into your apps ............................................................................................. 26

2.4.3 Apply the license key .................................................................................................................................... 30

2.4.4 Display a PDF document ............................................................................................................................... 31

2.4.5 Add support for Form Filling ......................................................................................................................... 35

2.4.6 Add support for Text Search ......................................................................................................................... 41

2.4.7 Add support for Outline ................................................................................................................................ 48

2.4.8 Add support for Annotations ........................................................................................................................ 54

3 Rapidly building a full-featured PDF Reader ............................................................................... 67

3.1 Create a PDF Reader app .................................................................................................................... 67

3.2 Integrate Foxit MobilePDF SDK........................................................................................................... 68

Page 3: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

3.3 Build a full-featured PDF Reader ........................................................................................................ 70

3.3.1 Add a configuration file ................................................................................................................................. 70

3.3.2 AndroidManifest.xml settings ....................................................................................................................... 71

3.3.3 Initialize UIExtensionsManager with a configuration file .............................................................................. 73

3.3.4 Run the project ............................................................................................................................................. 78

3.4 Configuration file ................................................................................................................................ 78

3.5 How to customize feature modules in your project ........................................................................... 82

4 Customizing the UI .................................................................................................................... 84

4.1 Customize UI elements through APIs ................................................................................................. 84

4.1.1 Customizing top/bottom bar ........................................................................................................................ 84

4.1.2 Customizing to show/hide a specific Panel ................................................................................................... 92

4.1.3 Customizing to show/hide the UI elements in the View setting bar ............................................................. 95

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

4.2 Customize UI elements through a configuration file ........................................................................ 103

4.3 Customize UI implementation through source code ........................................................................ 107

5 Creating a custom tool ............................................................................................................ 114

6 FAQ ........................................................................................................................................ 125

6.1 Open a PDF document from a specified PDF file path...................................................................... 125

6.2 Display a specified page when opening a PDF document ................................................................ 126

6.3 Add a link annotation to a PDF file ................................................................................................... 127

6.4 Insert an image into a PDF file .......................................................................................................... 128

6.5 License key and serial number cannot work .................................................................................... 129

6.6 Highlight the links in PDF documents and set the highlight color .................................................... 129

6.7 Highlight the form fields in PDF form files and set the highlight color ............................................. 130

6.8 Indexed Full Text Search support ..................................................................................................... 130

6.9 Print PDF document .......................................................................................................................... 132

6.10 Night mode color settings ................................................................................................................ 133

Page 4: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

7 Technical Support .................................................................................................................... 135

Page 5: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

1

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

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

Page 6: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

2

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.

1.2 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, Android platforms and Universal Windows Platform (UWP) for Windows

10.

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

The three elements for Foxit MobilePDF 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

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

Page 7: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

3

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.

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

Page 8: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

4

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 betting reading.

Text Select Search text in a PDF document, and provide indexed Full-Text Search

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.

Pan and Zoom Adjust the magnification and position of the view area to match the area in an

adjustable rectangle in the Pan & Zoom window's thumbnail view of the page.

Print Print PDF document.

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.

Support robust PDF applications with Foxit MobilePDF SDK

Development of robust PDF applications is challenging on mobile platforms which has limited memory.

When memory allocation fails, applications may crash or exit unexpectedly. To deal with this issue, Foxit

MobilePDF SDK provides an out-of-memory (OOM) mechanism to support applications.

OOM is an evolved feature in Foxit MobilePDF SDK because of its complexity. The key of OOM mechanism

is that Foxit MobilePDF SDK will monitor the usage of memory and take recovery operations automatically

once OOM is detected. During the recovery process, Foxit MobilePDF SDK reloads the document and page

Page 9: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

5

automatically and restores the status to the original before OOM. It means the current reading page and

location, as well as page view mode (single or continuous page) can be recovered. However, the data

generated from editing will be lost.

Foxit MobilePDF SDK provides a property "shouldRecover" in FSPDFViewCtrl class. By default, the value of

"shouldRecover" is "YES". If you do not want to enable the auto-recovery when OOM is detected, you can

set "shouldRecover" to "false" as follows:

PDFViewCtrl pdfViewerCtrl = new PDFViewCtrl(getActivity().getApplicationContext()); pdfViewerCtrl.shouldRecover = false;

At that time, the application will throw an exception, and may crash or exit unexpectedly.

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

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

1.6 About this Guide

Foxit MobilePDF SDK is currently available on iOS, Android and UWP for Windows 10 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:

Section 1: gives an introduction of Foxit MobilePDF SDK.

Section 2: illustrates the package structure, running demo, and adding PDF SDK into app.

Section 3: describes how to quickly create a full-featured PDF Reader.

Section 4: introduces how to customize the UI implementation.

Section 5: shows how to create a custom tool.

Section 6: lists some frequently asked questions.

Section 7: provides support information.

Page 10: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

6

Note:

In section 2, it shows you how to call Foxit MobilePDF SDK APIs to realize some specific

features, which does not use the PDFReader class (includes the basic UI implementations)

provided in version 4.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

PDFReader class provided in version 4.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.

Page 11: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

7

2 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

PDFReader class (includes the basic UI implementations) provided in version 4.0. If you want to quickly

build a full-featured PDF Reader, please see section 3 Rapidly building a full-featured PDF Reader directly.

2.1 System Requirements

Android devices’ requirements:

Android 4.x

32/64-bit ARM (armeabi-v7a/arm64-v8a) or 32-bit Intel x86 CPU

Android Studio 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

2.2 What is 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.

Page 12: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

8

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

Page 13: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

9

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.

Note: In order to reduce the size of FoxitRDKUIExtensions.aar, Foxit MobilePDF SDK uses shrink-code in

the uiextensions_src project. If you do not want to use shrink-code when you build the uiextensions_src

project, you can disable it by setting "minifyEnabled" to "false" in the App's build.gradle. For shrink-

code, you can refer to https://developer.android.com/studio/build/shrink-code.html.

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.

2.3 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 four useful demos for developers to learn how to call the SDK as shown in

Figure 2-3.

Figure 2-3

Page 14: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

10

2.3.1 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 section, 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.

Page 15: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

11

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

Page 16: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

12

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.

Page 17: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

13

Figure 2-6

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

Page 18: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

14

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, and you can click (overflow

button) to see more action items as shown in Figure 2-8.

Page 19: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

15

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.

Page 20: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

16

Figure 2-9

2.3.3 Multiple documents demo

The Multiple documents demo demonstrates how to use Foxit SDK to support viewing multiple PDF

documents.

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

Figure 2-10 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.

Page 21: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

17

Figure 2-10

Click the "Complete_pdf_viewer_guide_android.pdf" tab to open this document in current window view

(See Figure 2-11). Now, you can browse the two PDF documents by switching the tabs.

Page 22: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

18

Figure 2-11

2.3.4 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-12).

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.

Page 23: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

19

Figure 2-12

Click the "complete_pdf_viewer_guide_android.pdf" document, and then it will be opened and

displayed as shown in Figure 2-13.

Page 24: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

20

Figure 2-13

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-14, and then the thumbnail of the document will be displayed as shown

in Figure 2-15.

Page 25: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

21

Figure 2-14

Page 26: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

22

Figure 2-15

2.4 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:

1) Create a new Android project

2) Integrate Foxit MobilePDF SDK into your apps

3) Apply the license key

4) Display a PDF document

5) Add support for Form Filling

6) Add support for Text Search

Page 27: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

23

7) Add support for Outline

8) Add support for Annotations

2.4.1 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-16. After filling, click Next.

Figure 2-16

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-17. Then, click Next.

Page 28: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

24

Figure 2-17

Page 29: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

25

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-18, and then click Next.

Figure 2-18

Page 30: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

26

In the Customize the Activity dialog, customize your activity as desired, here, we use the default setting

as shown in Figure 2-19, and then click Finish.

Figure 2-19

2.4.2 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

Page 31: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

27

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

Figure 2-20

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

configuration:

Page 32: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

28

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

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.

Page 33: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

29

Figure 2-21

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 {

Page 34: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

30

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.

2.4.3 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 unock

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=").

Page 35: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

31

2.4.4 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"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.foxit.test_android.MainActivity">

<com.foxit.sdk.PDFViewCtrl

android:id="@+id/pdfviewer"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scrollbars="vertical|horizontal"/>

</RelativeLayout>

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: The MainActivity need 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;

Page 36: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

32

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 = new PDFDoc(path);

document.load(null);

pdfViewCtrl.setDoc(document);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

@Override

protected void onDestroy() {

super.onDestroy();

try {

Page 37: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

33

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"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.foxit.test_android">

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

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

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>

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.

Page 38: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

34

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-22. Now, this sample app has some

basic PDF features, such as zooming in/out and page turning. Just have a try!

Page 39: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

35

Figure 2-22

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

Page 40: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

36

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-23. Now, it is just like a normal PDF file, in which the form fields cannot be edited.

Figure 2-23

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:

Page 41: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

37

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"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.foxit.test_android.MainActivity"

android:id="@+id/parentLayout">

<com.foxit.sdk.PDFViewCtrl

android:id="@+id/pdfviewer"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scrollbars="vertical|horizontal"/>

</RelativeLayout>

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

Page 42: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

38

package com.foxit.test_android; import android.support.v4.app.FragmentActivity; import android.os.Bundle; 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);

Page 43: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

39

uiExtensionsManager.setAttachedActivity(this);

pdfViewCtrl.setUIExtensionsManager(uiExtensionsManager);

// Load a document.

String path = "/mnt/sdcard/input_files/FoxitForm.pdf";

try {

PDFDoc document = new PDFDoc(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-24.

You can find that the Figure 2-24 is already different from the Figure 2-23. It means the form filling

feature is available at present. Feel free to edit the form, such as Figure 2-25.

Page 44: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

40

Figure 2-24

Page 45: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

41

Figure 2-25

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.

2.4.6 Add support for Text Search

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:

Page 46: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

42

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"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.foxit.test_android.MainActivity"

android:id="@+id/parentLayout">

<com.foxit.sdk.PDFViewCtrl

android:id="@+id/pdfviewer"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scrollbars="vertical|horizontal"/>

<Button

android:id="@+id/search_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Search"

android:layout_alignParentRight="true"

android:onClick="Search_Click"/>

</RelativeLayout>

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

Import the following classes:

import android.view.Window;

import android.view.WindowManager;

import android.view.View;

import android.widget.Button;

import com.foxit.uiextensions.Module; import com.foxit.uiextensions.modules.SearchModule; import com.foxit.uiextensions.modules.SearchView;

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.

Page 47: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

43

// 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);

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.widget.RelativeLayout;

import android.view.Window;

import android.view.WindowManager;

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;

Page 48: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

44

import com.foxit.uiextensions.UIExtensionsManager;

import com.foxit.uiextensions.Module;

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);

Page 49: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

45

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 = new PDFDoc(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

Page 50: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

46

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-26).

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-26

Page 51: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

47

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

Figure 2-27

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-28. You can click the previous or next button to find the previous or

next search result.

Page 52: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

48

Figure 2-28

2.4.7 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:

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

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

Page 53: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

49

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.foxit.test_android.MainActivity"

android:id="@+id/parentLayout">

<com.foxit.sdk.PDFViewCtrl

android:id="@+id/pdfviewer"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scrollbars="vertical|horizontal"/>

<Button

android:id="@+id/outline_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Outline"

android:layout_alignParentRight="true"

android:onClick="Outline_Click"/>

</RelativeLayout>

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

Import the following classes:

import android.view.Window;

import android.view.WindowManager;

import android.view.View;

import android.widget.Button;

import com.foxit.uiextensions.Module;

import com.foxit.uiextensions.modules.OutlineModule;

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);

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

the outline module.

Page 54: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

50

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 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.modules.OutlineModule;

public class MainActivity extends FragmentActivity {

private PDFViewCtrl pdfViewCtrl = null;

private RelativeLayout parent = null;

Page 55: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

51

private UIExtensionsManager uiExtensionsManager = 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.

Page 56: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

52

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 = new PDFDoc(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".

Page 57: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

53

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-29).

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-29

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-30. 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 3.3 "Build a full-featured PDF Reader" and section 4.1.2 "Customizing to show/hide a specific

Panel" for more details).

Page 58: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

54

Figure 2-30

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

2.4.8.1 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:

Page 59: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

55

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"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

xmlns:tools="http://schemas.android.com/tools"

android:layout_width="match_parent"

android:layout_height="match_parent"

tools:context="com.foxit.test_android.MainActivity"

android:id="@+id/parentLayout">

<com.foxit.sdk.PDFViewCtrl

android:id="@+id/pdfviewer"

android:layout_width="match_parent"

android:layout_height="match_parent"

android:scrollbars="vertical|horizontal"/>

<Button

android:id="@+id/highlight_button"

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:text="Highlight"

android:layout_alignParentRight="true"

android:onClick="Highlight_Click"/>

</RelativeLayout>

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

Import the following classes:

import android.view.Window;

import android.view.WindowManager;

import android.view.View;

import android.widget.Button;

import com.foxit.uiextensions.Module;

import com.foxit.uiextensions.annots.textmarkup.highlight.HighlightModule;

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.

Page 60: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

56

// 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);

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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_HIGHLIGHT);

uiExtensionsManager.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;

Page 61: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

57

public class MainActivity extends FragmentActivity {

private PDFViewCtrl pdfViewCtrl = null;

private RelativeLayout parent = null;

private UIExtensionsManager uiExtensionsManager = 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.

uiExtensionsManager = new UIExtensionsManager(this.getApplicationContext(), parent,

pdfViewCtrl);

Page 62: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

58

uiExtensionsManager.setAttachedActivity(this);

pdfViewCtrl.setUIExtensionsManager(uiExtensionsManager);

// Load a document.

String path = "/mnt/sdcard/input_files/Sample.pdf";

try {

PDFDoc document = new PDFDoc(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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_HIGHLIGHT);

uiExtensionsManager.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 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 highlight into the project, let's build and run it. You will

see that the "Sample.pdf" document is automatically displayed (see Figure 2-31).

Page 63: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

59

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-31

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-32).

Page 64: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

60

Figure 2-32

2.4.8.2 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_UNDERLINE);

Page 65: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

61

uiExtensionsManager.setCurrentToolHandler(underlineModule.getToolHandler());

}

2.4.8.3 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_SQUIGGLY);

uiExtensionsManager.setCurrentToolHandler(squigglyModule.getToolHandler());

}

2.4.8.4 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_STRIKEOUT);

uiExtensionsManager.setCurrentToolHandler(strikeoutModule.getToolHandler());

}

2.4.8.5 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

Page 66: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

62

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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_CARET);

uiExtensionsManager.setCurrentToolHandler(caretModule.getISToolHandler());

}

2.4.8.6 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_CARET);

uiExtensionsManager.setCurrentToolHandler(caretModule.getRPToolHandler());

}

2.4.8.7 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;

Page 67: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

63

...

public void Line_Click(View view) {

if (lineModule == null)

lineModule = (LineModule) uiExtensionsManager.getModuleByName(Module.MODULE_NAME_LINE);

uiExtensionsManager.setCurrentToolHandler(lineModule.getLineToolHandler());

}

2.4.8.8 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) uiExtensionsManager.getModuleByName(Module.MODULE_NAME_LINE);

uiExtensionsManager.setCurrentToolHandler(lineModule.getArrowToolHandler());

}

2.4.8.9 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_SQUARE);

uiExtensionsManager.setCurrentToolHandler(squareModule.getToolHandler());

}

Page 68: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

64

2.4.8.10 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_CIRCLE);

uiExtensionsManager.setCurrentToolHandler(circleModule.getToolHandler());

}

2.4.8.11 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) uiExtensionsManager.getModuleByName(Module.MODULE_NAME_INK);

uiExtensionsManager.setCurrentToolHandler(inkModule.getToolHandler());

}

2.4.8.12 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:

Page 69: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

65

import com.foxit.uiextensions.annots.ink.EraserModule;

...

private EraserModule eraserModule = null;

...

public void Eraser_Click(View view) {

if (eraserModule == null)

eraserModule = (EraserModule)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_ERASER);

uiExtensionsManager.setCurrentToolHandler(eraserModule.getToolHandler());

}

2.4.8.13 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_TYPEWRITER);

uiExtensionsManager.setCurrentToolHandler(typewriterModule.getToolHandler());

}

2.4.8.14 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)

Page 70: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

66

noteModule = (NoteModule) uiExtensionsManager.getModuleByName(Module.MODULE_NAME_NOTE);

uiExtensionsManager.setCurrentToolHandler(noteModule.getToolHandler());

}

2.4.8.15 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_STAMP);

uiExtensionsManager.setCurrentToolHandler(stampModule.getToolHandler());

}

2.4.8.16 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)

uiExtensionsManager.getModuleByName(Module.MODULE_NAME_FILEATTACHMENT);

uiExtensionsManager.setCurrentToolHandler(fileAttachmentModule.getToolHandler());

}

Page 71: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

67

3 Rapidly building a full-featured PDF Reader

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.

3.1 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 dialog. 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.

Page 72: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

68

3.2 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 "FoxitRDKUIExtensions.aar" file from the "libs" folder of the download

package to "PDFReader\app\libs" folder.

b) Copy and paste the "librdk.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 "librdk.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']

}

}

}

Page 73: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

69

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

Page 74: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

70

3.3 Build a full-featured PDF Reader

Now, we will try to get started with experiencing the new improved spotlight in version 4.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

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 PDFReader class (includes the basic UI implementations) provided in version 4.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.

3.3.1 Add a configuration file

A configuration file is required if you want to use the PDFReader class 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:

{

"modules": {

"readingbookmark": true,

"outline": true,

"annotations": true,

"thumbnail" : true,

"attachment": true,

"signature": true,

"search": true,

"pageNavigation": true,

"form": true,

"selection": true,

"encryption" : true

}

}

Note: All of the items in "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).

Page 75: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

71

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" +

" \"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);

3.3.2 AndroidManifest.xml settings

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|locale|layoutDirection|screenSize">"

property to make sure that the project will only execute the onConfigurationChanged() function without

Page 76: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

72

recalling the activity lifecycle when rotating the screen. If you do not add this property, the signature

feature will not work correctly.

Add <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" /> and "<service

android:name="com.foxit.uiextensions.modules.panzoom.floatwindow.service.FloatWindowService"/>

", which grants your phone the floating window permissions. If you do not add this permission and

service, the Pan and Zoom feature will not be able to work.

Update the AndroidManifest.xml as follows:

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

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.foxit.pdfreader">

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

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

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

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

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:roundIcon="@mipmap/ic_launcher_round"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity"

android:configChanges="keyboardHidden|orientation|locale|layoutDirection|screenSize">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

<service android:name="com.foxit.uiextensions.modules.panzoom.floatwindow.service.FloatWindowService"/>

</application>

</manifest>

Page 77: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

73

3.3.3 Initialize UIExtensionsManager with a configuration file

In section 2.4.5 "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 PDFReader class, 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);

Page 78: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

74

// 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) {

Page 79: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

75

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)

Page 80: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

76

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();

Page 81: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

77

}

@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) {

mPDFReader.onConfigurationChanged(this, newConfig);

}

}

@Override

public boolean onKeyDown(int keyCode, KeyEvent event) {

if (mPDFReader != null && mPDFReader.onKeyDown(this, keyCode, event))

return true;

return super.onKeyDown(keyCode, event);

}

@Override

public boolean onPrepareOptionsMenu(Menu menu) {

if (mPDFReader != null && !mPDFReader.onPrepareOptionsMenu(this, menu))

return false;

return super.onPrepareOptionsMenu(menu);

}

}

Page 82: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

78

3.3.4 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

3.4 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 section 2.4.

Page 83: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

79

Note: If you use the configuration file to initialize UIExtensionsManager, it means you want to use the

built-in app's UI provided in PDFReader, otherwise it means you need to design the app's UI and write

the related function code.

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

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,

Page 84: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

80

"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,

Page 85: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

81

"line": true,

"rectangle": true,

"oval": true,

"arrow": true,

"pencil": true,

"eraser": true,

"typewriter": true,

"textbox": true,

"note": true,

"stamp": true,

"polygon": true,

"cloud":true,

"distance":true,

"image":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.

Page 86: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

82

3.5 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 section

3.1-3.4). 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".

Page 87: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

83

Figure 3-3

Page 88: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

84

4 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 section 3.4

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.

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

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

Page 89: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

85

Table 4-1

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.

Page 90: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

86

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

Page 91: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

87

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:

Example2: 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:

Page 92: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

88

Example3: 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:

Example4: 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:

Page 93: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

89

Example5: 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:

Example6: 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 Example1)

After:

Example7: Remove all the items in the bottom bar.

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

Before:

After:

Page 94: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

90

Example8: 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 , then the "more menu" will be hidden as follows:

Click , then the "more menu" will appear as follows:

Page 95: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

91

Example9: Remove the whole bottom bar.

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

Example10: 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);

Page 96: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

92

4.1.2 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) Return 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:

Page 97: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

93

Panel PanelType

Reading Bookmarks PanelSpec.PanelType.ReadingBookmarks

Outline PanelSpec.PanelType.Outline

Annotations PanelSpec.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:

Page 98: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

94

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.

Page 99: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

95

4.1.3 Customizing to show/hide the UI elements in the View setting 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.

type integer

IMultiLineBar.TYPE_LIGHT 1

IMultiLineBar.TYPE_DAYNIGHT 2

IMultiLineBar.TYPE_SYSLIGHT 4

IMultiLineBar.TYPE_SINGLEPAGE 8

IMultiLineBar.TYPE_CONTINUOUSPAGE 16

IMultiLineBar.TYPE_THUMBNAIL 32

IMultiLineBar.TYPE_LOCKSCREEN 64

IMultiLineBar.TYPE_REFLOW 128

IMultiLineBar.TYPE_CROP 256

IMultiLineBar.TYPE_FACING_MODE 288

IMultiLineBar.TYPE_COVER_MODE 320

IMultiLineBar.TYPE_PANZOOM 384

Page 100: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

96

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

visibility integer description

View.VISIBLE 0 The view is visible.

View.INVISIBLE 4 This view is invisible, but it still takes up

space for layout purposes.

View.GONE 8 This 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();").

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

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

Before: After:

Page 101: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

97

Example2: 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".

Page 102: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

98

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

To show or hide the More Menu item, please see section 4.1.1 "Customizing top/bottom bar" (see

example 8).

To show or hide the UI elements in the More Menu view (See Figure 4-4, just clicks 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

Page 103: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

99

The value of the parameter "tag" in the setGroupVisibility interface or the "groupTag" in the

setItemVisibility interface can be set as follows:

tag integer

GROUP_FILE 100

GROUP_PROTECT 101

GROUP_FORM 102

GROUP_PRINT 103

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

groupTag itemTag integer

GROUP_FILE

ITEM_DOCINFO 0

ITEM_REDUCE_FILE_SIZE 1

ITEM_SNAPSHOT 2

GROUP_PROTECT ITEM_PASSWORD 0

ITEM_REMOVESECURITY_PASSWORD 4

GROUP_FORM

ITEM_RESET_FORM 0

ITEM_IMPORT_FORM 1

ITEM_EXPORT_FORM 2

GROUP_PRINT ITEM_PRINT_FILE 0

The value of the parameter "visibility" in the setGroupVisibility and setItemVisibility interfaces can

be set as follows:

visibility integer description

View.VISIBLE 0 The view is visible.

View.INVISIBLE 4 This view is invisible, but it still

takes up space for layout purposes.

View.GONE 8 This view is invisible, and it

doesn't take any space for layout.

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.

Page 104: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

100

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: 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:

Page 105: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

101

Example2: 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:

Example3: 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:

Page 106: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

102

Example4: 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".

Page 107: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

103

4.2 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 section 3.4 "Configurtion file".

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

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,

Page 108: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

104

"arrow": true, "pencil": true, "eraser": true, "typewriter": true, "textbox": true, "note": true, "stamp": true, "polygon": true, "cloud":true, "distance":true, "image":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".

Page 109: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

105

Example: Remove "highlight" "eraser", "stamp" and "polygon" 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, "textbox": true, "note": true, "stamp": false, "polygon": false, "cloud":true, "distance":true, "image":true }, "thumbnail" : true, "attachment": true, "signature": true, "search": true, "pageNavigation": true, "form": true, "selection": true, "encryption" : true } }

Page 110: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

106

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

Before: After:

Page 111: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

107

4.3 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

Page 112: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

108

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")

Page 113: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

109

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

Page 114: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

110

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.

Page 115: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

111

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

Page 116: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

112

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.

Page 117: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

113

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.

Page 118: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

114

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

Page 119: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

115

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.common.Progressive; 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;

Page 120: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

116

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);

Page 121: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

117

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();

Page 122: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

118

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 = new Renderer(bmp); // Get the display matrix. Matrix matrix = page.getDisplayMatrix(0, 0, width, height, 0); Progressive progress = renderer.startRender(page, matrix, null); int state = CommonDefines.e_progressToBeContinued;

while (state == CommonDefines.e_progressToBeContinued) {

state = progress.continueProgress();

}

// 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;

Page 123: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

119

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);

Page 124: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

120

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.

<item

android:id="@+id/ScreenCapture "

android:title=" @string/screencapture"/>

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

<string name="screencapture">ScreenCapture</string>

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

(overflow button) to find the ScreenCapture action button as shown in Figure 5-2.

Page 125: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

121

Figure 5-2

Page 126: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

122

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

Page 127: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

123

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

Page 128: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

124

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.

Page 129: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

125

6 FAQ

6.1 Open a PDF document from a specified PDF file path

How do I open a PDF document from a specified PDF file path?

Foxit MobilePDF SDK provides multiple interfaces to open a PDF document. You can open a PDF

document from a specified PDF file path, or from a memory buffer. For from a specified PDF file path,

there are two ways to do that.

The first one is that just use the openDoc interface, which includes the operations of creating a PDF

document object (PDFDoc(String path)), loading the document content (load), and setting the PDF

document object to view control (setDoc). Following is the sample code:

Note: The openDoc interface is only available for opening a PDF document from a file path. If you want

to customize to load a PDF document, you can implement it in the callback function (FileRead), and then

create a document object with a FireRead instance using PDFDoc(FileRead fileRead). Next, also load the

document content using load, and set the PDF document object to view control using setDoc.

// Assuming A PDFViewCtrl has been created.

// Open an unencrypted PDF document from a specified PDF file path.

String path = "/mnt/sdcard/input_files/Sample.pdf";

pdfViewCtrl.openDoc(path, null);

The second one is that use the PDFDoc(String path) interface to create a PDF document object , use

load interface to load the document content, and then use setDoc to set the PDF document object to

view control. Following is the sample code:

// Assuming A PDFViewCtrl has been created.

String path = "/mnt/sdcard/input_files/Sample.pdf";

try {

// Initialize a PDFDoc object with the path to the PDF file.

PDFDoc document = new PDFDoc(path);

// Load the unencrypted document content.

document.load(null);

// Set the document to view control.

Page 130: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

126

pdfViewCtrl.setDoc(document);

} catch (Exception e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

6.2 Display a specified page when opening a PDF document

What should I do if I want to display a specified page when opening a PDF document?

To display a specified page when opening a PDF file, the interface gotoPage (int pageIndex) is supposed

to use. Foxit MobilePDF SDK utilizes multi-thread to improve rendering speed, so you need to make sure

the document has been loaded successfully before using the gotoPage interface.

Please implement the callback interface in the IDocEventListener, and then call the gotoPage interface

in the onDocOpened event. Following is the sample code:

// Assuming A PDFViewCtrl has been created.

// Register the PDF document event listener.

pdfViewCtrl.registerDocEventListener(docListener);

// Open an unencrypted PDF document from a specified PDF file path.

String path = "/mnt/sdcard/input_files/Sample.pdf";

pdfViewCtrl.openDoc(path, null);

...

PDFViewCtrl.IDocEventListener docListener = new PDFViewCtrl.IDocEventListener() {

@Override

public void onDocWillOpen() {

}

@Override

public void onDocOpened(PDFDoc pdfDoc, int errCode) {

pdfViewCtrl.gotoPage(2);

}

@Override

public void onDocWillClose(PDFDoc pdfDoc) {

}

@Override

public void onDocClosed(PDFDoc pdfDoc, int i) {

}

Page 131: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

127

@Override

public void onDocWillSave(PDFDoc pdfDoc) {

}

@Override

public void onDocSaved(PDFDoc pdfDoc, int i) {

}

};

6.3 Add a link annotation to a PDF file

How can I add a link annotation to a PDF file?

To add a link annotation to a PDF file, you should first call the PDFPage.addAnnot to add an annotation

to a specified page, then call Action.Create to create an action, and set the action to the added link

annotation. Following is the sample code for adding a URI link annotation to the first page of a PDF file:

private Link linkAnnot = null; ... String path = "mnt/sdcard/Foxitsdk/sample.pdf"; try { // Initialize a PDFDoc object with the path to the PDF file. PDFDoc document = new PDFDoc(path); // Load the unencrypted document content. document.load(null); // Get the first page of the PDF file. PDFPage page = document.getPage(0); // Add a link annotation to the first page. linkAnnot = (Link) page.addAnnot(Annot.e_annotLink, new RectF(250, 750, 500, 650)); // Create a URI action and set the URI. URIAction uriAction = (URIAction) Action.create(document, Action.e_actionTypeURI); uriAction.setURI("www.foxitsoftware.com"); // Set the action to link annotation. linkAnnot.setAction(uriAction); // Reset appearance stream. linkAnnot.resetAppearanceStream(); // Save the document that has added the link annotation. document.saveAs("mnt/sdcard/Foxitsdk/sample_annot.pdf", PDFDoc.e_saveFlagNormal); } catch (Exception e) { e.printStackTrace(); }

Page 132: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

128

6.4 Insert an image into a PDF file

How do I insert an image into a PDF file?

There are two ways to help you insert an image into a PDF file. The first one is calling

PDFPage.addImageFromFilePath interface. You can refer to the following sample code which inserts an

image into the first page of a PDF file:

Note: Before calling PDFPage.addImageFromFilePath interface, you should get and parse the page that

you want to add the image.

String path = "mnt/sdcard/Foxitsdk/sample.pdf"; try { // Initialize a PDFDoc object with the path to the PDF file. PDFDoc document = new PDFDoc(path); // Load the unencrypted document content. document.load(null); // Get the first page of the PDF file. PDFPage page = document.getPage(0); // Parse the page. if (!page.isParsed()) { Progressive parse = page.startParse(e_parsePageNormal, null, false); int state = CommonDefines.e_progressToBeContinued; while (state == CommonDefines.e_progressToBeContinued) { state = parse.continueProgress(); } }

// Add an image to the first page. page.addImageFromFilePath("mnt/sdcard/Foxitsdk/2.png", new PointF(20, 30), 60, 50, true); // Save the document that has added the image. document.saveAs("mnt/sdcard/Foxitsdk/sample_image.pdf", PDFDoc.e_saveFlagNormal); } catch (Exception e) { e.printStackTrace(); }

The second one is that use the PDFPage.addAnnot interface to add a stamp annotation to a specified

page, and then convert the image to a bitmap and set the bitmap to the added stamp annotation. You

can refer to the following sample code which inserts an image as a stamp annotation into the first page

of a PDF file:

String path = "mnt/sdcard/Foxitsdk/sample.pdf"; try { // Initialize a PDFDoc object with the path to the PDF file. PDFDoc document = new PDFDoc(path);

Page 133: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

129

// Load the unencrypted document content. document.load(null); // Get the first page of the PDF file. PDFPage page = document.getPage(0); // Add a stamp annotation to the first page. Stamp stamp = (Stamp) page.addAnnot(Annot.e_annotStamp, new RectF(100, 350, 250, 150)); // Load a local image and convert it to a Bitmap. Bitmap bitmap = BitmapFactory.decodeFile("mnt/sdcard/Foxitsdk/2.png"); // Set the bitmap to the added stamp annotation. stamp.setBitmap(bitmap); //Reset appearance stream. stamp.resetAppearanceStream(); // Save the document that has added the stamp annotation. document.saveAs("mnt/sdcard/Foxitsdk/sample_image.pdf", PDFDoc.e_saveFlagNormal); } catch (Exception e) { e.printStackTrace(); }

6.5 License key and serial number cannot work

I have downloaded the SDK package from your website without making any changes. Why can't the

license key and serial number work?

Generally, the package uploaded to the website is supposed to work. It has been tested before it is

uploaded. So, if you find the license key and serial number cannot work, it may be caused by the time of

your device. If the device's time is earlier than the StartDate in the rdk_key.txt file found in the "libs"

folder of the download package, the "librdk.so" library will be failed to unlock. Please check the time of

your device.

6.6 Highlight the links in PDF documents and set the highlight color

How can I set whether to highlight the links in PDF documents? And how to set the highlight color if I

want to highlight links?

UIExtensionsManager.enableLinkHighlight() interface is provided to set whether to enable highlighting

the links in PDF documents. By default, the links in PDF documents will be highlighted. If you do not

want to highlight links, please set the parameter to "false" as follows:

// Assume you have already Initialized a UIExtensionsManager object uiExtensionsManager.enableLinkHighlight(false);

UIExtensionsManager.setLinkHighlightColor() interface is used to set the highlight color. Please make

sure you have not disabled highlighting links. Following is a sample for calling this API:

Page 134: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

130

// Assume you have already Initialized a UIExtensionsManager object uiExtensionsManager.setLinkHighlightColor(0x4b0000ff);

6.7 Highlight the form fields in PDF form files and set the highlight color

How can I set whether to highlight the form fields in PDF form files? And how to set the highlight color

if I want to highlight form fields?

UIExtensionsManager.enableFormHighlight() interface is provided to set whether to enable

highlighting the form fields in PDF form files. By default, the form fields will be highlighted. If you do not

want to highlight form fields, please set the parameter to "false" as follows:

// Assume you have already Initialized a UIExtensionsManager object uiExtensionsManager.enableFormHighlight(false);

UIExtensionsManager.setLinkHighlightColor() interface is used to set the highlight color. Please make

sure you have not disabled highlighting form fields. Following is a sample for calling this API:

// Set the highlight color to blue. uiextensionsManager.setFormHighlightColor(0x4b0000ff);

6.8 Indexed Full Text Search support

Does Foxit MobilePDF SDK support Indexed Full Text Search? If yes, how can I use it to search through

PDF files stored offline on my mobile device?

Yes. Foxit MobilePDF SDK for Android supports Indexed Full Text Search from version 5.0.

To use this feature, follows the steps below:

a) Get document source information. Create a document source based on a directory which will be

used as the search directory.

public DocumentsSource(String directory)

b) Create a full text search object, and set a path of database to store the indexed data.

public FullTextSearch() public void setDataBasePath(String pathOfDataBase)

c) Start to index the PDF documents which receive from the source.

public Progressive startUpdateIndex(DocumentsSource source, Pause pause, boolean reUpdate)

Note: You can index a specified PDF file. For example, if the contents of a PDF file have been

changed, you can re-index it using the following API:

public boolean updateIndexWithFilePath(java.lang.String filePath)

Page 135: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

131

d) Search the specified keyword from the indexed data source. The search results will be returned to

external by a specified callback function when a matched one is found.

public boolean searchOf(java.lang.String matchString, RankMode rankMode, SearchCallback searchCallback)

Following is a sample for how to use it:

String directory = "A search directory..."; FullTextSearch search = new FullTextSearch(); try { String dbPath = "The path of data base to store the indexed data..."; search.setDataBasePath(dbPath); // Get document source information. DocumentsSource source = new DocumentsSource(directory); // Create a Pause callback object implemented by users to pause the updating process. PauseUtil pause = new PauseUtil(30); // Start to update the index of PDF files which receive from the source. Progressive progressive = search.startUpdateIndex(source, pause, false); int state = CommonDefines.e_progressToBeContinued; while (state == CommonDefines.e_progressToBeContinued) { state = progressive.continueProgress(); } // Create a callback object which will be invoked when a matched one is found. MySearchCallback searchCallback = new MySearchCallback(); // Search the specified keyword from the indexed data source. search.searchOf("looking for this text", RankMode.e_rankHitCountASC, searchCallback); } catch (PDFException e) { e.printStackTrace(); }

A sample callback for PauseUtil is as follows:

public class PauseUtil extends Pause { private long m_milliseconds = 0; private long m_startTime = 0; public PauseUtil(long milliSeconds) { Date date = new Date(); m_milliseconds = milliSeconds; m_startTime = date.getTime(); } @Override public boolean needPauseNow() { // TODO Auto-generated method stub if (this.m_milliseconds < 1) return false; Date date = new Date(); long diff = date.getTime() - m_startTime; if (diff > this.m_milliseconds) { m_startTime = date.getTime(); return true;

Page 136: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

132

} else return false; } }

A sample callback for MySearchCallback is as follows:

public class MySearchCallback extends SearchCallback { private static final String TAG = MySearchCallback.class.getCanonicalName(); @Override public void release() { } @Override public int retrieveSearchResult(String filePath, int pageIndex, String matchResult, int matchStartTextIndex, int matchEndTextIndex) { String s = String.format("Found file is :%s \n Page index is :%d Start text index :%d End text index :%d \n Match is :%s \n\n", filePath, pageIndex, matchStartTextIndex, matchEndTextIndex, matchResult); Log.v(TAG, "retrieveSearchResult: " + s); return 0; } }

Note:

The indexed full text search provided by Foxit MobilePDF SDK will go through a directory

recursively, so that both the files and the folders under the search directory will be indexed.

If you want to abort the index process, you can pass in a pause callback parameter to the

startUpdateIndex interface. The callback function NeedPauseNow will be invoked once a PDF

document is indexed, so that the caller can abort the index process when the callback

NeedPauseNow return "true".

The location of the indexed database is set by setDataBasePath interface. If you want to

clear the indexed database, you shoud do it manually. And now, removing a file from index

function is not supported.

Every search result of the searchOf interface is returned to external by a specified callback.

Once the searchOf interface returns "true" or "false", it means the searching is finished.

6.9 Print PDF document

Does Foxit MobilePDF SDK support to print a PDF document? If yes, how can I use it?

Page 137: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

133

Yes. Foxit MobilePDF SDK supports the print feature from version 5.1. You can press the Wireless Print

button on the More Menu view in the Complete PDF viewer demo to print the PDF document.

Furthermore, you can call the following API to print the PDF documents:

// for iPhone and iTouch

public void startPrintJob(Context context, PDFDoc doc, String printJobName, String outputFileName, IPrintResultCallback callback)

Following is a sample for how to use it:

// Assume you have already Initialized a UIExtensionsManager object PDFDoc doc = null; IPrintResultCallback print_callback = new IPrintResultCallback() { @Override public void printFinished() { } @Override public void printFailed() { } @Override public void printCancelled() { } }; try { doc = new PDFDoc("/mnt/sdcard/Foxitsdk/Sample.pdf"); doc.load(null); } catch (PDFException e) { Assert.fail("unexpect a PDF Exception!!errCode = " + e.getLastError()); } uiextensionsManager.startPrintJob(getActivity(), doc, "print with name", "print_withAPI", print_callback); }

6.10 Night mode color settings

How can I set the night mode color?

From version 5.1, Foxit MobilePDF SDK support to set the night mode color as desired.

To set the night mode color, you should call the PDFViewCtrl.setMappingModeBackgroundColor(int)

and PDFViewCtrl.setMappingModeForegroundColor(int) APIs to set the color as you wish, then set the

color mode by using PDFViewCtrl.setColorMode(int).

Note: If the color mode is already set to Renderer.e_colorModeMapping, you still need to set it again

after calling PDFViewCtrl.setMappingModeBackgroundColor(int) and

PDFViewCtrl.setMappingModeForegroundColor(int). Otherwise, the settings may not work.

Following is a sample to set the night mode color:

Page 138: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

134

private UIExtensionsManager uiextensionsManager = null;

...

PDFViewCtrl pdfViewCtrl = uiextensionsManager.getPDFViewCtrl();

pdfViewCtrl.setMappingModeBackgroundColor(0xff87cefa);

pdfViewCtrl.setMappingModeForegroundColor(0xff7cfc00);

pdfViewCtrl.setColorMode(Renderer.e_colorModeMapping);

Page 139: Foxit MobilePDF SDK · PDF file · 2018-01-292.3 How to run a demo ... 2.4 How to make an Android app with Foxit MobilePDF SDK ... 2.4.1 Create a new Android project

Foxit MobilePDF SDK Developer Guide

135

7 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:

http://www.foxitsoftware.com/support/

Sales Contact:

Phone: 1-866-680-3668

Email: [email protected]

Support & General Contact:

Phone: 1-866-MYFOXIT or 1-866-693-6948

Email: [email protected]