Developer Guide for Foxit PDF SDK for Java API (8.0)
Contents
- Introduction to Foxit PDF SDK
- Getting Started
- Working with SDK API
- Initialize Library
- Document
- Page
- Render
- Attachment
- Text Page
- Text Search
- Text Link
- Bookmark
- Form (AcroForm)
- XFA Form
- Form Design
- Annotations
- Image Conversion
- Watermark
- Barcode
- Security
- Reflow
- Asynchronous PDF
- Pressure Sensitive Ink
- Wrapper
- PDF Objects
- Page Object
- Marked content
- Layer
- Signature
- Long term validation (LTV)
- PAdES
- PDF Action
- JavaScript
- Redaction
- Comparison
- OCR
- Compliance
- Optimization
- HTML to PDF Conversion
- Office to PDF Conversion
- Output Preview
- Combination
- PDF Portfolio
- FAQ
- Appendix
- References
- Support
Introduction to Foxit PDF SDK
Have you ever thought about building your own application that can do everything you want with PDF files? If your answer is “Yes“, congratulations! You just found the best solution in the industry that allows you to build stable, secure, efficient and full-featured PDF applications.
Foxit PDF SDK provides high-performance libraries to help any software developer add robust PDF functionality to their enterprise, mobile and cloud applications across all platforms (includes Windows, Mac, Linux, Web, Android, iOS, and UWP), using the most popular development languages and environments.
Why Foxit PDF SDK is your choice
Foxit is a 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. Customers choose Foxit PDF SDK product for the following reasons:
- Easy to integrate
Developers can seamlessly integrate Foxit PDF SDK into their own applications.
- Lightweight footprint
Do not exhaust system resource and deploys quickly.
- Cross-platform support
Support current mainstream platforms, such as Windows, Mac, Linux, Web, Android, iOS, and UWP.
- Powered by Foxit’s high fidelity rendering PDF engine
The core technology of the SDK is based on Foxit’s PDF engine, which is trusted by a large number of the world’s largest and well-known companies. Foxit’s powerful engine makes the app fast on parsing, rendering, and makes document viewing consistent on a variety of devices.
- Premium World-side Support
Foxit offers premium support for its developer products because when you are developing mission critical products you need the best support. Foxit has one of the PDF industry’s largest team of support engineers. Updates are released on a regular basis to improve user experience by adding new features and enhancements.
Foxit PDF SDK for Java
Application developers who use Foxit PDF SDK can leverage Foxit’s powerful, standard-compliant PDF technology to securely display, create, edit, annotate, format, organize, print, share, secure, search documents as well as to fill PDF forms. Additionally, Foxit PDF SDK (for C++ and .NET) includes a built-in, embeddable PDF Viewer, making the development process easier and faster. For more detailed information, please visit the website https://developers.foxit.com/pdf-sdk/.
In this guide, we focus on the introduction of Foxit PDF SDK for Java API on Windows and Linux platforms.
Foxit PDF SDK for Java API ships with simple-to-use APIs that can help Java developers seamlessly integrate powerful PDF technology into their own projects on Windows and Linux platforms. It provides rich features on PDF documents, such as PDF viewing, bookmark navigating, text selecting/copying/searching, PDF signatures, PDF forms, rights management, PDF annotations, and full text search.
Evaluation
Foxit PDF SDK allows users to download trial version to evaluate SDK. The trial version has no difference from a standard version except for the 10-day limitation trial period and the trail watermarks that will be generated on the PDF pages. After the evaluation period expires, customers should contact Foxit sales team and purchase licenses to continue using Foxit PDF SDK.
License
Developers should purchase licenses to use Foxit PDF SDK in their solutions. Licenses grant users permissions to release their applications based on PDF SDK libraries. However, users are prohibited to distribute any documents, sample codes, or source codes in the SDK released package to any third party without the permission from Foxit Software Incorporated.
About this guide
This guide is intended for developers who need to integrate Foxit PDF SDK for Java into their own applications. It aims at introducing installation package structure on desktop platform with Java, and the usage of SDK.
Getting Started
It is very easy to setup Foxit PDF SDK and see it in action! This guide will provide you with a brief introduction about our SDK package. The following sections introduce the contents of system requirements, the installation package as well as how to run a demo, and create your own project.
System Requirements
Platform | System Requirement | JDK version | Memo |
Windows | Windows XP, Vista, 7, 8 and 10 (32-bit and 64-bit) Windows Server 2003, 2008 and 2012 (32-bit and 64-bit) |
At least 1.8 | It only supports for Windows 8/10 classic style, but not for Store App or Universal App. |
Linux | 32-bit and 64-bit OS | At least 1.8 |
What is in the Package
Package for Windows Java is named “foxitpdfsdk_8_0_win_java.zip” and package for Linux Java is named “foxitpdfsdk_8_0_linux_java.zip”. They have the same structure, so in this guide mainly introduce “foxitpdfsdk_8_0_win_java.zip” as an example.
Download the package for Windows Java and extract it to a new directory like “foxitpdfsdk_8_0_win_java”. The structure of the release package is shown in Figure 2-1.
NOTE: the highlighted rectangle in the figure is just the version of Foxit PDF SDK. Here the SDK version is 8.0, so it shows 8_0 in the package name. Other highlighted rectangles in other figures have the same meaning in this guide.
This package contains the following folders:
doc: API references, developer guide
examples: sample projects and demos
lib: libraries and license files
res: the default icc profile files used for output preview demo
Figure 2-1
How to initialize Foxit PDF SDK
It is necessary for applications to initialize Foxit PDF SDK with license before calling any APIs. The static function Library.initialize(sn, key) is provided in com.foxit.sdk.common.Library. The trial license files can be found in the “lib” folder. Before initializing library, you should load the proper library for your system at first.
The following code will automatically load the proper library and then initialize the library:
// Load the library. // You can also use System.load("filename") instead. The filename argument must be an absolute path name. static { String os = System.getProperty("os.name"); if(os.toLowerCase().startsWith("win")){ if(System.getProperty("sun.arch.data.model").equals( "64")) { System.loadLibrary("fsdk_java_win64"); } else { System.loadLibrary("fsdk_java_win32"); } } else { if(System.getProperty("sun.arch.data.model").equals("64")) { System.loadLibrary("fsdk_java_linux64"); } else { System.loadLibrary("fsdk_java_linux32"); } } } // Initialize the library. // The value of "sn" can be got from "gsdk_sn.txt" (the string after "SN="). // The value of "key" can be got from "gsdk_key.txt" (the string after "Sign="). int error_code = Library.initialize("sn", "key"); if (error_code != e_ErrSuccess) { return; }
How to run a demo
Run a demo using batch script
Foxit PDF SDK provides several simple demos in directory “\examples\simple_demo”. All these demos (except ocr, html2pdf and office2pdf demos for Windows, compliance and output preview demos for Windows and Linux) can be run directly with the “.bat” files or “.sh” files in directory “\examples\simple_demo”:
a) Go to directory “\examples\simple_demo”, and run all demos by “RunAllDemo.bat” for Windows or by “RunAllDemo.sh” for Linux.
b) If you want to run a specific single demo, please locate to the directory of the demo, for example locate to “\examples\simple_demo\annotation”, and run this demo by “RunDemo.bat” for Windows or by “RunDemo.sh” for Linux.
“\examples\simple_demo\input_files” contains all the input files used among these demos. Some demos will generate output files (pdf, text or image files) to a folder named by the demo name under “\examples\simple_demo\output_files\”.
OCR and Compliance demos
For ocr and compliance demos, you should build a resource directory at first, please contact Foxit support team or sales team to get the resource files packages. For more details about how to run the demos, please refer to section “OCR” and section “Compliance”.
HTML to PDF demo
For html2pdf demo, you should contact Foxit support team or sales team to get the engine files package for converting from HTML to PDF at first. For more details about how to run the demo, please refer to section “HTML to PDF Conversion”.
Office to PDF demo
For office2pdf demo, you should make sure that Microsoft Office 2007 version or higher is already installed and the default Microsoft virtual printer is already set on your Windows system. Then, run the demo following the steps as the other demos.
Output Preview demo
For output preview demo, you should set the folder path which contains default icc profile files. For more details about how to run the demos, please refer to section “Output Preview”.
Run a demo using Eclipse IDE
In order to reduce the size of the package, we did not provide the Eclipse project for the demos. Therefore, if you want to run a demo in Eclipse IDE, you should do the steps below:
1) Create a Java project in Eclipse, and then refer to the steps 1)-3) in the next section “How to create a simple project” to integrate the libraries into the project.
2) Copy the java file of the demo that you want to run, and then paste it to the project. For example, for image2pdf demo, copy the “image2pdf.java” file (under “\examples\simple_demo\image2pdf”) to the “src” folder of the project.
3) Open the Java file, modify the output_path and input_path path as your need. For example, if you want to use the default test files in the code, you may need to use an absolute path which points to the “output_files” and “input_files” folders in the “examples\simple_demo”.
4) Run the demo. Right-click the project, choose Run As -> Java Application to run the project.
Note:
For ocr and compliance demos, you should build a resource directory referring to section “OCR” and section “Compliance“.
For html2pdf demo, you should get the engine files package for converting from HTML to PDF, and then specify the html2pdf engine directory, referring to section “HTML to PDF Conversion“.
For office2pdf demo, you should make sure that Microsoft Office 2007 version or higher is already installed and the default Microsoft virtual printer is already set on your Windows system. Then, run the demo following the steps as the other demos.
For output preview demo, you should set the folder path which contains default icc profile files referring to section “Output Preview“.
How to create a simple project
In this section, we will show you how to use Foxit PDF SDK for Windows Java (Linux Java is similar to Windows Java) to create a simple project that renders the first page of a PDF to a bitmap and saves it as a JPG image. For better writing code, we use Eclipse IDE to create a Java project called “test”. Then follow the steps below:
1) Copy “lib” folder from the download package to the project folder, and then refresh the project. The structure of the test project is shown in Figure 2-2.
Figure 2-2
2) Add “fsdk.jar” to the project. Right click the test project, select “Build Path > Configure Build Path > Libraries > Add JARs”, and choose the “fsdk.jar” in “test/lib” as shown in Figure 2-3.
Figure 2-3
3) Configure build path for .dll (for Windows) or .so (for Linux). Right click the test project, select “Build Path > Configure Build Path > Source > Native library location: (None) > Edit”, and locate to the “test/lib” folder as shown in Figure 2-4.
Figure 2-4
4) Create a new class file called test.java under “test/src/test” directory.
5) Open the “test.java” file, import the classes that you need to use in “fsdk.jar”. Here, we just import the classes as follows:
import com.foxit.sdk.PDFException; import com.foxit.sdk.common.Bitmap; import com.foxit.sdk.common.Image; import com.foxit.sdk.common.Library; import com.foxit.sdk.common.Renderer; import com.foxit.sdk.common.fxcrt.Matrix2D; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage;
6) Load and initialize the PDF SDK library. The project can automatically load the proper library for your system with the following code. If your system is 64 bit, the fsdk_java_win64.dll library will be loaded, or loading the fsdk_java_win32.dll library. Then, initialize the library with the license files. The trial license files can be found in the “lib” folder.
// Load the library. static { if(System.getProperty("sun.arch.data.model").equals("64")) { System.loadLibrary("fsdk_java_win64"); } else { System.loadLibrary("fsdk_java_win32"); } } // Initialize the library. // The value of "sn" can be got from "gsdk_sn.txt" (the string after "SN="). // The value of "key" can be got from "gsdk_key.txt" (the string after "Sign="). int error_code = Library.initialize("sn", "key"); if (error_code != e_ErrSuccess) { return; }
7) Load a PDF document, and parse the first page of the document. Assume that you have already put a “Sample.pdf” to the “test” folder.
// load a "Sample.pdf" document. PDFDoc doc = new PDFDoc("Sample.pdf"); error_code = doc.load(null); if (error_code != e_ErrSuccess) { return; } // Get the first page of the document. PDFPage page = doc.getPage(0); // Parse page. page.startParse(e_ParsePageNormal, null, false);
8) Render the first page to a bitmap and save it as a JPG file.
int width = (int) page.getWidth(); int height = (int) page.getHeight(); Matrix2D matrix = page.getDisplayMatrix(0, 0, width, height, page.getRotation()); // Prepare a bitmap for rendering. Bitmap bitmap = new Bitmap(width, height, e_DIBArgb, null, 0); bitmap.fillRect(0xFFFFFFFF, null); // Render page Renderer render = new Renderer(bitmap, false); render.startRender(page, matrix, null); // Add the bitmap to image and save the image. Image image = new Image(); image.addFrame(bitmap); image.saveAs("testpage.jpg");
9) Build and Run the project. Right-click the test project in package explorer, and then choose “Run as > Java Application” to run it. The “testpage.jpg” will be generated in the “test” folder (See Figure 2-5).
Figure 2-5
The final contents of “test.java” is as follow:
package test; import com.foxit.sdk.PDFException; import com.foxit.sdk.common.Bitmap; import com.foxit.sdk.common.Image; import com.foxit.sdk.common.Library; import com.foxit.sdk.common.Renderer; import com.foxit.sdk.common.fxcrt.Matrix2D; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import static com.foxit.sdk.common.Bitmap.e_DIBArgb; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import static com.foxit.sdk.pdf.PDFPage.e_ParsePageNormal; public class test { // Load the library. static { if(System.getProperty("sun.arch.data.model").equals("64")) { System.loadLibrary("fsdk_java_win64"); } else { System.loadLibrary("fsdk_java_win32"); } } public static void main(String[] args) throws PDFException { // The value of "sn" can be got from "gsdk_sn.txt" (the string after "SN="). // The value of "key" can be got from "gsdk_key.txt" (the string after "Sign="). String sn = " "; String key = " "; int error_code = Library.initialize(sn, key); if (error_code != e_ErrSuccess) { return; } // load a "Sample.pdf" document. PDFDoc doc = new PDFDoc("Sample.pdf"); error_code = doc.load(null); if (error_code != e_ErrSuccess) { return; } // Get the first page of the document. PDFPage page = doc.getPage(0); // Parse page. page.startParse(e_ParsePageNormal, null, false); int width = (int) page.getWidth(); int height = (int) page.getHeight(); Matrix2D matrix = page.getDisplayMatrix(0, 0, width, height, page.getRotation()); // Prepare a bitmap for rendering. Bitmap bitmap = new Bitmap(width, height, e_DIBArgb, null, 0); bitmap.fillRect(0xFFFFFFFF, null); // Render page. Renderer render = new Renderer(bitmap, false); render.startRender(page, matrix, null); // Add the bitmap to image and save the image. Image image = new Image(); image.addFrame(bitmap); image.saveAs("testpage.jpg"); } }
Note: If you have not installed Eclipse IDE in your machine, you can create a Java file, and then use command line to build and run it. For example, we use the test.java file created in the previous Eclipse IDE, and then follow the steps below:
1) Create a folder named “test_cm”. Put the test.java into this folder. (Please note that you need to delete the first line “package test;” in the “test.java”).
2) Copy “lib” folder to the same folder (test_cm) with “test.java”.
3) Put a PDF document named “Sample.pdf” into “test_cm” folder.
4) Open command line window and navigate to “test_cm” folder, and then use the following commands to build and run the Java file.
For Windows,
javac -cp .;./lib/fsdk.jar *.java java -Djava.library.path=lib -classpath .;lib/fsdk.jar test
For Linux,
javac -cp .:./lib/fsdk.jar *.java java -Djava.library.path=lib -classpath .:lib/fsdk.jar test
Working with SDK API
In this section, we will introduce a set of major features and list some examples for each feature to show you how to integrate powerful PDF capabilities with your applications using Foxit PDF SDK Java API. You can refer to the API reference [2] to get more details about the APIs used in all of the examples.
Initialize Library
It is necessary for applications to initialize and unlock Foxit PDF SDK license before calling any APIs. The function Library.initialize is provided to initialize Foxit PDF SDK. A license should be purchased for the application and pass unlock key and code to get proper supports. When there is no need to use Foxit PDF SDK any more, please call function Library.release to release it. Before initializing library, you should load the proper library for your system at first.
Note The parameter “sn” can be found in the “gsdk_sn.txt” (the string after “SN=”) and the “key” can be found in the “gsdk_key.txt” (the string after “Sign=”).
Example:
How to initialize Foxit PDF SDK
import com.foxit.sdk.common.*; import static com.foxit.sdk.common.Constants.e_ErrSuccess; // Load the library. // You can also use System.load("filename") instead. The filename argument must be an absolute path name. static { String os = System.getProperty("os.name"); if(os.toLowerCase().startsWith("win")){ if(System.getProperty("sun.arch.data.model").equals("64")) { System.loadLibrary("fsdk_java_win64"); } else { System.loadLibrary("fsdk_java_win32"); } } else { if(System.getProperty("sun.arch.data.model").equals("64")) { System.loadLibrary("fsdk_java_linux64"); } else { System.loadLibrary("fsdk_java_linux32"); } } } // Initialize the library. String sn = " "; String key = " "; int error_code = Library.initialize(sn, key); if (error_code != e_ErrSuccess) return; ...
Document
A PDF document object can be constructed with an existing PDF file from file path, memory buffer, a custom implemented ReaderCallback object and an input file stream. Then call function PDFDoc.load or PDFDoc.startLoad to load document content. A PDF document object is used for document level operation, such as opening and closing files, getting page,, metadata and etc.
Example:
How to create a PDF document from scratch
import static com.foxit.sdk.pdf.PDFDoc.*; ... PDFDoc doc = new PDFDoc();
Note: It creates a new PDF document without any pages.
How to load an existing PDF document from file path
import static com.foxit.sdk.pdf.PDFDoc.*; import static com.foxit.sdk.common.Constants.e_ErrSuccess; ... PDFDoc doc = new PDFDoc("sample.pdf"); int error_code = doc.load(null); if (error_code != e_ErrSuccess) return;
How to load an existing PDF document from a memory buffer
import static com.foxit.sdk.pdf.PDFDoc.*; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import java.io.FileInputStream; import java.io.BufferedInputStream; ... BufferedInputStream bis = new BufferedInputStream(new FileInputStream("sample.pdf")); byte[] b = new byte[bis.available()]; bis.read(b); PDFDoc doc = new PDFDoc(b); error_code = doc.load(null); if (error_code != e_ErrSuccess) return;
How to load an existing PDF document from a file read callback object
import static com.foxit.sdk.pdf.PDFDoc.*; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import java.io.IOException; import com.foxit.sdk.common.fxcrt.FileReaderCallback; import java.io.RandomAccessFile; ... class FileReader extends FileReaderCallback { private RandomAccessFile file_ = null; FileReader() { } boolean LoadFile(String file_path) throws FileNotFoundException { file_ = new RandomAccessFile(file_path, "r"); return true; } @Override public long getSize() { try { return this.file_.length(); } catch (IOException e) { e.printStackTrace(); } return 0; } @Override public boolean readBlock(byte[] buffer, long offset, long size) { try { file_.seek(offset); int read = file_.read(buffer, 0, (int) size); return read == size ? true : false; } catch (IOException e) { e.printStackTrace(); } return false; } public void release() { try { this.file_.close(); } catch (IOException e) { e.printStackTrace(); } } } FileReader callback = new FileReader(); callback.LoadFile("sample.pdf"); PDFDoc doc = new PDFDoc(callback, false); int error_code = doc.load(null); if (error_code != e_ErrSuccess) return;
How to load PDF document and get the first page of the PDF document
import static com.foxit.sdk.pdf.PDFDoc.*; import static com.foxit.sdk.pdf.PDFPage.*; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import static com.foxit.sdk.pdf.PDFPage.e_ParsePageNormal; ... PDFDoc doc = new PDFDoc("sample.pdf"); int error_code = doc.load(null); if (error_code != e_ErrSuccess) return; // Get the first page of the document. PDFPage page = doc.getPage(0); // Parse page. page.startParse(e_ParsePageNormal, null, false);
How to save a PDF to a file
import static com.foxit.sdk.pdf.PDFDoc.*; import static com.foxit.sdk.pdf.PDFPage.*; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import static com.foxit.sdk.pdf.PDFDoc.e_SaveFlagNoOriginal; ... PDFDoc doc = new PDFDoc("sample.pdf"); int error_code = doc.load(null); if (error_code != e_ErrSuccess) return; doc.saveAs("new_Sample.pdf", e_SaveFlagNoOriginal);
How to save a document into memory buffer by FileWriterCallback
import static com.foxit.sdk.pdf.PDFDoc.*; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import java.io.FileInputStream; import java.io.BufferedInputStream; ... class FileWriter extends FileWriterCallback { private ByteArrayOutputStream buf = new ByteArrayOutputStream(); @Override public long getSize() { return buf.size(); } @Override public boolean writeBlock(byte[] buffer, long offset, long size) { buf.write(buffer, (int)0, (int)size); return true; } @Override public void release() { } @Override public boolean flush() { return true; } } ... FileWriter filewriter = new FileWriter(); // Assuming PDFDoc doc has been loaded. ... doc.startSaveAs(filewriter, e_SaveFlagNoOriginal,null); ...
Page
PDF Page is the basic and important component of PDF Document. A PDFPage object is retrieved from a PDF document by function PDFDoc.getPage. Page level APIs provide functions to parse, render, edit (includes creating, deleting and flattening) a page, retrieve PDF annotations, read and set the properties of a page, and etc. For most cases, A PDF page needs to be parsed before it is rendered or processed.
Example:
How to get page size
import static com.foxit.sdk.pdf.PDFPage.*; ... // Assuming PDFPage page has been loaded and parsed. ... int width = (int) page.getWidth(); int height = (int) page.getHeight(); ...
How to calculate bounding box of page contents
import static com.foxit.sdk.pdf.PDFPage.*; ... // Assuming PDFPage page has been loaded and parsed. ... RectF calcRc = page.calcContentBBox(e_CalcContentsBox); float fcalcRc = calcRc.width(); float fcalcRcHeight = calcRc.height();
How to create a PDF page and set the size
import static com.foxit.sdk.pdf.PDFPage.*; ... // Assuming PDFDoc doc has been loaded. // Insert a new blank PDF page to document, which will be inserted to the first page. PDFPage newBlankPage = doc.insertPage(-1, 500, 800); // Insert a new blank PDF page to document, which will be inserted at index 1. PDFPage newBlankPage = doc.insertPage(1, 500, 800); // Insert a new blank PDF page to document, which will be inserted to the end. PDFPage newBlankPage = doc.insertPage(doc.getPageCount(), e_SizeLetter);
How to delete a PDF page
import static com.foxit.sdk.pdf.PDFDoc.*; ... // Assuming PDFDoc doc has been loaded. // Remove a PDF page by page index. doc.removePage(index); // Remove a specified PDF page. doc.removePage(page); ...
How to flatten a PDF page
import static com.foxit.sdk.pdf.PDFPage.*; ... // Assuming PDFPage page has been loaded and parsed. // Flatten all contents of a PDF page. page.flatten(true, e_FlattenAll); // Flatten a PDF page without annotations. page.flatten(true, e_FlattenNoAnnot); // Flatten a PDF page without form controls. page.flatten(true, e_FlattenNoFormControl); // Flatten a PDF page without annotations and form controls (Equals to nothing to be flattened). page.flatten(true, e_FlattenNoAnnot | e_FlattenNoFormControl); ...
How to get and set page thumbnails in a PDF document
import static com.foxit.sdk.pdf.PDFPage.*; ... // Assuming PDFPage page has been loaded and parsed. ... // Load the thumbnail bitmap. If the return value of function db.isEmpty() is true means no thumbnail can be found. Bitmap db = page.loadThumbnail(); if (!db.isEmpty()) { int dbWidth = db.getWidth(); int dbHeight = db.getHeight(); } // Set page thumbnail, db should be a valid bitmap. page.setThumbnail(db); ...
Render
PDF rendering is realized through the Foxit renderer, a graphic engine that is used to render page to a bitmap or platform graphics device. Foxit PDF SDK provides APIs to set rendering options/flags, for example set flag to decide whether to render form fields and signature, whether to draw image anti-aliasing and path anti-aliasing. To do rendering, you can use the following APIs:
- To render page and annotations, first use function Renderer.setRenderContentFlags to decide whether to render page and annotation both or not, and then use function Renderer.startRender to do the rendering. Function Renderer.startQuickRender can also be used to render page but only for thumbnail purpose.
- To render a single annotation, use function Renderer.renderAnnot.
- To render on a bitmap, use function Renderer.startRenderBitmap.
- To render a reflowed page, use function Renderer.startRenderReflowPage.
Widget annotation is always associated with form field and form control in Foxit PDF SDK. For how to render widget annotations, here is a recommended flow:
- After loading a PDF page, first render the page and all annotations in this page (including widget annotations).
- Then, if use com.foxit.sdk.pdf.interform.Filler object to fill the form, the function pdf.interform.Filler.render should be used to render the focused form control instead of the function Renderer.renderAnnot.
Example:
How to render a page to a bitmap
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.common.Bitmap; import com.foxit.sdk.common.Renderer; import com.foxit.sdk.common.fxcrt.Matrix2D; import static com.foxit.sdk.common.Bitmap.e_DIBArgb; // Assuming PDFPage page has been loaded and parsed. int width = (int) page.getWidth(); int height = (int) page.getHeight(); Matrix2D matrix = page.getDisplayMatrix(0, 0, width, height, page.getRotation()); // Prepare a bitmap for rendering. Bitmap bitmap = new Bitmap(width, height, e_DIBArgb, null, 0); bitmap.fillRect(0xFFFFFFFF, null); // Render page. Renderer render = new Renderer(bitmap, false); render.startRender(page, matrix, null); ...
How to render page and annotation
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.common.Bitmap; import com.foxit.sdk.common.Renderer; import com.foxit.sdk.common.fxcrt.Matrix2D; import static com.foxit.sdk.common.Bitmap.e_DIBArgb; // Assuming PDFPage page has been loaded and parsed. int width = (int) page.getWidth(); int height = (int) page.getHeight(); Matrix2D matrix = page.getDisplayMatrix(0, 0, width, height, page.getRotation()); // Prepare a bitmap for rendering. Bitmap bitmap = new Bitmap(width, height, e_DIBArgb, null, 0); bitmap.fillRect(0xFFFFFFFF, null); Renderer render(bitmap, false); render.setRenderContentFlags(e_RenderAnnot | e_RenderPage); render.startRender(page, matrix, null); ...
Attachment
In Foxit PDF SDK, attachments are only referred to attachments of documents rather than file attachment annotation, which allow whole files to be encapsulated in a document, much like email attachments. PDF SDK provides applications APIs to access attachments such as loading attachments, getting attachments, inserting/removing attachments, and accessing properties of attachments.
Example:
How to export the embedded attachment file from a PDF and save it as a single file
import com.foxit.sdk.PDFException; import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.Attachments; import com.foxit.sdk.pdf.FileSpec; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.objects.PDFNameTree; ... PDFNameTree empty_nametree = new PDFNameTree(); { // Get information of attachments. Attachments attachments = new Attachments(doc, empty_nametree); int count = attachments.getCount(); for (int i = 0; i < count; i++) { String key = attachments.getKey(i); FileSpec file_spec = attachments.getEmbeddedFile(key); if (!file_spec.isEmpty()) { String name = file_spec.getFileName(); if (file_spec.isEmbedded()) { String export_file_path = output_path + name; file_spec.exportToFile(export_file_path); } } } }
How to remove all the attachments of a PDF
import com.foxit.sdk.PDFException; import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.Attachments; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.objects.PDFNameTree; ... // Assuming PDFDoc doc has been loaded. PDFNameTree empty_nametree = new PDFNameTree(); { // Get information of attachments. Attachments attachments = new Attachments(doc, empty_nametree); attachments.removeAllEmbeddedFiles(); } ...
Text Page
Foxit PDF SDK provides APIs to extract, select, search and retrieve text in PDF documents. PDF text contents are stored in TextPage objects which are related to a specific page. TextPage class can be used to retrieve information about text in a PDF page, such as single character, single word, text content within specified character range or rectangle and so on. It also can be used to construct objects of other text related classes to do more operations for text contents or access specified information from text contents:
- To search text in text contents of a PDF page, construct a TextSearch object with TextPage object.
- To access text such like hypertext link, construct a PageTextLinks object with TextPage object.
Example:
How to extract text from a PDF page
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.TextPage; ... // Assuming PDFPage page has been loaded and parsed. // Get the text page object. TextPage textpage = new TextPage(page, e_ParseTextNormal); int nCharCount = textpage.getCharCount(); String texts = textpage.getChars(0, nCharCount); ...
How to select text of a rectangle area in a PDF
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.TextPage; import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.common.fxcrt.RectFArray; ... // Assuming PDFPage page has been loaded and parsed. ... TextPage textpage = new TextPage(page, e_ParseTextNormal); RectF selRc = new RectF(100,100,250,250); String selText = textpage.getTextInRect(selRc); ...
Text Search
Foxit PDF SDK provides APIs to search text in a PDF document, a XFA document, a text page or in a PDF annotation’s appearance. It offers functions to do a text search and get the searching result:
- To specify the searching pattern and options, use functions TextSearch.setPattern, TextSearch.setStartPage (only useful for a text search in PDF document), TextSearch.setEndPage (only useful for a text search in PDF document) and TextSearch.setSearchFlags.
- To do the searching, use function TextSearch.findNext or TextSearch.findPrev.
- To get the searching result, use function TextSearch.getMatchXXX().
Example:
How to search a text pattern in a PDF
import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.common.fxcrt.RectFArray; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.TextSearch; import com.foxit.sdk.pdf.TextPage; ... TextSearch search = new TextSearch(doc, null, TextPage.e_ParseTextNormal ); int start_index = 0, end_index = doc.getPageCount() - 1; search.setStartPage(0); search.setEndPage(doc.getPageCount() - 1); String pattern = "Foxit"; search.setPattern(pattern); int flags = e_SearchNormal; // if want to specify flags, you can do it like this: // flags |= TextSearch::e_SearchMatchCase; // flags |= TextSearch::e_SearchMatchWholeWord; // flags |= TextSearch::e_SearchConsecutive; search.setSearchFlags(flags); int match_count = 0; while (search.findNext()) { RectFArray rect_array = search.getMatchRects(); match_count++; } ...
Text Link
In a PDF page, some text contents that represent a hypertext link to a website or a resource on the intent, or an email address are the same with common texts. Prior to text link processing, user should first call PageTextLinks.getTextLink to get a textlink object.
Example:
How to retrieve hyperlinks in a PDF page
import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.annots.*; ... // Assuming PDFPage page has been loaded and parsed. ... TextPage text_page = new TextPage(page, TextPage.e_ParseTextNormal); PageTextLinks page_textlinks = new PageTextLinks(text_page); TextLink text_link = page_textlinks.getTextLink(index); // specify an index. String str_uri = text_link.getURI(); ...
Bookmark
Foxit PDF SDK provides navigational tools called Bookmarks to allow users to quickly locate and link their point of interest within a PDF document. PDF bookmark is also called outline, and each bookmark contains a destination or actions to describe where it links to. It is a tree-structured hierarchy, so function pdf.PDFDoc.getRootBookmark must be called first to get the root of the whole bookmark tree before accessing to the bookmark tree. Here, “root bookmark” is an abstract object which can only have some child bookmarks without next sibling bookmarks and any data (includes bookmark data, destination data and action data). It cannot be shown on the application UI since it has no data. Therefore, a root bookmark can only call function Bookmark.getFirstChild.
After the root bookmark is retrieved, following functions can be called to access other bookmarks:
- To access the parent bookmark, use function Bookmark.getParent.
- To access the first child bookmark, use function Bookmark.getFirstChild.
- To access the next sibling bookmark, use function Bookmark.getNextSibling.
- To insert a new bookmark, use function Bookmark.insert.
- To move a bookmark, use function Bookmark.moveTo.
Example:
How to find and list all bookmarks of a PDF
import com.foxit.sdk.pdf.Bookmark; import com.foxit.sdk.pdf.PDFDoc; ... // Assuming PDFDoc doc has been loaded. ... Bookmark root = doc.getRootBookmark(); if (root.isEmpty()) { root = doc.createRootBookmark(); } String titleStr = ""; Bookmark iterBookmark = root.getFirstChild (); if (iterBookmark.isEmpty()) return; while (!iterBookmark.isEmpty()) { titleStr = iterBookmark.getTitle(); if (iterBookmark.hasChild()) { Bookmark childBookmark = iterBookmark.getFirstChild(); titleStr = childBookmark.getTitle(); } iterBookmark = iterBookmark.getNextSibling(); } ...
How to insert a new bookmark
import com.foxit.sdk.pdf.Bookmark; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.actions.Destination; import static com.foxit.sdk.pdf.Bookmark.e_PosLastChild; // Assuming PDFDoc doc has been loaded. Bookmark root = doc.getRootBookmark(); if (root.isEmpty()) { root = doc.createRootBookmark(); } Destination dest = Destination.createFitPage(doc, 0); String ws_title = String.format("A bookmark to a page (index: %d)", 0); Bookmark child = root.insert(ws_title, e_PosLastChild); child.setDestination(dest); child.setColor(0xF68C21);
Form (AcroForm)
PDF currently supports two different forms for gathering information interactively from the user – AcroForms and XFA forms. Acroforms are the original PDF-based fillable forms, based on the PDF architecture. Foxit PDF SDK provides APIs to view and edit form field programmatically. Form fields are commonly used in PDF documents to gather data. The Form class offers functions to retrieve form fields or form controls, import/export form data and other features, for example:
- To retrieve form fields, please use functions Form.getFieldCount and Form.getField.
- To retrieve form controls from a PDF page, please use functions Form.getControlCount and Form.getControl.
- To import form data from an XML file, please use function Form.importFromXML; to export form data to an XML file, please use function Form.exportToXML.
- To retrieve form filler object, please use function Form.getFormFiller.
To import form data from a FDF/XFDF file or export such data to a FDF/XFDF file, please refer to functions pdf.PDFDoc.importFromFDF and pdf.PDFDoc.exportToFDF.
Example:
How to load the forms in a PDF
import com.foxit.sdk.pdf.interform.Form; ... // Assuming PDFDoc doc has been loaded. ... Boolean hasForm = doc.hasForm(); if(hasForm) Form form = new Form(doc); ...
How to count form fields and get the properties
import com.foxit.sdk.pdf.interform.Form; import com.foxit.sdk.pdf.interform.Control; import com.foxit.sdk.pdf.interform.Field; ... // Assuming PDFDoc doc has been loaded. ... Form form = new Form(doc); String filter = ""; int nControlCount = form.getFieldCount(filter); for (int i=0; i<nControlCount; i++) { Field field = form.getField(i, filter); String fdName = field.getName(); String fdValue = field.getValue(); String DefaultValue = field.getDefaultValue(); } ...
How to export the form data in a PDF to a XML file
import com.foxit.sdk.pdf.interform.Form; ... // Assuming PDFDoc doc has been loaded. ... Form form = new Form(doc); form.exportToXML("form.xml"); ...
How to import form data from a XML file
import com.foxit.sdk.pdf.interform.Form; ... Form form = new Form(doc); form.importFromXML("form.xml"); ...
XFA Form
XFA (XML Forms Architecture) forms are XML-based forms, wrapped inside a PDF. The XML Forms Architecture provides a template-based grammar and a set of processing rules that allow uses to build interactive forms. At its simplest, a template-based grammar defines fields in which a user provides data.
Foxit PDF SDK provides APIs to render the XFA form, fill the form, export or import form’s data.
Note:
- Foxit PDF SDK provides two callback classes com.foxit.sdk.addon.xfa.AppProviderCallback and com.foxit.sdk.addon.xfa.DocProviderCallback to represent the callback objects as an XFA document provider and an XFA application provider respectively. All the functions in those classes are used as callback functions. Pure virtual functions should be implemented by users.
- To use the XFA form feature, please make sure the license key has the permission of the ‘XFA’ module.
Example:
How to load XFADoc and represent an Interactive XFA form
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.PDFException; import com.foxit.sdk.common.Library; import com.foxit.sdk.common.WStringArray; import com.foxit.sdk.common.Constants; import com.foxit.sdk.addon.xfa.*; import com.foxit.sdk.addon.xfa.XFADoc.*; import com.foxit.sdk.common.fxcrt.*; import com.foxit.sdk.common.WStringArray; ... try { // Create com.foxit.sdk.addon.xfa.AppProviderCallback handler. XFAAppHandler xfa_app = new XFAAppHandler(); // Register it in application. Library.registerXFAAppProviderCallback(xfa_app); String input_file = input_path + "xfa_dynamic.pdf"; PDFDoc doc = new PDFDoc(input_file); int error_code = doc.load(null); if (error_code != e_ErrSuccess) return; // Create com.foxit.sdk.addon.xfa.DocProviderCallback handler. XFADocHandler xfa_dochandler = new XFADocHandler(); // Load xfa document from pdf document. XFADoc xfa_doc = new XFADoc(doc, xfa_dochandler); xfa_doc.startLoad(null); } catch (PDFException e) { System.out.println(e.getMessage()); return; } ...
How to export and import XFA form data
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.PDFException; import com.foxit.sdk.common.Library; import com.foxit.sdk.common.WStringArray; import com.foxit.sdk.common.Constants; import com.foxit.sdk.addon.xfa.*; import com.foxit.sdk.addon.xfa.XFADoc.*; import com.foxit.sdk.common.fxcrt.*; import com.foxit.sdk.common.WStringArray; ... // Assuming XFADoc xfa_doc has been loaded. String output_xml = "xfa_form.xml"; xfa_doc.exportData(output_xml, XFADoc.e_ExportDataTypeXML); xfa_doc.resetForm(); doc.saveAs("xfa_dynamic_resetform.pdf", PDFDoc.e_SaveFlagNormal); xfa_doc.importData(output_xml); doc.saveAs("xfa_dynamic_importdata.pdf", PDFDoc.e_SaveFlagNormal); ...
Form Design
Fillable PDF forms (AcroForm) are especially convenient for preparation of various applications, such as taxes and other government forms. Form design provides APIs to add or remove form fields (Acroform) to or from a PDF file. Designing a form from scratch allows developers to create the exact content and layout of the form they want.
Example:
How to add a text form field to a PDF
import com.foxit.sdk.pdf.interform.Form; import com.foxit.sdk.pdf.interform.Control; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.common.fxcrt.RectF; ... // Assuming PDFDoc doc has been loaded. ... Form form = new Form(doc); Control control = form.addControl(page, "Text Field0", Field.e_TypeTextField, new RectF(50, 600, 90, 640)); control.getField().setValue("3"); // Update text field's appearance. control.getWidget().resetAppearanceStream(); ...
How to remove a text form field from a PDF
import com.foxit.sdk.pdf.interform.Form; import com.foxit.sdk.pdf.interform.Control; import com.foxit.sdk.pdf.interform.Field; ... // Assuming PDFDoc doc has been loaded. ... Form form = new Form(doc); int nControlCount = form.getFieldCount("Text Field0"); if (nControlCount > 0) { Field field = form.getField(0, "Text Field0"); form.removeField(field); } ...
Annotations
General
An annotation associates an object such as note, line, and highlight with a location on a page of a PDF document. It provides a way to interact with users by means of the mouse and keyboard. PDF includes a wide variety of standard annotation types as listed in Table 3. Among these annotation types, many of them are defined as markup annotations for they are used primarily to mark up PDF documents. These annotations have text that appears as part of the annotation and may be displayed in other ways by a conforming reader, such as in a Comments pane. The ‘Markup’ column in Table 3 shows whether an annotation is a markup annotation.
Foxit PDF SDK supports most annotation types defined in PDF reference [1]. PDF SDK provides APIs of annotation creation, properties access and modification, appearance setting and drawing.
Table 31
Annotation type | Description | Markup | Supported by SDK |
Text(Note) | Text annotation | Yes | Yes |
Link | Link Annotation | No | Yes |
FreeText (TypeWriter/TextBox/Callout) |
Free text annotation | Yes | Yes |
Line | Line annotation | Yes | Yes |
Square | Square annotation | Yes | Yes |
Circle | Circle annotation | Yes | Yes |
Polygon | Polygon annotation | Yes | Yes |
PolyLine | PolyLine annotation | Yes | Yes |
Highlight | Highlight annotation | Yes | Yes |
Underline | Underline annotation | Yes | Yes |
Squiggly | Squiggly annotation | Yes | Yes |
StrikeOut | StrikeOut annotation | Yes | Yes |
Stamp | Stamp annotation | Yes | Yes |
Caret | Caret annotation | Yes | Yes |
Ink(pencil) | Ink annotation | Yes | Yes |
Popup | Popup annotation | No | Yes |
File Attachment | FileAttachment annotation | Yes | Yes |
Sound | Sound annotation | Yes | No |
Movie | Movie annotation | No | No |
Widget* | Widget annotation | No | Yes |
Screen | Screen annotation | No | Yes |
PrinterMark | PrinterMark annotation | No | No |
TrapNet | Trap network annotation | No | No |
Watermark* | Watermark annotation | No | Yes |
3D | 3D annotation | No | No |
Redact | Redact annotation | Yes | Yes |
Note:
1) The annotation types of widget and watermark are special. They aren’t supported in the module of ‘Annotation’. The type of widget is only used in the module of ‘form filler’ and the type of watermark only in the module of ‘watermark’.
2) Foxit SDK supports a customized annotation type called PSI (pressure sensitive ink) annotation that is not described in PDF reference [1]. Usually, PSI is for handwriting features and Foxit SDK treats it as PSI annotation so that it can be handled by other PDF products.
Example:
How to add a link annotation to a PDF page
import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.annots.Link; ... // Assuming PDFPage page has been loaded and parsed. // Add link annotation Link link = new Link(page.addAnnot(Annot.e_Link, new RectF(350, 350, 380, 400))); link.setHighlightingMode(Annot.e_HighlightingToggle); // Appearance should be reset. link.resetAppearanceStream(); ...
How to add a highlight annotation to a page and set the related annotation properties
import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.annots.Highlight; import com.foxit.sdk.common.fxcrt.PointF; import com.foxit.sdk.common.fxcrt.PointFArray; import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.pdf.annots.QuadPoints; import com.foxit.sdk.pdf.annots.QuadPointsArray; ... // Assuming PDFPage page has been loaded and parsed. // Add highlight annotation Highlight highlight = new Highlight(page.addAnnot(Annot.e_Highlight, new RectF(10, 450, 100, 550))); highlight.setContent("Highlight"); QuadPoints quad_points = new QuadPoints(); quad_points.setFirst(new PointF(10, 500)); quad_points.setSecond(new PointF(90, 500)); quad_points.setThird(new PointF(10, 480)); quad_points.setFourth(new PointF(90, 480)); QuadPointsArray quad_points_array = new QuadPointsArray(); quad_points_array.add(quad_points); highlight.setQuadPoints(quad_points_array); highlight.setSubject("Highlight"); highlight.setTitle("Foxit SDK"); highlight.setCreationDateTime(GetLocalDateTime()); highlight.setModifiedDateTime(GetLocalDateTime()); highlight.setUniqueID(RandomUID()); // Appearance should be reset. highlight.resetAppearanceStream(); ...
How to set the popup information when creating markup annotations
import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.annots.Note; import com.foxit.sdk.pdf.annots.Popup; import com.foxit.sdk.common.fxcrt.RectF; ... // Assuming PDFPage page has been loaded and parsed. // Add note annotation Note note = new Note(page.addAnnot(Annot.e_Note, new RectF(10, 350, 50, 400))); note.setIconName("Comment"); note.setSubject("Note"); note.setTitle("Foxit SDK"); note.setContent("Note annotation."); note.setCreationDateTime(GetLocalDateTime()); note.setModifiedDateTime(GetLocalDateTime()); note.setUniqueID(RandomUID()); // Add popup to note annotation Popup popup = new Popup(page.addAnnot(Annot.e_Popup, new RectF(300, 450, 500, 550))); popup.setBorderColor(0x00FF00); popup.setOpenStatus(false); popup.setModifiedDateTime(GetLocalDateTime()); note.setPopup(popup); // Appearance should be reset. note.resetAppearanceStream(); ...
How to get page transformation matrix between PDF page coordinates and rendering device coordinates
import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.common.fxcrt.Matrix2D; // Assuming PDFDoc doc has been loaded. // Assuming PDFPage page has been loaded and parsed. ... Matrix2D mtx = page.getDisplayMatrix(0, 0, width, height, page.getRotation()); RectF srcRc = new RectF(100, 200, 200, 100); RectF pageRc = new RectF(100, 200, 200, 100); mtx.transformRect(pageRc); RectF devRc = new RectF(pageRc.getLeft(), pageRc.getBottom(), pageRc.getRight(), pageRc.getTop()); Matrix2D reverse_mtx = new Matrix2D(); reverse_mtx.setReverse(mtx); reverse_mtx.transformRect(devRc); ...
How to extract the texts under text markup annotations
import com.foxit.sdk.PDFException; import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.TextPage; import com.foxit.sdk.pdf.annots.Annot; import com.foxit.sdk.pdf.annots.TextMarkup; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import static com.foxit.sdk.pdf.PDFPage.e_ParsePageNormal; // Assuming PDFDoc doc has been loaded. PDFPage page = doc.getPage(0); // Parse the first page. page.startParse(e_ParsePageNormal, null, false); // Get a TextPage object. TextPage text_page = new TextPage(page, TextPage.e_ParseTextNormal); int annot_count = page.getAnnotCount(); for (int i = 0; i < annot_count; i++) { Annot annot = page.getAnnot(i); TextMarkup text_markup = new TextMarkup(annot); if (!text_markup.isEmpty()) { // Get the texts which intersect with a text markup annotation. String text = text_page.getTextUnderAnnot(text_markup); } }
How to add richtext for freetext annotation
import com.foxit.sdk.common.Library; import com.foxit.sdk.common.Font; import com.foxit.sdk.pdf.annots.FreeText; import com.foxit.sdk.pdf.annots.RichTextStyle; // Make sure that SDK has already been initialized successfully. // Load a PDF document, get a PDF page and parse it. // Add a new freetext annotation, as text box. Annot annot = pdf_page.addAnnot(Annot.e_FreeText, new RectF(50, 50, 150, 100)); FreeText freetext = new FreeText(annot); // Set annotation's properties. // Add/insert richtext string with style. RichTextStyle richtext_style = new RichTextStyle(); richtext_style.setFont(new Font("Times New Roman", 0, Font.e_CharsetANSI, 0)); richtext_style.setText_color(0xFF0000); richtext_style.setText_size(10); freetext.addRichText("Textbox annotation ", richtext_style); richtext_style.setText_color(0x00FF00); richtext_style.setIs_underline(true); freetext.addRichText("1-underline ", richtext_style); richtext_style.setFont(new Font("Calibri", 0, Font.e_CharsetANSI, 0)); richtext_style.setText_color(0x0000FF); richtext_style.setIs_underline(false); richtext_style.setIs_strikethrough(true); int richtext_count = freetext.getRichTextCount(); freetext.insertRichText(richtext_count-1, "2_strikethrough ", richtext_style); // Appearance should be reset. freetext.resetAppearanceStream();
Import annotations from or export annotations to a FDF file
In Foxit PDF SDK, annotations can be created with data not only from applications but also from FDF files. At the same time, PDF SDK supports to export annotations to FDF files.
Example:
How to load annotations from a FDF file and add them into the first page of a given PDF
import com.foxit.sdk.common.Range; import com.foxit.sdk.fdf.FDFDoc; import com.foxit.sdk.pdf.PDFDoc; import static com.foxit.sdk.pdf.PDFDoc.e_Annots; // Assuming PDFDoc doc has been loaded. ... Range empty_range = new Range(); { String input_file = input_path + "AboutFoxit.pdf"; String fdf_file = input_path + "AnnotationData.fdf"; PDFDoc pdf_doc = new PDFDoc(input_file); error_code = pdf_doc.load(null); if (error_code != e_ErrSuccess) { System.out.println("The Doc " + input_file + " Error: " + error_code); return; } FDFDoc fdf_doc = new FDFDoc(fdf_file); pdf_doc.importFromFDF(fdf_doc, e_Annots, empty_range); } ...
Image Conversion
Foxit PDF SDK provides APIs for conversion between PDF files and images. Applications could easily fulfill functionalities like image creation and image conversion which supports the following image formats: BMP, TIFF, PNG, JPX, JPEG, and GIF. Foxit PDF SDK can make the conversion between PDF files and the supported image formats except for GIF. It only supports converting GIF images to PDF files.
Example:
How to convert PDF pages to bitmap files
import com.foxit.sdk.common.Bitmap; import com.foxit.sdk.common.Image; import com.foxit.sdk.common.Renderer; import com.foxit.sdk.common.fxcrt.Matrix2D; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import static com.foxit.sdk.common.Bitmap.e_DIBArgb; import static com.foxit.sdk.pdf.PDFPage.e_ParsePageNormal; // Assuming PDFDoc doc has been loaded. ... Image image = new Image(); // Get page count int nPageCount = doc.getPageCount(); for (int i = 0; i < nPageCount; i++) { PDFPage page = doc.getPage(i); // Parse page. page.startParse(e_ParsePageNormal, null, false); int width = (int) page.getWidth(); int height = (int) page.getHeight(); Matrix2D matrix = page.getDisplayMatrix(0, 0, width, height, page.getRotation()); // Prepare a bitmap for rendering. Bitmap bitmap = new Bitmap(width, height, e_DIBArgb, null, 0); bitmap.fillRect(0xFFFFFFFF, null); // Render page. Renderer render = new Renderer(bitmap, false); render.startRender(page, matrix, null); image.addFrame(bitmap); } ...
How to convert a image file to PDF file
import com.foxit.sdk.common.Image; import com.foxit.sdk.common.fxcrt.PointF; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import static com.foxit.sdk.pdf.PDFPage.e_ParsePageNormal; import static com.foxit.sdk.pdf.PDFPage.e_SaveFlagNoOriginal; Image image = new Image(input_file); int count = image.getFrameCount(); PDFDoc doc = new PDFDoc(); for (int i = 0; i < count; i++) { PDFPage page = doc.insertPage(i, PDFPage.e_SizeLetter); page.startParse(e_ParsePageNormal, null, false); // Add image to page. page.addImage(image, i, new PointF(0, 0), page.getWidth(), page.getHeight(), true); } doc.saveAs("convertedPDF.pdf", e_SaveFlagNoOriginal); ...
Watermark
Watermark is a type of PDF annotation and is widely used in PDF document. Watermark is a visible embedded overlay on a document consisting of text, a logo, or a copyright notice. The purpose of a watermark is to identify the work and discourage its unauthorized use. Foxit PDF SDK provides APIs to work with watermark, allowing applications to create, insert, release and remove watermarks.
Example:
How to create a text watermark and insert it into the first page
import com.foxit.sdk.common.Font; import com.foxit.sdk.pdf.*; import com.foxit.sdk.pdf.Watermark; import com.foxit.sdk.pdf.WatermarkSettings; import com.foxit.sdk.pdf.WatermarkTextProperties; import com.foxit.sdk.common.Constants; import static com.foxit.sdk.common.Constants.e_AlignmentCenter; import static com.foxit.sdk.common.Font.e_StdIDTimesB; import static com.foxit.sdk.pdf.WatermarkSettings.*; import static com.foxit.sdk.pdf.WatermarkTextProperties.e_FontStyleNormal; ... // Assuming PDFDoc doc has been loaded. WatermarkSettings settings = new WatermarkSettings(); settings.setFlags(e_FlagASPageContents | e_FlagOnTop); settings.setOffset_x(0); settings.setOffset_y(0); settings.setOpacity(90); settings.setPosition(Constants.e_PosTopRight); settings.setRotation(-45.f); settings.setScale_x(1.f); settings.setScale_y(1.f); WatermarkTextProperties text_properties = new WatermarkTextProperties(); text_properties.setAlignment(e_AlignmentCenter); text_properties.setColor(0xF68C21); text_properties.setFont_size(e_FontStyleNormal); text_properties.setLine_space(1); text_properties.setFont_size(12.f); text_properties.setFont(new Font(e_StdIDTimesB)); Watermark watermark = new Watermark(doc, "Foxit PDF SDK\nwww.foxit.com", text_properties, settings); watermark.insertToPage(page); // Save document to file ...
How to create an image watermark and insert it into the first page
import com.foxit.sdk.common.Bitmap; import com.foxit.sdk.common.Image; import com.foxit.sdk.pdf.*; import com.foxit.sdk.pdf.Watermark; import com.foxit.sdk.pdf.WatermarkSettings; import com.foxit.sdk.common.Constants; import static com.foxit.sdk.common.Constants.e_AlignmentCenter; import static com.foxit.sdk.common.Font.e_StdIDTimesB; import static com.foxit.sdk.pdf.WatermarkSettings.*; import static com.foxit.sdk.pdf.WatermarkTextProperties.e_FontStyleNormal; ... // Assuming PDFDoc doc has been loaded. WatermarkSettings settings = new WatermarkSettings(); settings.setFlags(e_FlagASPageContents | e_FlagOnTop); settings.setOffset_x(0.f); settings.setOffset_y(0.f); settings.setOpacity(20); settings.setPosition(Constants.e_PosCenter); settings.setRotation(0.0f); Image image = new Image(image_file); Bitmap bitmap = image.getFrameBitmap(0); settings.setScale_x(page.getWidth() * 0.618f / bitmap.getWidth()); settings.setScale_y(settings.getScale_x()); Watermark watermark = new Watermark(doc, image, 0, settings); watermark.insertToPage(page); // Save document to file. ...
How to remove all watermarks from a page
import com.foxit.sdk.pdf.PDFPage; ... // Assuming PDFPage page has been loaded and parsed. ... page.removeAllWatermarks(); ... // Save document to file ...
Barcode
A barcode is an optical machine-readable representation of data relating to the object to which it is attached. Originally barcodes systematically represented data by varying the widths and spacing of parallel lines, and may be referred to as linear or one-dimensional (1D). Later they evolved into rectangles, dots, hexagons and other geometric patterns in two dimensions (2D). Although 2D systems use a variety of symbols, they are generally referred to as barcodes as well. Barcodes originally were scanned by special optical scanners called barcode readers. Later, scanners and interpretive software became available on devices including desktop printers and smartphones. Foxit PDF SDK provides applications to generate a barcode bitmap from a given string. The barcode types that Foxit PDF SDK supports are listed in Table 3-2.
Table 32
Barcode Type | Code39 | Code128 | EAN8 | UPCA | EAN13 | ITF | PDF417 | QR |
Dimension | 1D | 1D | 1D | 1D | 1D | 1D | 2D | 2D |
Example:
How to generate a barcode bitmap from a string
import com.foxit.sdk.common.Barcode; ... // Strings used as barcode content. String codeStr = "TEST-SHEET" // Barcode format types. int codeFormat = Barcode.e_FormatCode39; // Format error correction level of QR code. int qrLevel = Barcode.e_QRCorrectionLevelLow; // Image names for the saved image files for QR code. String bmpQrName = "/QR_CODE_TestForBarcodeQrCode_L.bmp"; // Unit width for barcode in pixels, preferred value is 1-5 pixels. int unitWidth = 2; // Unit height for barcode in pixels, preferred value is >= 20 pixels. int unitHeight = 120; Barcode barcode = new Barcode(); Bitmap bitmap = barcode.generateBitmap(codeStr, codeFormat, unitWidth, unitHeight, qrLevel); ...
Security
Foxit PDF SDK provides a range of encryption and decryption functions to meet different level of document security protection. Users can use regular password encryption and certificate-driven encryption, or using their own security handler for custom security implementation. It also provides APIs to integrate with the third-party security mechanism (Microsoft RMS). These APIs allow developers to work with the Microsoft RMS SDK to both encrypt (protect) and decrypt (unprotect) PDF documents.
Note: For more detailed information about the RMS encryption and decryption, please refer to the simple demo “security” in the “\examples\simple_demo” folder of the download package.
Example:
How to encrypt a PDF file with Certificate
import com.foxit.sdk.pdf.CertificateEncryptData; import com.foxit.sdk.pdf.CertificateSecurityCallback; import com.foxit.sdk.pdf.CertificateSecurityHandler; import java.io.File; import java.io.UnsupportedEncodingException; import java.security.MessageDigest; import java.util.ArrayList; import java.util.Random; import java.io.ByteArrayOutputStream; import java.io.FileInputStream; import java.util.Enumeration; import java.security.Key; import java.security.KeyStore; import java.security.cert.CertificateFactory; import javax.crypto.Cipher; ... // Assuming PDFDoc doc has been loaded. ... public static Key getPublicKey(String cerPath) { try { CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509"); FileInputStream stream = new FileInputStream(cerPath); java.security.cert.Certificate certificate = certificateFactory.generateCertificate(stream); stream.close(); return certificate.getPublicKey(); } catch (Exception e) { e.printStackTrace(); } return null; } private static byte[] cryptByKey(byte[] inputData, Key key, int opmode) { if (inputData == null) return null; // The max length of decrypted byte array: 128 final int max_crypt_block = 128; try { Cipher cipher = Cipher.getInstance(key.getAlgorithm()); cipher.init(opmode, key); int len = inputData.length; ByteArrayOutputStream stream = new ByteArrayOutputStream(); int offSet = 0; byte[] data; // Decrypt data segment by segment while (len > offSet) { data = cipher.doFinal(inputData, offSet, (len - offSet > max_crypt_block) ? max_crypt_block : (len - offSet)); stream.write(data, 0, data.length); offSet += max_crypt_block; } byte[] outputData = stream.toByteArray(); stream.close(); return outputData; } catch (Exception e) { e.printStackTrace(); } return null; } public static byte[] encryptByKey(byte[] plainData, Key key) { return cryptByKey(plainData, key, Cipher.ENCRYPT_MODE); } public class CertificateSecurityEvent extends CertificateSecurityCallback { private String filePath; private String password; public CertificateSecurityEvent(String filePath, String password) { this.filePath = filePath; this.password = password; } @Override public void release() {} @Override public byte[] getDecryptionKey(byte[] arg0) { return CryptUtil.decryptByKey(arg0, CryptUtil.getPrivateKey(filePath, password)); } } Random rand = new Random(23); byte[] seed = new byte[24]; rand.nextBytes(seed); for (int i = 20; i < 24; i++) { seed[i] = (byte) 0xFF; } PDFDoc doc = new PDFDoc(input_file); int error_code = doc.load(null); if (error_code != e_ErrSuccess) { System.out.println("The Doc " + input_file + " Error: " + error_code); return; } // Do encryption. String cert_file_path = input_path + "foxit.cer"; ArrayList<byte[]> envelopes = new ArrayList<byte[]>(); byte[] bytes=null; try { bytes = CryptUtil.encryptByKey(seed, CryptUtil.getPublicKey(cert_file_path)); envelopes.add(bytes); } catch (Exception e) { System.out.println("[Failed] Cannot get certificate information from " + cert_file_path); return; } byte[] data=new byte[20+bytes.length]; System.arraycopy(seed, 0, data, 0, 20); System.arraycopy(bytes, 0, data, 20, bytes.length); MessageDigest messageDigest = MessageDigest.getInstance("SHA1"); messageDigest.update(data); byte[] initial_key = new byte[16]; System.arraycopy(messageDigest.digest(),0,initial_key,0,16); CertificateSecurityHandler handler = new CertificateSecurityHandler(); CertificateEncryptData encrypt_data = new CertificateEncryptData(true, SecurityHandler.e_CipherAES, envelopes); handler.initialize(encrypt_data, initial_key); doc.setSecurityHandler(handler); String output_file = output_directory + "certificate_encrypt.pdf"; doc.saveAs(output_file, PDFDoc.e_SaveFlagNoOriginal); ...
How to encrypt a PDF file with Foxit DRM
import com.foxit.sdk.pdf.DRMSecurityCallback; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.SecurityHandler; ... public class DRMSecurityEvent extends DRMSecurityCallback { private String fileID; private byte[] initialKey; public DRMSecurityEvent(String fileID, byte[] initialKey) { this.fileID = fileID; this.initialKey = initialKey; } @Override public void release() {} @Override public int getCipherType(PDFDoc arg0, String arg1) { return SecurityHandler.e_CipherAES; } @Override public String getFileID(PDFDoc arg0, String arg1) { return fileID; } @Override public byte[] getInitialKey(PDFDoc arg0, String arg1) { return initialKey; } @Override public int getKeyLength(PDFDoc arg0, String arg1) { return 16; } @Override public int getUserPermissions(PDFDoc arg0, String arg1) { return 0xFFFFFFFC; } @Override public boolean isOwner(PDFDoc arg0, String arg1) { return true; } } PDFDoc doc = new PDFDoc(input_file); int error_code = doc.load(null); if (error_code != e_ErrSuccess) { return; } // Do encryption. DRMSecurityHandler handler = new DRMSecurityHandler(); String file_id = "Simple-DRM-file-ID"; String initialize_key = "Simple-DRM-initialize-key"; DRMEncryptData encrypt_data = new DRMEncryptData(true, "Simple-DRM-filter", SecurityHandler.e_CipherAES, 16, true, 0xfffffffc); handler.initialize(encrypt_data, file_id, initialize_key); doc.setSecurityHandler(handler); String output_file = output_directory + "foxit_drm_encrypt.pdf"; doc.saveAs(output_file, PDFDoc.e_SaveFlagNoOriginal); ...
Reflow
Reflow is a function that rearranges page content when the page size changes. It is useful for applications that have output devices with difference sizes. Reflow frees the applications from considering layout for different devices. This function provides APIs to create, render, release and access properties of ‘reflow’ pages.
Example:
How to create a reflow page and render it to a bmp file.
import com.foxit.sdk.common.Bitmap; import com.foxit.sdk.common.Image; import com.foxit.sdk.common.Renderer; import com.foxit.sdk.common.fxcrt.Matrix2D; import com.foxit.sdk.common.fxcrt.PointF; import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.common.fxcrt.RectI; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.ReflowPage; import static com.foxit.sdk.common.Bitmap.e_DIBArgb; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import static com.foxit.sdk.pdf.PDFPage.e_ParsePageNormal; import static com.foxit.sdk.pdf.ReflowPage.e_Normal; import static com.foxit.sdk.pdf.ReflowPage.e_WithImage; ... public static void SaveBitmap(Bitmap bitmap, int index, String file_name) throws PDFException { RectF margin = new RectF(50, 30, 30, 30); PointF size = new PointF(480, 800); RectI rect = new RectI(0, 0, (int) size.getX(), (int) margin.getTop()); bitmap.fillRect(0xFFFFFFFF, rect); rect = new RectI(0, (int) size.getY() - (int) margin.getBottom(), (int) size.getX(), (int) size.getY()); bitmap.fillRect(0xFFFFFFFF, rect); Image image = new Image(); image.addFrame(bitmap); String save_path; String sIndex; sIndex = "" + index; save_path = output_path + "reflow" + file_name + sIndex + ".bmp"; image.saveAs(save_path); } RectF margin = new RectF(50, 30, 30, 30); PointF size = new PointF(480, 800); int nCount = doc.getPageCount(); for (int i = 0; i < nCount; i++) { PDFPage page = doc.getPage(i); // Parse PDF page. page.startParse(e_ParsePageNormal, null, false); ReflowPage reflow_page = new ReflowPage(page); // Set some arguments used for parsing the relfow page. reflow_page.setLineSpace(0); reflow_page.setScreenMargin((int) margin.getLeft(), (int) margin.getTop(), (int) margin.getRight(), (int) margin.getBottom()); reflow_page.setScreenSize(size.getX(), size.getY()); reflow_page.setZoom(100); reflow_page.setParseFlags(e_Normal); // Parse reflow page. reflow_page.startParse(null); // Get actual size of content of reflow page. The content size does not contain the margin. float content_width = reflow_page.getContentWidth(); float content_height = reflow_page.getContentHeight(); // Create a bitmap for rendering the reflow page. The bitmap size contains the margin. Bitmap bitmap = new Bitmap((int) (content_width + margin.getLeft() + margin.getRight()), (int) (content_height + margin.getTop() + margin.getBottom()), e_DIBArgb, null, 0); bitmap.fillRect(0xFFFFFFFF, null); // Render reflow page. Renderer renderer = new Renderer(bitmap, false); Matrix2D matrix = reflow_page.getDisplayMatrix(0, 0); renderer.startRenderReflowPage(reflow_page, matrix, null); String file_name = "_single_"; SaveBitmap(bitmap, i, file_name); } ...
Asynchronous PDF
Asynchronous PDF technique is a way to access PDF pages without loading the whole document when it takes a long time. It’s especially designed for accessing PDF files on internet. With asynchronous PDF technique, applications do not have to wait for the whole PDF file to be downloaded before accessing it. Applications can open any page when the data of that page is available. It provides a convenient and efficient way for web reading applications. For how to open and parse pages with asynchronous mode, you can refer to the simple demo “async_load” in the “\examples\simple_demo” folder of the download package.
Pressure Sensitive Ink
Pressure Sensitive Ink (PSI) is a technique to obtain varying electrical outputs in response to varying pressure or force applied across a layer of pressure sensitive devices. In PDF, PSI is usually used for hand writing signatures. PSI data are collected by touching screens or handwriting on boards. PSI data contains coordinates and canvas of the operating area which can be used to generate appearance of PSI. Foxit PDF SDK allows applications to create PSI, access properties, operate on ink and canvas, and release PSI.
Example:
How to create a PSI and set the related properties for it
import com.foxit.sdk.pdf.PSI; import com.foxit.sdk.common.fxcrt.PointF; ... PSI psi = new PSI(480, 180, true); // Set ink diameter. psi.setDiameter(9); // Set ink color. psi.setColor(0x434236); // Set ink opacity. psi.setOpacity(0.8f); // Add points to pressure sensitive ink. float x = 121.3043f; float y = 326.6846f; float pressure = 0.0966f; int type = 1; PointF point = new PointF(x, y); psi.addPoint(point, type, pressure); ...
Wrapper
Wrapper provides a way for users to save their own data related to a PDF document. For example, when opening an encrypted unauthorized PDF document, users may get an error message. In this case, users can still access wrapper data even when they do not have permissions to the PDF content. The wrapper data could be used to provide information like where to get decryption method of this document.
Example:
How to open a document including wrapper data
import com.foxit.sdk.common.fxcrt.FileReaderCallback; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.WrapperData; ... PDFDoc doc = new PDFDoc(file_name); int code = doc.load(null); if (code != e_ErrSuccess) { return; } if (!doc.isWrapper()) { return; } int offset = doc.getWrapperOffset(); FileReader file_reader = new FileReader(offset); file_reader.LoadFile(file_name); PDFDoc doc_real = new PDFDoc(file_reader, false); code = doc_real.load(null); if (code != e_ErrSuccess) { return; } ...
PDF Objects
There are eight types of object in PDF: Boolean object, numerical object, string object, name object, array object, dictionary object, stream object and null object. PDF objects are document level objects that are different from page objects (see 3.23) which are associated with a specific page each. Foxit PDF SDK provides APIs to create, modify, retrieve and delete these objects in a document.
Example:
How to remove some properties from catalog dictionary
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.objects.PDFDictionary; ... PDFDictionary catalog = document.getCatalog(); if (null == catalog) { return; } String[] key_strings = {"Type", "Boolean", "Name", "String", "Array", "Dict"}; int count = key_strings.length; for (int i = 0; i < count; i++) { if (catalog.hasKey(key_strings[i])) { catalog.removeAt(key_strings[i]); } } ...
Page Object
Page object is a feature that allows novice users having limited knowledge of PDF objects to be able to work with text, path, image, and canvas objects (see 3.22 for details of PDF Objects). Foxit PDF SDK provides APIs to add and delete PDF objects in a page and set specific attributes. Using page object, users can create PDF page from object contents. Other possible usages of page object include adding headers and footers to PDF documents, adding an image logo to each page, or generating a template PDF on demand.
Example:
How to create a text object in a PDF page
import com.foxit.sdk.common.fxcrt.Matrix2D; import com.foxit.sdk.common.fxcrt.PointF; import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.graphics.*; import com.foxit.sdk.common.Font; import static com.foxit.sdk.common.Font.*; ... long position = page.getLastGraphicsObjectPosition(e_TypeText); TextObject text_object = TextObject.create(); text_object.setFillColor(0xFFFF7F00); // Prepare text state TextState state = new TextState(); state.setFont_size(80.0f); state.setFont(new Font("Simsun", e_StylesSmallCap, e_CharsetGB2312, 0)); state.setTextmode(e_ModeFill); text_object.setTextState(page, state, false, 750); // Set text. text_object.setText("Foxit Software"); long last_position = page.insertGraphicsObject(position, text_object); RectF rect = text_object.getRect(); float offset_x = (page.getWidth() - (rect.getRight() - rect.getLeft())) / 2; float offset_y = page.getHeight() * 0.8f - (rect.getTop() - rect.getBottom()) / 2; text_object.transform(new Matrix2D(1, 0, 0, 1, offset_x, offset_y), false); // Generate content page.generateContent(); ...
How to add an image logo to a PDF page
import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.graphics.*; import com.foxit.sdk.common.Font; import static com.foxit.sdk.common.Font.*; import com.foxit.sdk.common.Image; ... long position = page.getLastGraphicsObjectPosition(e_TypeImage); Image image = new Image(image_file); ImageObject image_object = ImageObject.create(page.getDocument()); image_object.setImage(image, 0); float width = image.getWidth(); float height = image.getHeight(); float page_width = page.getWidth(); float page_height = page.getHeight(); // Please notice the matrix value. image_object.setMatrix(new Matrix2D(width, 0, 0, height, (page_width - width) / 2.0f, (page_height - height) / 2.0f)); page.insertGraphicsObject(position, image_object); page.generateContent(); ...
Marked content
In PDF document, a portion of content can be marked as marked content element. Marked content helps to organize the logical structure information in a PDF document and enables stylized tagged PDF. Tagged PDF has a standard structure types and attributes that allow page content to be extracted and reused for other purposes. More details about marked content could be found in chapter 10.5 of PDF reference 1.7 [1].
Example:
How to get marked content in a page and get the tag name
import com.foxit.sdk.pdf.graphics.GraphicsObject; import com.foxit.sdk.pdf.graphics.MarkedContent; ... long position = page.getFirstGraphicsObjectPosition(e_TypeText); GraphicsObject text_obj = page.getGraphicsObject(position); MarkedContent content = text_obj.getMarkedContent(); int nCount = content.getItemCount(); // Get marked content property for (int i = 0; i < nCount; i++) { String tag_name = content.getItemTagName(i); int mcid = content.getItemMCID(i); } ...
Layer
PDF Layers, in other words, Optional Content Groups (OCG), are supported in Foxit PDF SDK. Users can selectively view or hide the contents in different layers of a multi-layer PDF document. Multi-layers are widely used in many application domains such as CAD drawings, maps, layered artwork and multi-language document, etc.
In Foxit PDF SDK, a PDF layer is associated with a layer node. To retrieve a layer node, user should construct a PDF LayerTree object first and then call function LayerTree.getRootNode to get the root layer node of the whole layer tree. Furthermore, you can enumerate all the nodes in the layer tree from the root layer node. Foxit PDF SDK provides APIs to get/set layer data, view or hide the contents in different layers, set layers’ name, add or remove layers, and edit layers.
Example:
How to create a PDF layer
import static com.foxit.sdk.pdf.LayerTree; import static com.foxit.sdk.pdf.LayerNode; ... LayerTree layertree = new LayerTree(doc); LayerNode root = layertree.getRootNode();
How to set all the layer nodes information
import com.foxit.sdk.pdf.*; ... static void setAllLayerNodesInformation(LayerNode layer_node) throws PDFException { if (layer_node.hasLayer()) { layer_node.setDefaultVisible(true); layer_node.setExportUsage(e_StateUndefined); layer_node.setViewUsage(e_StateOFF); LayerPrintData print_data = new LayerPrintData("subtype_print", e_StateON); layer_node.setPrintUsage(print_data); LayerZoomData zoom_data = new LayerZoomData(1, 10); layer_node.setZoomUsage(zoom_data); String new_name = String.format("[View_OFF_Print_ON_Export_Undefined]") + layer_node.getName(); layer_node.setName(new_name); } int count = layer_node.getChildrenCount(); for (int i = 0; i < count; i++) { LayerNode child = layer_node.getChild(i); setAllLayerNodesInformation(child); } } ...
How to edit layer tree
import com.foxit.sdk.pdf.*; ... LayerTree layertree = new LayerTree(doc); LayerNode root = layertree.getRootNode(); int children_count = root.getChildrenCount(); root.removeChild(children_count -1); LayerNode child = root.getChild(children_count - 2); LayerNode child0 = root.getChild(0); child.moveTo(child0, 0); child.addChild(0, "AddedLayerNode", true); child.addChild(0, "AddedNode", false); ...
Signature
PDF Signature module can be used to create and sign digital signatures for PDF documents, which protects the security of documents’ contents and avoids it to be tampered maliciously. It can let the receiver make sure that the document is released by the signer and the contents of the document are complete and unchanged. Foxit PDF SDK provides APIs to create digital signature, verify the validity of signature, delete existing digital signature, get and set properties of digital signature, display signature and customize the appearance of the signature form fields.
Note: Foxit PDF SDK provides default Signature callbacks which supports the following two types of signature filter and subfilter:
(1) filter: Adobe.PPKLite – subfilter: adbe.pkcs7.detached
(2) filter: Adobe.PPKLite – subfilter: adbe.pkcs7.sha1
If you use one of the above signature filter and subfilter, you can sign a PDF document and verify the validity of signature by default without needing to register a custom callback.
Example:
How to sign the PDF document with a signature
import com.foxit.sdk.pdf.*; ... String filter = "Adobe.PPKLite"; String sub_filter = "adbe.pkcs7.detached"; PDFPage pdf_page = pdf_doc.getPage(0); // Add a new signature to first page. com.foxit.sdk.pdf.Signature new_signature = AddSiganture(pdf_page, sub_filter); // Set filter and subfilter for the new signature. new_signature.setFilter(filter); new_signature.setSubFilter(sub_filter); boolean is_signed = new_signature.isSigned(); int sig_state = new_signature.getState(); String signed_pdf_path = output_directory + "signed_newsignature.pdf"; String cert_file_path = input_path + "foxit_all.pfx"; String cert_file_password = "123456"; // Cert file path will be passed back to application through callback function SignatureCallback::Sign(). // In this demo, the cert file path will be used for signing in callback function SignatureCallback::Sign(). new_signature.startSign(cert_file_path, cert_file_password.getBytes(), e_DigestSHA1, signed_pdf_path, null, null); ...
How to implement signature callback function of signing
import com.foxit.sdk.pdf.*; ... // Implementation of SignatureCallback class SignatureCallbackImpl extends SignatureCallback { private String sub_filter_; private DigestContext digest_context_ = null; byte[] arrall = null; SignatureCallbackImpl(String subfilter) { sub_filter_ = subfilter; } @Override public boolean startCalcDigest(FileReaderCallback var1, int[] var2, com.foxit.sdk.pdf.Signature var3, Object var4) { digest_context_ = new DigestContext(var1, var2, var2.length); return true; } @Override public int continueCalcDigest(Object var1, PauseCallback var2) { return com.foxit.sdk.common.Progressive.e_Finished; } @Override public byte[] getDigest(Object var1) { return arrall; } @Override public byte[] sign(byte[] digest, String cert_path, byte[] cert_password, int digest_algorithm, java.lang.Object client_data){ String encryptStr = null; try { try { FileReaderCallback filehandler = digest_context_.file_read_callback_; { long size = filehandler.getSize(); byte[] arr1 = new byte[digest_context_.byte_range_array_[1]]; filehandler.readBlock(arr1, digest_context_.byte_range_array_[0], digest_context_.byte_range_array_[1]); byte[] arr2 = new byte[digest_context_.byte_range_array_[3]]; filehandler.readBlock(arr2, digest_context_.byte_range_array_[2], digest_context_.byte_range_array_[3]); size = 0; arrall = new byte[(int) digest_context_.byte_range_array_[1] + (int) digest_context_.byte_range_array_[3]]; System.arraycopy(arr1, 0, arrall, 0, arr1.length); System.arraycopy(arr2, 0, arrall, arr1.length, arr2.length); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } encryptStr = CertUtil.SignMsg(arrall, signature.input_path + "foxit_all.pfx", "123456"); return encryptStr.getBytes(); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return null; } @Override public byte[] sign(byte[] digest, StreamCallback cert_path, byte[] cert_password, int digest_algorithm, java.lang.Object client_data){ return null; } @Override public int verifySigState(byte[] var1, byte[] var2, Object var3) { byte[] arrall_verify = null; boolean verify_state = false; try { verify_state = CertUtil.VerifyMsg(new String(var2).toLowerCase(), arrall, signature.input_path + "foxit.cer"); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } return verify_state ? com.foxit.sdk.pdf.Signature.e_StateVerifyNoChange : com.foxit.sdk.pdf.Signature.e_StateVerifyChange; } @Override public boolean isNeedPadData() {return false;} } ...
Long term validation (LTV)
From version 7.0, Foxit PDF SDK provides APIs to establish long term validation (LTV) of signatures, which is mainly used to solve the verification problem of signatures that have already expired. LTV requires DSS (Document Security Store) which contains the verification information of the signatures, as well as DTS (Document Timestamp Signature) which belongs to the type of time stamp signature.
In order to support LTV, Foxit PDF SDK provides:
- Support for adding the signatures of time stamp type, and provides a default signature callback for the subfilter “ETSI.RFC3161”.
- TimeStampServerMgr and TimeStampServer classes, which are used to set and manager the server for time stamp. The default signature callback for the subfilter “ETSI.RFC3161” will use the default time stamp server.
- LTVVerifier class which offers the functionalities of verifying signatures and adding DSS information to documents. It also provides a basic default RevocationCallback which is required by LTVVerifier.
Following lists an example about how to establish long term validation of signatures using the default signature callback for subfilter “ETSI.RFC3161” and the default RevocationCallback. For more details, please refer to the simple demo “ltv” in the “\examples\simple_demo” folder of the download package.
Example:
How to establish long term validation of signatures using the default signature callback for subfilter “ETSI.RFC3161” and the default RevocationCallback
// Initialize time stamp server manager, add and set a default time stamp server, which will be used by default signature callback for time stamp signature. TimeStampServerMgr.initialize(); TimeStampServer timestamp_server = TimeStampServerMgr.addServer(server_name, server_url, server_username, server_password); TimeStampServerMgr.setDefaultServer(timestamp_server); // Assume that "signed_pdf_path" represents a signed PDF document which contains signed signature. PDFDoc pdf_doc = new PDFDoc(signed_pdf_path); pdf_doc.startLoad(null, false, null); { // Use LTVVerifier to verify and add DSS. LTVVerifier ltv_verifier = new LTVVerifier(pdf_doc, true, true, false, LTVVerifier.e_SignatureCreationTime); // Set verifying mode which is necessary. ltv_verifier.setVerifyMode(LTVVerifier.e_VerifyModeAcrobat); SignatureVerifyResultArray sig_verify_result_array = ltv_verifier.verify(); for (long i = 0; i < sig_verify_result_array.getSize(); i++) { // ltv state would be e_LTVStateNotEnable here. int ltv_state = sig_verify_result_array.getAt(i).getLTVState(); if ((sig_verify_result_array.getAt(i).getSignatureState() & Signature.e_StateVerifyValid) == Signature.e_StateVerifyValid) ltv_verifier.addDSS(sig_verify_result_array.getAt(i)); } } // Add a time stamp signature as DTS and sign it. "saved_ltv_pdf_path" represents the newly saved signed PDF file. PDFPage pdf_page = pdf_doc.getPage(0); // The new time stamp signature will have default filter name "Adobe.PPKLite" and default subfilter name "ETSI.RFC3161". Signature timestamp_signature = pdf_page.addSignature(new RectF(), "", Signature.e_SignatureTypeTimeStamp, true); Progressive sign_progressive = timestamp_signature.startSign("", empty_str.getBytes(), Signature.e_DigestSHA256, saved_ltv_pdf_path, null, null); if (sign_progressive.getRateOfProgress() != 100) sign_progressive.resume(); // Then use LTVVeirfier to verify the new signed PDF file. PDFDoc check_pdf_doc = new PDFDoc(saved_ltv_pdf_path); check_pdf_doc.startLoad(null, false, null); { // Use LTVVeirfier to verify. LTVVerifier ltv_verifier = new LTVVerifier(pdf_doc, true, true, false, LTVVerifier.e_SignatureCreationTime); // Set verifying mode which is necessary. ltv_verifier.setVerifyMode(LTVVerifier.e_VerifyModeAcrobat); SignatureVerifyResultArray sig_verify_result_array = ltv_verifier.verify(); for (long i = 0; i < sig_verify_result_array.getSize(); i++) { // ltv state would be e_LTVStateEnable here. int ltv_state = sig_verify_result_array.getAt(i).getLTVState(); ... // User can get other information from SignatureVerifyResult. } } // Release time stamp server manager when everything is done. TimeStampServerMgr::Release();
PAdES
From version 7.0, Foxit PDF SDK also supports PAdES (PDF Advanced Electronic Signature) which is the application for CAdES signature in the field of PDF. CAdES is a new standard for advanced digital signature, its default subfilter is “ETSI.CAdES.detached”. PAdES signature includes four levels: B-B, B-T, B-LT, and B-LTA.
- B-B: Must include the basic attributes.
- B-T: Must include document time stamp or signature time stamp to provide trusted time for existing signatures, based on B-B.
- B-LT: Must include DSS/VRI to provide certificates and revocation information, based on B-T.
- B-LTA: Must include the trusted time DTS for existing revocation information, based on B-LT.
Foxit PDF SDK provides a default signature callback for the subfilter “ETSI.CAdES.detached” to sign and verify the signatures (with subfilter “ETSI.CAdES.detached”). It also provides TimeStampServerMgr and TimeStampServer classes to set and manager the server for time stamp. The default signature callback for the subfilter “ETSI.CAdES.detached” will use the default time stamp server.
Foxit PDF SDK provides functions to get the level of PAdES from signature, and application level can also judge and determine the level of PAdES according to the requirements of each level. For more details about how to add, sign and verify a PAdES signature in PDF document, please refer to the simple demo “pades” in the “\examples\simple_demo” folder of the download package.
PDF Action
PDF Action is represented as the base PDF action class. Foxit PDF SDK provides APIs to create a series of actions and get the action handlers, such as embedded goto action, JavaScript action, named action and launch action, etc.
Example:
How to create a URI action and insert to a link annot
import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.URIAction; import com.foxit.sdk.pdf.annots.Link; ... // Assuming PDFPage page has been loaded and parsed. // Assuming the annnots in the page have been loaded. // Add link annotation Link link = new Link(page.addAnnot(Annot.e_Link, new RectF(350, 350, 380, 400))); link.setHighlightingMode(Annot.e_HighlightingToggle); // Add action for link annotation Action action = Action.create(page.getDocument(), Action.e_TypeURI); URIAction uriAction = new URIAction(action); uriAction.setTrackPositionFlag(true); uriAction.setURI("www.foxit.com"); link.setAction(uriAction); // Appearance should be reset. link.resetAppearanceStream(); ...
How to create a GoTo action and insert to a link annot
import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.GotoAction; import com.foxit.sdk.pdf.annots.Link; ... // Assuming PDFPage page has been loaded and parsed. // Assuming the annnots in the page have been loaded. Link link = new Link(page.addAnnot(Annot.e_Link, new RectF(350, 350, 380, 400))); link.setHighlightingMode(Annot.e_HighlightingToggle); // Add action for link annotation Action action = Action.create(page.getDocument(), Action.e_TypeGoto); GotoAction gotoAction = new GotoAction(action); Destination dest = Destination.createFitPage(doc, 0); gotoAction.setDestination(dest); ...
JavaScript
JavaScript was created to offload Web page processing from a server onto a client in Web-based applications. Foxit PDF SDK JavaScript implements extensions, in the form of new objects and their accompanying methods and properties, to the JavaScript language. It enables a developer to manage document security, communicate with a database, handle file attachments, and manipulate a PDF file so that it behaves as an interactive, web-enabled form, and so on.
JavaScript action is an action that causes a script to be compiled and executed by the JavaScript interpreter. Class com.foxit.sdk.pdf.actions.JavaScriptAction is derived from Action and offers functions to get/set JavaScript action data.
The JavaScript methods and properties supported by Foxit PDF SDK are listed in the appendix.
Example:
How to add JavaScript Action to Document
import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.JavaScriptAction; ... // Load Document doc. ... JavaScriptAction javascipt_action = new JavaScriptAction(Action.create(doc, Action.e_TypeJavaScript)); javascipt_action.setScript("app.alert(\"Hello Foxit \");"); AdditionalAction aa = new AdditionalAction(doc); aa.setAction(AdditionalAction.e_TriggerDocWillClose, javascipt_action); aa.doJSAction(AdditionalAction.e_TriggerDocWillClose); ...
How to add JavaScript Action to Annotation
import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.JavaScriptAction; ... // Load Document and get a widget annotation. ... JavaScriptAction javascipt_action = new JavaScriptAction(Action.create(page.getDocument(), Action.e_TypeJavaScript)); javascipt_action.setScript("app.alert(\"Hello Foxit \");"); AdditionalAction aa = new AdditionalAction(annot); aa.setAction(AdditionalAction.e_TriggerAnnotMouseButtonPressed, javascipt_action); aa.doJSAction(AdditionalAction.e_TriggerAnnotMouseButtonPressed); ...
How to add JavaScript Action to FormField
import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.JavaScriptAction; import com.foxit.sdk.pdf.interform.Form; import com.foxit.sdk.pdf.interform.Control; import com.foxit.sdk.pdf.interform.Field; ... // Load Document and get a form field. ... // Add text field. Control control = form.addControl(page, "Text Field0", Field.e_TypeTextField, new RectF(50, 600, 90, 640)); control.getField().setValue("3"); // Update text field's appearance. control.getWidget().resetAppearanceStream(); Control control1 = form.addControl(page, "Text Field1", Field.e_TypeTextField, new RectF(100, 600, 140, 640)); control1.getField().setValue("23"); // Update text field's appearance. control1.getWidget().resetAppearanceStream(); Control control2 = form.addControl(page, "Text Field2", Field.e_TypeTextField, new RectF(150, 600, 190, 640)); Field field2 = control2.getField(); JavaScriptAction javascipt_action = new JavaScriptAction(Action.create(form.getDocument(), Action.e_TypeJavaScript)); javascipt_action.setScript("AFSimple_Calculate(\"SUM\", new Array (\"Text Field0\", \"Text Field1\"));"); AdditionalAction aa = new AdditionalAction(field2); aa.setAction(AdditionalAction.e_TriggerFieldRecalculateValue, javascipt_action); // Update text field's appearance. control2.getWidget().resetAppearanceStream(); ...
How to add a new annotation to PDF using JavaScript
import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.JavaScriptAction; ... // Load Document and get form field, construct a Form object and a Filler object. ... JavaScriptAction javascipt_action = new JavaScriptAction(Action.create(form.getDocument(), Action.e_TypeJavaScript)); javascipt_action.setScript("var annot = this.addAnnot({ page : 0, type : \"Square\", rect : [ 0, 0, 100, 100 ], name : \"UniqueID\", author : \"A. C. Robat\", contents : \"This section needs revision.\" });"); AdditionalAction aa = new AdditionalAction(field); aa.setAction(AdditionalAction.e_TriggerAnnotCursorEnter, javascipt_action); aa.doJSAction(AdditionalAction.e_TriggerAnnotCursorEnter); ...
How to get/set properties of annotations (strokeColor, fillColor, readOnly, rect, type) using JavaScript
import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.JavaScriptAction; ... // Load Document and get form field, construct a Form object and a Filler object. ... // Get properties of annotations. JavaScriptAction javascipt_action = new JavaScriptAction(Action.create(form.getDocument(), Action.e_TypeJavaScript)); javascipt_action.setScript("var ann = this.getAnnot(0, \" UniqueID \"); if (ann != null) { console.println(\"Found it! type: \" + ann.type); console.println(\"readOnly: \" + ann.readOnly); console.println(\"strokeColor: \" + ann.strokeColor);console.println(\"fillColor: \" + ann.fillColor); console.println(\"rect: \" + ann.rect);}"); AdditionalAction aa = new AdditionalAction(field); aa.setAction(AdditionalAction.e_TriggerAnnotCursorEnter, javascipt_action); aa.doJSAction(AdditionalAction.e_TriggerAnnotCursorEnter); // Set properties of annotations (only take strokeColor as an example). JavaScriptAction javascipt_action1 = new JavaScriptAction(Action.create(form.getDocument(), Action.e_TypeJavaScript)); javascipt_action1.setScript("var ann = this.getAnnot(0, \"UniqueID\"); if (ann != null) { ann.strokeColor = color.blue; }"); AdditionalAction aa1 = new AdditionalAction(field1); aa1.setAction(AdditionalAction.e_TriggerAnnotCursorEnter, javascipt_action1); aa1.doJSAction(AdditionalAction.e_TriggerAnnotCursorEnter); ...
How to destroy annotation using JavaScript
import com.foxit.sdk.pdf.actions.Action; import com.foxit.sdk.pdf.actions.JavaScriptAction; ... // Load Document and get form field, construct a Form object and a Filler object. ... JavaScriptAction javascipt_action = new JavaScriptAction(Action.create(form.getDocument(), Action.e_TypeJavaScript)); javascipt_action.setScript("var ann = this.getAnnot(0, \" UniqueID \"); if (ann != null) { ann.destroy(); } "); AdditionalAction aa = new AdditionalAction(field); aa.setAction(AdditionalAction.e_TriggerAnnotCursorEnter, javascipt_action); aa.doJSAction(AdditionalAction.e_TriggerAnnotCursorEnter); ...
Redaction
Redaction is the process of removing sensitive information while keeping the document’s layout. It allows users to permanently remove (redact) visible text and images from PDF documents to protect confidential information, such as social security numbers, credit card information, product release dates, and so on.
Redaction is a type of markup annotation, which is used to mark some contents of a PDF file and then the contents will be removed once the redact annotations are applied.
To do Redaction, you can use the following APIs:
- Call function com.foxit.sdk.addon.Redaction.Redaction to create a redaction module. If module “Redaction” is not defined in the license information which is used in function common.Library.initialize, it means user has no right in using redaction related functions and this constructor will throw exception com.foxit.sdk.common.Constants.e_ErrInvalidLicense .
- Then call function com.foxit.sdk.addon.Redaction.markRedactAnnot to create a redaction object and mark page contents (text object, image object, and path object) which are to be redacted.
- Finally call function com.foxit.sdk.addon.Redaction.apply to apply redaction in marked areas: remove the text or graphics under marked areas permanently.
Note: To use the redaction feature, please make sure the license key has the permission of the ‘Redaction’ module.
Example:
How to redact the text “PDF” on the first page of a PDF
import com.foxit.sdk.common.fxcrt.RectFArray; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.TextPage; import com.foxit.sdk.pdf.TextSearch; import com.foxit.sdk.addon.Redaction; import com.foxit.sdk.pdf.annots.Redact; ... // Assuming PDFDoc doc has been loaded. ... Redaction redaction = new Redaction(doc); PDFPage page = doc.getPage(0); // Parse PDF page. page.startParse(PDFPage.e_ParsePageNormal, null, false); TextPage text_page = new TextPage(page, TextPage.e_ParseTextNormal); TextSearch text_search = new TextSearch(text_page); text_search.setPattern("PDF"); RectFArray matched_rect_array = new RectFArray(); while (text_search.findNext()) { RectFArray temp_rect_array = text_search.getMatchRects(); for (int z=0; z<temp_rect_array.getSize(); z++) matched_rect_array.add(temp_rect_array.getAt(z)); } if (matched_rect_array.getSize()>0) { Redact redact = redaction.markRedactAnnot(page, matched_rect_array); redact.resetAppearanceStream(); doc.saveAs(output_path + "AboutFoxit_redected_default.pdf", PDFDoc.e_SaveFlagNormal); // set border color to Green redact.setBorderColor((long)0x00FF00); // set fill color to Blue redact.setFillColor((long)0x0000FF); // set rollover fill color to Red redact.setApplyFillColor((long)0xFF0000); redact.resetAppearanceStream(); doc.saveAs(output_path + "AboutFoxit_redected_setColor.pdf", PDFDoc.e_SaveFlagNormal); redact.setOpacity((float)0.5); redact.resetAppearanceStream(); doc.saveAs(output_path+"AboutFoxit_redected_setOpacity.pdf", PDFDoc.e_SaveFlagNormal); redaction.apply(); } ...
Comparison
Comparison feature lets you see the differences in two versions of a PDF. Foxit PDF SDK provides APIs to compare two PDF documents page by page, the differences between the two documents will be returned.
The differences can be defined into three types: delete, insert and replace. You can save these differences into a PDF file and mark them as annotations.
Note: To use the comparison feature, please make sure the license key has the permission of the ‘Comparison’ module
Example:
How to compare two PDF documents and save the differences between them into a PDF file
import com.foxit.sdk.common.fxcrt.RectF; import com.foxit.sdk.common.fxcrt.PointF; import com.foxit.sdk.common.fxcrt.RectFArray; import com.foxit.sdk.common.Image; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.addon.comparison.CompareResultInfo; import com.foxit.sdk.addon.comparison.CompareResultInfoArray; import com.foxit.sdk.addon.comparison.CompareResults; import com.foxit.sdk.addon.comparison.Comparison; import com.foxit.sdk.common.DateTime; import com.foxit.sdk.pdf.annots.Annot; import com.foxit.sdk.pdf.annots.Highlight; import com.foxit.sdk.pdf.annots.Stamp; import com.foxit.sdk.pdf.annots.QuadPoints; import com.foxit.sdk.pdf.annots.QuadPointsArray; ... PDFDoc base_doc = new PDFDoc("input_base_file"); error_code = base_doc.load(null); if (error_code != e_ErrSuccess) { return; } PDFDoc compared_doc = new PDFDoc("input_compared_file"); error_code = compared_doc.load(null); if (error_code != e_ErrSuccess) { return; } Comparison comparison = new Comparison(base_doc, compared_doc); // Start comparing. CompareResults result = comparison.doCompare(0, 0, Comparison.e_CompareTypeText); CompareResultInfoArray oldInfo = result.getResults_base_doc(); CompareResultInfoArray newInfo = result.getResults_compared_doc(); long oldInfoSize = oldInfo.getSize(); long newInfoSize = newInfo.getSize(); PDFPage page = compared_doc.getPage(0); for (int i=0; i<newInfoSize; i++) { CompareResultInfo item = newInfo.getAt(i); int type = item.getType(); if (type == CompareResultInfo.e_CompareResultTypeDeleteText) { String res_string; res_string = String.format("\"%s\"", item.getDiff_contents()); // Add stamp to mark the "delete" type differences between the two documents. CreateDeleteTextStamp(page, item.getRect_array(), 0xff0000, res_string, "Compare : Delete", "Text"); } else if (type == CompareResultInfo.e_CompareResultTypeInsertText) { String res_string; res_string = String.format("\"%s\"", item.getDiff_contents()); // Highlight the "insert" type differences between the two documents. CreateHighlightRect(page, item.getRect_array(), 0x0000ff, res_string, "Compare : Insert", "Text"); } else if (type == CompareResultInfo.e_CompareResultTypeReplaceText) { String res_string; res_string = String.format("[Old]: \"%s\"\r\n[New]: \"%s\"", oldInfo.getAt(i).getDiff_contents(), item.getDiff_contents()); // Highlight the "replace" type differences between the two documents. CreateHighlightRect(page, item.getRect_array(), 0xe7651a, res_string, "Compare : Replace", "Text"); } } // Save the comparison result to a PDF file. compared_doc.saveAs(output_path + "result.pdf", PDFDoc.e_SaveFlagNormal);
Note: for CreateDeleteTextStamp and CreateHighlightRect functions, please refer to the simple demo “pdfcompare” located in the “\examples\simple_demo” folder of the download package.
OCR
Optical Character Recognition, or OCR, is a software process that enables images or printed text
to be translated into machine-readable text. OCR is most commonly used when scanning paper
documents to create electronic copies, but can also be performed on existing electronic
documents (e.g. PDF).
This section will provide instructions on how to set up your environment for the OCR feature module using Foxit PDF SDK for Windows (Java).
System requirements
Platform: Windows
Programming Language: C, C++, Java, C#
License Key requirement: ‘OCR’ module permission in the license key
SDK Version: Foxit PDF SDK (C++, Java, C#) 6.4 or higher; Foxit PDF SDK (C) 7.4 or higher
Trial limit for SDK OCR add-on module
For the trial version, there are three trail limits that you should notice:
1) Allow 30 consecutive natural days to evaluate SDK from the first time of OCREngine initialization.
2) Allow up to 5000 pages to be converted using OCR from the first time of OCREngine initialization.
3) Trail watermarks will be generated on the PDF pages. This limit is used for all of the SDK modules.
OCR resource files
Please contact Foxit support team or sales team to get the OCR resource files package.
After getting the package, extract it to a desired directory (for example, extract the package to a directory named “ocr_addon”), and then you can see the resource files for OCR are as follows:
- debugging_files: Resource files used for debugging the OCR project. These file(s) cannot be distributed.
- language_resource_CJK: Resource files for CJK language, including: Chinese-Simplified, Chinese-Traditional, Japanese, and Korean.
- language_resources_noCJK: Resource files for the languages except CJK, including: Basque, Bulgarian, Catalan, Croatian, Czech, Danish, Dutch, English , Estonian, Faeroese, Finnish, French, Galician, German, Greek, Hebrew, Hungarian, Icelandic, Italian, Latvian(Lettish), Lithuanian, Macedonian, Maltese, Norwegian, Polish, Portuguese, Romanian, Russian, Serbian, Slovak, Slovenian, Spanish, Swedish, Thai, Turkish, Ukrainian.
- win32_lib: 32-bit library resource files
- win64_lib: 64-bit library resource files
- readme.txt: A txt file for introducing the role of each folder in this directory, as well as how to use those resource files for OCR.
How to run the OCR demo
Foxit PDF SDK for Windows (Java) provides an OCR demo located in the “\examples\simple_demo\ocr” folder to show you how to use Foxit PDF SDK to do OCR for a PDF page or a PDF document.
Build an OCR resource directory
Before running the OCR demo, you should first build an OCR resource directory, and then pass the directory to Foxit PDF SDK API OCREngine.initialize to initialize OCR engine.
To build an OCR resource directory, please follow the steps below:
1) Create a new folder to add the resources. For example, “D:/ocr_resources”.
2) Add the appropriate library resource based on the platform architecture.
- For win32, copy all the files under “ocr_addon/win32_lib” folder to “D:/ocr_resources”.
- For win64, copy all the files under “ocr_addon/win64_lib” folder to “D:/ocr_resources”.
3) Add the language resource.
- For CJK (Chinese-Simplified, Chinese-Traditional, Japanese, and Korean), copy all the files under “ocr_addon/language_resource_CJK” folder to “D:/ocr_resources”.
- For all other languages except CJK, copy all the files under “ocr_addon/language_resources_noCJK” folder to “D:/ocr_resources”.
- For all the supported languages, copy all the files under “ocr_addon/language_resource_CJK” and “ocr_addon/language_resources_noCJK” folders to “D:/ocr_resources”.
4) (Optional) Add debugging file resource if you need to debug the demo.
- For win32, copy the file(s) under “ocr_addon/debugging_files/win32” folder to “D:/ocr_resources”.
- For win64, copy the file(s) under “ocr_addon/debugging_files/win64” folder to “D:/ocr_resources”.
Note: The debugging files should be exclusively used for testing purposes. So, you cannot distribute them.
Configure the demo
After building the OCR resource directory, configure the demo in the “\examples\simple_demo\ocr\ocr.java” file.
Specify the OCR resource directory
Add the OCR resource directory as follows, which will be used to initialize the OCR engine.
Choose the language resource
You will need to set the language used by the OCR engine into the demo code. This is done with the OCREngine.setLanguages method and is set to “English” by default.
(Optional) Set log for OCREngine
If you add the debugging file resource to the OCR resource directory, and want to print the entire log of the OCR Engine, please uncomment the OCREngine.setLogFile method as below:
Run the demo
Once you run the demo successfully, the console will print the following by default:
The demo will OCR the default document (“\examples\simple_demo\input_files\ocr\AboutFoxit_ocr.pdf”) in four different ways, which will output four different PDFs in the output folder (“\examples\simple_demo\output_files\ocr”):
- OCR Editable PDF – ocr_doc_editable.pdf
- OCR Searchable PDF – ocr_doc_searchable.pdf
- OCR Editable PDF Page – ocr_page_editable.pdf
- OCR Searchable PDF Page – ocr_page_searchable.pdf
Compliance
PDF Compliance
Foxit PDF SDK supports to convert PDF versions among PDF 1.3, PDF 1.4, PDF 1.5, PDF 1.6 and PDF 1.7. When converting to PDF 1.3, if the source document contains transparency data, then it will be converted to PDF 1.4 instead of PDF 1.3 (PDF 1.3 does not support transparency). If the source document does not contain any transparency data, then it will be converted to PDF 1.3 as expected.
PDF/A Compliance
PDF/A is an ISO-standardized version of the PDF specialized for use in the archiving and long-term preservation of electronic documents. PDF/A differs from PDF by prohibiting features unsuitable for long-term archiving, such as font linking (as opposed to font embedding), encryption, JavaScript, audio, video and so on.
Foxit PDF SDK provides APIs to convert a PDF to be compliance with PDF/A standard, or verify whether a PDF is compliance with PDF/A standard. It supports the PDF/A version including PDF/A-1a, PDF/A-1b, PDF/A-2a, PDF/A-2b, PDF/A-2u, PDF/A-3a, PDF/A-3b, PDF/A-3u (ISO 19005- 1, 19005 -2 and 19005-3).
This section will provide instructions on how to set up your environment for running the ‘compliance’ demo.
System requirements
Platform: Windows, Linux, Mac
Programming Language: C, C++, Java, C#, Objective-C
License Key requirement: ‘Compliance’ module permission in the license key
SDK Version: Foxit PDF SDK 6.4 or higher (for PDF Compliance, it requires Foxit PDF SDK 7.1 or higher)
Compliance resource files
Please contact Foxit support team or sales team to get the Compliance resource files package.
After getting the package, extract it to a desired directory (for example, extract the package to a directory: “compliance/win” for Windows, and “compliance/linux” for Linux), and then you can see the resource files for Compliance are as follows:
For Windows:
For Linux:
How to run the compliance demo
Foxit PDF SDK provides a compliance demo located in the “\examples\simple_demo\compliance” folder to show you how to use Foxit PDF SDK to verify whether a PDF is compliance with PDF/A standard, and convert a PDF to be compliance with PDF/A standard, as well as convert PDF versions.
Build a compliance resource directory
Before running the compliance demo, you should first build a compliance resource directory, and then pass the directory to Foxit PDF SDK API ComplianceEngine.initialize to initialize compliance engine.
Windows
To build a compliance resource directory on Windows, please follow the steps below:
1) Create a new folder to add the resources. For example, “D:/compliance_resources”.
2) Copy the whole folders of “ect“, “lang“, “var” under the “compliance/win” to “D:/compliance_resources”.
3) Add the appropriate library resource based on the platform architecture.
- For win32, copy all the files under “compliance/win/lib/x86” folder to “D:/compliance_resources”.
- For win64, copy all the files under “compliance/win/lib/x64” folder to “D:/compliance_resources”.
For example, use win32 platform architecture, then the compliance resource directory should be as follows:
Linux
To build a compliance resource directory on Linux, please follow the steps below:
1) Create a new folder to add the resources. For example, “/root/Desktop/compliance_resources”.
2) Copy the whole folders of “bin“, “ect“, “lang“, “var” under the “compliance/linux” to “/root/Desktop/compliance_resources”.
3) Add the appropriate library resource based on the platform architecture.
- For linux32, copy all the files under “compliance/linux/lib/x86” folder to “/root/Desktop/compliance_resources”.
- For linux64, copy all the files under “compliance/linux/lib/x64” folder to “/root/Desktop/compliance_resources”.
For example, use linux32 platform architecture, then the compliance resource directory should be as follows:
Note: For Linux platform, you should put the compliance resource directory into the search path for system shared library before running the demo, otherwise ComplianceEngine.initialize will fail.
For example, you can use the command (export LD_LIBRARY_PATH=${LD_LIBRARY_PATH}: /root/Desktop/compliance_resources) to temporarily add the compliance resource directory to LD_LIBRARY_PATH.
Configure the demo
After building the compliance resource directory, configure the demo in the “\examples\simple_demo\compliance\compliance.java” file.
This section takes Windows as an example to show you how to configure the demo in the “compliance.java” file. For Linux, do the same configuration with Windows.
Specify the compliance resource directory
In the “compliance.java” file, add the compliance resource directory as follows, which will be used to initialize the compliance engine.
Note: If you have purchased an authorization license key (includes ‘Compliance’ module permission), Foxit sales team will send you an extra unlock code for initializing compliance engine.
(Optional) Set language for compliance engine
ComplianceEngine.setLanguage function is used to set language for compliance engine. The default language is “English”, and the supported languages are as follows:
“Czech”, “Danish”, “Dutch”, “English”, “French”, “Finnish”, “German”, “Italian”, “Norwegian”, “Polish”, “Portuguese”, “Spanish”, “Swedish”, “Chinese-Simplified”, “Chinese-Traditional”, “Japanese”, “Korean”.
For example, uncomment the ComplianceEngine.setLanguage method, and set the language to “Chinese-Simplified”.
(Optional) Set a temp folder for compliance engine
ComplianceEngine.setTempFolderPath function is used to set a temp folder to store several files for proper processing (e.g verifying or converting). If no custom temp folder is set by this function, the default temp folder in system will be used.
For example, uncomment the ComplianceEngine.setTempFolderPath method, and set the path to “D:/compliance_temp” (should be a valid path).
Run the demo
Locate to “\examples\simple_demo\compliance”, and run “RunDemo.bat”, then the console will print the following by default:
The demo will
- verify whether the PDF (“\examples\simple_demo\input_files\AboutFoxit.pdf”) is compliance with PDF/A-1a standard, and convert the PDF to be compliance with PDF/A-1a standard.
- convert PDF file (“\examples\simple_demo\input_files\AF_ImageXObject_FormXObject.pdf”) to PDF-1.4 and PDF-1.7.
The output files are located in “\examples\simple_demo\output_files\compliance” folder.
Optimization
Optimization feature can reduce the size of PDF files to save disk space and make files easier to send and store, through compressing images, deleting redundant data, discarding useless user data and so on. From version 7.0, optimization module provides functions to compress the color/grayscale/monochrome images in PDF files to reduce the size of the PDF files.
Note: To use the Optimization feature, please make sure the license key has the permission of the ‘Optimization’ module.
Example:
How to optimize PDF files by compressing the color/grayscale/monochrome images
import com.foxit.sdk.common.Progressive; import com.foxit.sdk.common.Constants; import com.foxit.sdk.common.fxcrt.PauseCallback; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.addon.*; import com.foxit.sdk.addon.optimization.*; import com.foxit.sdk.addon.optimization.Optimizer; import java.io.File; import static com.foxit.sdk.common.Constants.e_ErrSuccess; import static com.foxit.sdk.pdf.PDFDoc.e_SaveFlagRemoveRedundantObjects; PDFDoc doc = new PDFDoc("input_pdf_file"); error_code = doc.load(null); if (error_code != e_ErrSuccess) { System.out.println(" Error: " + error_code); return; } PauseUtil pause = new PauseUtil(); OptimizerSettings settings = new OptimizerSettings(); System.out.println("Optimized Start."); Progressive progressive = Optimizer.optimize(doc, settings, pause); int state = Progressive.e_ToBeContinued; while (state == Progressive.e_ToBeContinued) { state = progressive.resume(); int rate = progressive.getRateOfProgress(); System.out.println("Optimize progress percent: " + rate + "%"); } if(state == Progressive.e_Finished) { doc.saveAs("ImageCompression_Optimized.pdf", e_SaveFlagRemoveRedundantObjects); } System.out.println("Optimized Finish.");
HTML to PDF Conversion
For some large HTML files or a webpage which contain(s) many contents, it is not convenient to print or archive them directly. Foxit PDF SDK provides APIs to convert the online webpage or local HTML files like invoices or reports into PDF file(s), which makes them easier to print or archive. In the process of conversion from HTML to PDF, Foxit PDF SDK also supports to create and add PDF Tags based on the organizational structure of HTML.
From version 7.6, Foxit PDF SDK supports to convert HTML to PDF on Linux platform. But for HTML to PDF engine (Linux), the version of libnss should be 3.22.
This section will provide instructions on how to set up your environment for running the ‘html2pdf’ demo on Windows platform.
System requirements
Platform: Windows, Linux, Mac
Programming Language: C, C++, Java, C#, Objective-C
License Key requirement: ‘Conversion’ module permission in the license key
SDK Version: Foxit PDF SDK 7.0 or higher
HTML to PDF engine files
Please contact Foxit support team or sales team to get the HTML to PDF engine files package.
After getting the package, extract it to a desired directory (for example, extract the package to a directory: “D:/htmltopdf/win” for Windows, and “htmltopdf/linux” for Linux).
How to run the html2pdf demo
Foxit PDF SDK provides a html2pdf demo located in the “\examples\simple_demo\html2pdf” folder to show you how to use Foxit PDF SDK to convert from html to PDF.
Configure the demo
For html2pdf demo, you can configure the demo in the “\examples\simple_demo\html2pdf\html2pdf.java” file, or you can configure the demo with parameters directly in a command prompt. Following will configure the demo in “html2pdf.java” file on Windows for example. For Linux platform, do the same configuration with Windows.
Specify the html2pdf engine directory
In the “html2pdf.java” file, add the path of the engine file “fxhtml2pdf.exe” as follows, which will be used to convert html files to PDF files.
(Optional) Specify cookies file path
Add the path of the cookies file exported from the web pages that you want to convert. For example,
Run the demo
Run the demo without parameters
Locate to “\examples\simple_demo\html2pdf”, and run “RunDemo.bat”, then the console will print the following by default:
Run the demo with parameters
Locate to “\examples\simple_demo\html2pdf”, and run “RunDemo.bat” at first.
Then, open a command prompt, navigate to “\examples\simple_demo\html2pdf”, type “java -Djava.library.path=../../../lib -classpath .;../../../lib/fsdk.jar html2pdf –help” to see how to use the parameters to execute the program.
For example, convert the URL web page “www.foxit.com” into a PDF with setting the page width to 900 points and the page height to 300 points:
The output file is located in “\examples\simple_demo\output_files\html2pdf” folder.
Parameters Description
Basic Syntax:
html2pdf <-html <the url or html path>> <-o <output pdf path>> <-engine <htmltopdf engine path>>
[-w <page width>] [-h <page height>] [-ml <margin left>] [-mr <margin right>]
[-mt <margin top>] [-mb <margin bottom>] [-r <page rotate degree>] [-mode <page mode>]
[-scale <whether scale page>] [-link <whether convert link>] [-tag <whether generate tag>]
[-cookies <cookies file path>] [-timeout <timeout>]
html2pdf –help
Note:
- <> required
- [ ] optional
Parameters | Description |
–help | The usage description of the parameters. |
-html | The url or html file path. For examples ‘-html www.foxit.com’. |
-o | The path of the output PDF file. |
-engine | The path of the engine file “fxhtml2pdf.exe”. |
-w | The page width of the output PDF file in points. |
-h | The page height of the output PDF file in points. |
-r | The page rotate for the output PDF file. 0 : 0 degree. 1 : 90 degree. 2 : 180 degree. 3 : 270 degree. |
-ml | The left margin of the pages for the output PDF file. |
-mr | The right margin of the pages for the output PDF file. |
-mt | The top margin of the pages for the output PDF file. |
-mb | The bottom margin of the pages for the output PDF file. |
-mode | The page mode for the output PDF file. 0 : single page mode. 1 : multiple pages mode. |
-scale | Whether to scale pages. ‘yes’ : scale pages. ‘no’ : No need to scale pages. |
-link | Whether to convert links. ‘yes’ : convert links. ‘no’ : No need to convert links. |
-tag | Whether to generate tag. ‘yes’ : generate tag. ‘no’ : No need to generate tag. |
-cookies | The path of the cookies file exported from a URL that you want to convert. |
-timeout | The timeout of loading webpages. |
Office to PDF Conversion
From version 7.3, Foxit PDF SDK provides APIs to convert Microsoft Office documents (Word and Excel) into professional-quality PDF files on Windows platform.
From version 7.4, Foxit PDF SDK also supports to converst PowerPoint documents into PDF files on Windows platform.
For using this feature, please note that:
- Make sure that Microsoft Office 2007 version or higher is already installed on your Windows system.
- Before converting Excel to PDF, make sure that the default Microsoft virtual printer is already set on your Windows system.
System requirements
Platform: Windows
Programming Language: C, C++, Java, C#
License Key requirement: ‘Conversion’ module permission in the license key
SDK Version: Word and Excel (Foxit PDF SDK 7.3 or higher), PowerPoint (Foxit PDF SDK 7.4 or higher)
Example:
How to convert Word to PDF
import com.foxit.sdk.addon.conversion.Word2PDFSettingData; import com.foxit.sdk.addon.conversion.Convert; // Make sure that SDK has already been initialized successfully. String word_file_path = "test.doc"; String saved_pdf_path = "saved.pdf"; // Use default Word2PDFSettingData values. Word2PDFSettingData word_convert_setting_data = new Word2PDFSettingData(); Convert.fromWord(word_file_path, "", saved_pdf_path, word_convert_setting_data);
How to convert Excel to PDF
import com.foxit.sdk.addon.conversion.Word2PDFSettingData; import com.foxit.sdk.addon.conversion.Convert; // Make sure that SDK has already been initialized successfully. String excel_file_path = "test.xls"; String saved_pdf_path = "saved.pdf"; // Use default Excel2PDFSettingData values. Excel2PDFSettingData excel_convert_setting_data = new Excel2PDFSettingData(); Convert.fromExcel(excel_file_path, "", saved_pdf_path, excel_convert_setting_data);
How to convert PowerPoint to PDF
import com.foxit.sdk.addon.conversion.PowerPoint2PDFSettingData; import com.foxit.sdk.addon.conversion.Convert; // Make sure that SDK has already been initialized successfully. String ppt_file_path = "test.ppt"; String saved_pdf_path = "saved.pdf"; // Use default PowerPoint2PDFSettingData values. PowerPoint2PDFSettingData ppt_convert_setting_data = new PowerPoint2PDFSettingData(); Convert.fromPowerPoint(ppt_file_path, "", saved_pdf_path, ppt_convert_setting_data);
Output Preview
From version 7.4, Foxit PDF SDK supports output preview feature which can preview color separations and test different color profiles.
System requirements
Platform: Windows, Linux, Mac
Programming Language: C, C++, Java, C#, Objective-C
License Key requirement: valid license key
SDK Version: Foxit PDF SDK 7.4 or higher
How to run the output preview demo
Before running the output preview demo in the “\examples\simple_demo\output_preview” folder, you should first set the folder path of “\res\icc_profile” in the SDK package to the variable default_icc_folder_path. For example:
// "default_icc_folder_path" is the path of the folder which contains default icc profile files. Please refer to Developer Guide for more details. String default_icc_folder_path = "E:/foxitpdfsdk_X_X_win_java/res/icc_profile";
Then, run the demo following the steps as the other demos.
How to do output preview using Foxit PDF SDK
import com.foxit.sdk.common.Library; import com.foxit.sdk.common.Renderer; import com.foxit.sdk.common.fxcrt.Matrix2D; import com.foxit.sdk.pdf.OutputPreview; // Make sure that SDK has already been initialized successfully. // Set folder path which contains default icc profile files. Library.setDefaultICCProfilesPath(default_icc_folder_path); // Load a PDF document; Get a PDF page and parse it. // Prepare a Renderer object and the matrix for rendering. OutputPreview output_preview = new OutputPreview(pdf_doc); String simulation_icc_file_path = input_path + "icc_profile/USWebCoatedSWOP.icc"; output_preview.setSimulationProfile(simulation_icc_file_path); output_preview.setShowType(OutputPreview.e_ShowAll); ArrayList<String> process_plates = output_preview.getPlates(OutputPreview.e_ColorantTypeProcess); ArrayList<String> spot_plates = output_preview.getPlates(OutputPreview.e_ColorantTypeSpot); // Set check status of process plate to be true, if there's any process plate. for (int i = 0; i < (int)process_plates.size(); i++) { output_preview.setCheckStatus(process_plates.get(i), true); } // Set check status of spot plate to be true, if there's any spot plate. for (int i = 0; i < (int)spot_plates.size(); i++) { output_preview.setCheckStatus(spot_plates.get(i), true); } Bitmap preview_bitmap = output_preview.generatePreviewBitmap(pdf_page, display_matrix, renderer);
Combination
Combination feature is used to combine several PDF files into one PDF file.
How to combine several PDF files into one PDF file
import com.foxit.sdk.common.Progressive; import com.foxit.sdk.pdf.CombineDocumentInfo; import com.foxit.sdk.pdf.CombineDocumentInfoArray; import com.foxit.sdk.pdf.Combination; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionBookmark; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionAcroformRename; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionStructrueTree; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionOutputIntents; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionOCProperties; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionMarkInfos; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionPageLabels; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionNames; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionObjectStream; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionDuplicateStream; import static com.foxit.sdk.pdf.Combination.e_CombineDocsOptionDuplicateStream; // Make sure that SDK has already been initialized successfully. CombineDocumentInfoArray info_array = new CombineDocumentInfoArray(); info_array.add(new CombineDocumentInfo(input_path + "AboutFoxit.pdf", "")); info_array.add(new CombineDocumentInfo(input_path + "Annot_all.pdf", "")); info_array.add(new CombineDocumentInfo(input_path + "SamplePDF.pdf", "")); String savepath = output_path + "Test_Combined.pdf"; int option = (int)(e_CombineDocsOptionBookmark | e_CombineDocsOptionAcroformRename | e_CombineDocsOptionStructrueTree | e_CombineDocsOptionOutputIntents | e_CombineDocsOptionOCProperties | e_CombineDocsOptionMarkInfos | e_CombineDocsOptionPageLabels | e_CombineDocsOptionNames | e_CombineDocsOptionObjectStream | e_CombineDocsOptionDuplicateStream); Progressive progress = Combination.startCombineDocuments(savepath, info_array, option, null); int progress_state = Progressive.e_ToBeContinued; while (Progressive.e_ToBeContinued == progress_state) { progress_state = progress.resume(); }
PDF Portfolio
PDF portfolios are a combination of files with different formats. Portfolio file itself is a PDF document, and files with different formats can be embedded into this kind of PDF document.
System requirements
Platform: Windows, Linux, Mac
Programming Language: C, C++, Java, C#, Objective-C
License Key requirement: valid license key
SDK Version: Foxit PDF SDK 7.6 or higher
Example:
How to create a new and blank PDF portfolio
import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.Portfolio; import com.foxit.sdk.common.Constants; // Make sure that SDK has already been initialized successfully. Portfolio new_portfolio = Portfolio.createPortfolio(); // Set properties, add file/folder node to the new portfolio. ... // Get portfolio PDF document object. PDFDoc portfolio_pdf_doc = new_portfolio.getPortfolioPDFDoc();
How to create a Portfolio object from a PDF portfolio
import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.Portfolio; import com.foxit.sdk.common.Constants; // Make sure that SDK has already been initialized successfully. PDFDoc pdf_doc = new PDFDoc("portfolio.pdf"); int error_code = portfolio_pdf_doc.load(null); if (Constants.e_ErrSuccess == error_code) { if (portfolio_pdf_doc.isPortfolio()) { Portfolio existed_portfolio = Portfolio.createPortfolio(portfolio_pdf_doc); } }
How to get portfolio nodes
import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.Portfolio; import com.foxit.sdk.pdf.SchemaField; import com.foxit.sdk.pdf.SchemaFieldArray; import com.foxit.sdk.pdf.PortfolioNode; import com.foxit.sdk.pdf.PortfolioNodeArray; import com.foxit.sdk.pdf.PortfolioFileNode; import com.foxit.sdk.pdf.PortfolioFolderNode; import com.foxit.sdk.pdf.FileSpec; import com.foxit.sdk.common.Constants; // Make sure that SDK has already been initialized successfully. // Portfolio object has been created, assuming it is named "portfolio". ... PortfolioNode root_node = portfolio.getRootNode(); PortfolioFolderNode root_folder = new PortfolioFolderNode(root_node); PortfolioNodeArray sub_nodes = root_folder.getSortedSubNodes(); for (int index = 0; index < sub_nodes.getSize(); index++) { PortfolioNode node = sub_nodes.getAt(index); switch(node.getNodeType()) { case PortfolioNode::e_TypeFolder: { PortfolioFolderNode folder_node = new PortfolioFolderNode(node); // Use PortfolioFolderNode's methods to get some properties. ... PortfolioNodeArray sub_nodes_2 = folder_node.getSortedSubNodes(); ... break; } case PortfolioNode::e_TypeFile: { PortfolioFileNode file_node = new PortfolioFileNode(node); // Get file specification object from this file node, and then get/set information from/to this file specification object. FileSpec file_spec = file_node.getFileSpec(); ... break; } } }
How to add file node or folder node
import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.Portfolio; import com.foxit.sdk.pdf.SchemaField; import com.foxit.sdk.pdf.SchemaFieldArray; import com.foxit.sdk.pdf.PortfolioNode; import com.foxit.sdk.pdf.PortfolioNodeArray; import com.foxit.sdk.pdf.PortfolioFileNode; import com.foxit.sdk.pdf.PortfolioFolderNode; import com.foxit.sdk.pdf.FileSpec; import com.foxit.sdk.common.Constants; // Make sure that SDK has already been initialized successfully. // Add file from path. String path_to_a_file = "directory/Sample.txt"; PortfolioFileNode new_file_node_1 = root_folder.addFile(path_to_a_file); // User can update properties of file specification for new_file_node_1 if necessary. ... // Add file from MyStreamCallback which is inherited from StreamCallback and implemented by user. MyStreamCallback my_stream_callback = new MyStreamCallback(); PortfolioFileNode new_file_node_2 = root_folder.addFile(my_stream_callback, "file_name"); // Please get file specification of new_file_node_2 and update properties of the file specification by its setting methods. ... // Add a loaded PDF file. // Open and load a PDF file, assume it is named "test_pdf_doc". ... PortfolioFileNode new_file_node_3 = root_folder.addPDFDoc(test_pdf_doc, "pdf_file_name"); // User can update properties of file specification for new_file_node_3 if necessary. ... // Add a sub folder in root_folder. PortfolioFolderNode new_sub_foldernode = root_folder.addSubFolder("Sub Folder-1"); // User can add file or folder node to new_sub_foldernode. ...
How to remove a node
import com.foxit.sdk.common.Library; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.Portfolio; import com.foxit.sdk.pdf.SchemaField; import com.foxit.sdk.pdf.SchemaFieldArray; import com.foxit.sdk.pdf.PortfolioNode; import com.foxit.sdk.pdf.PortfolioNodeArray; import com.foxit.sdk.pdf.PortfolioFileNode; import com.foxit.sdk.pdf.PortfolioFolderNode; import com.foxit.sdk.pdf.FileSpec; import com.foxit.sdk.common.Constants; // Make sure that SDK has already been initialized successfully. // Remove a child folder node from its parent folder node. parent_folder_node.removeSubNode(child_folder_node); // Remove a child file node from its parent folder node. parent_folder_node.removeSubNode(child_file_node);
FAQ
How do I get text objects in a specified position of a PDF and change the contents of the text objects?
To get text objects in a specified position of a PDF and change the contents of the text objects using Foxit PDF SDK, you can follow the steps below:
1) Open a PDF file.
2) Load PDF pages and get the page objects.
3) Use PDFPage.getGraphicsObjectAtPoint to get the text object at a certain position. Note: use the page object to get rectangle to see the position of the text object.
4) Change the contents of the text objects and save the PDF document.
Following is the sample code:
import com.foxit.sdk.PDFException; import com.foxit.sdk.common.fxcrt.PointF; import com.foxit.sdk.pdf.PDFDoc; import com.foxit.sdk.pdf.PDFPage; import com.foxit.sdk.pdf.graphics.*; import static com.foxit.sdk.common.Constants.*; import static com.foxit.sdk.pdf.PDFDoc.*; import static com.foxit.sdk.pdf.graphics.GraphicsObject.*; ... public class graphics_objects { ... static bool ChangeTextObjectContent() throws PDFException { String input_file = input_path + "AboutFoxit.pdf"; PDFDoc doc = new PDFDoc(input_file); int error_code = doc.load(null); if (error_code != e_ErrSuccess) { System.out.println(String.format("The Doc [%s] Error: %d\n", input_file, error_code); return false; } // Get original shading objects from the first PDF page. PDFPage original_page = doc.getPage(0); original_page.startParse((e_ParsePageNormal, null, false); PointF pointf = new PointF(92, 762); GraphicsObjectArray arr = original_page.getGraphicsObjectsAtPoint(pointf, 10, e_TypeText); for(int i = 0; i<arr.getSize(); i++) { GraphicsObject graphobj = arr.getAt(i); TextObject textobj = graphobj.getTextObject(); textobj.setText("Foxit Test"); } original_page.generateContent(); String output_directory = output_path + "graphics_objects/"; String output_file = output_directory + "After_revise.pdf"; doc.saveAs(output_file, e_SaveFlagNormal); return true; } ... }
Can I change the DPI of an embedded TIFF image?
No, you cannot change it. The DPI of the images in PDF files is static, so if the images already exist, Foxit PDF SDK does not have functions to change its DPI.
The solution is that you can use third-party library to change the DPI of an image, and then add it to the PDF file.
Note: Foxit PDF SDK provides a function “Image.setDPIs” which can set the DPI property of an image object. However, it only supports the images that are created by Foxit PDF SDK or created by function “Image.addFrame”, and it does not support the image formats of JPX, GIF and TIF.
Appendix
Supported JavaScript List
Objects’ property or method
Object | Properites/Method Names | Minimum Supported SDK Version |
annotation properties | alignment | V7.0 |
author | V7.0 | |
contents | V7.0 | |
creationDate | V7.0 | |
fillColor | V7.0 | |
hidden | V7.0 | |
modDate | V7.0 | |
name | V7.0 | |
opacity | V7.0 | |
page | V7.0 | |
readOnly | V7.0 | |
rect | V7.0 | |
richContents | V7.1 | |
rotate | V7.0 | |
strokeColor | V7.0 | |
textSize | V7.0 | |
type | V7.0 | |
annotation method | destroy | V7.0 |
app properties | activeDocs | V4.0 |
calculate | V4.0 | |
formsVersion | V4.0 | |
fs | V4.0 | |
fullscreen | V4.0 | |
language | V4.2 | |
platform | V4.0 | |
runtimeHighlight | V4.0 | |
viewerType | V4.0 | |
viewerVariation | V4.0 | |
viewerVersion | V4.0 | |
app methods | alert | V4.0 |
beep | V4.0 | |
browseForDoc | V4.0 | |
clearInterval | V4.0 | |
clearTimeOut | V4.0 | |
launchURL | V4.0 | |
mailMsg | V4.0 | |
response | V4.0 | |
setInterval | V4.0 | |
setTimeOut | V4.0 | |
popUpMenu | V4.0 | |
color properties | black | V4.0 |
blue | V4.0 | |
cyan | V4.0 | |
dkGray | V4.0 | |
gray | V4.0 | |
green | V4.0 | |
ltGray | V4.0 | |
magenta | V4.0 | |
red | V4.0 | |
transparent | V4.0 | |
white | V4.0 | |
yellow | V4.0 | |
color methods | convert | V4.0 |
equal | V4.0 | |
document properties | author | V4.0 |
baseURL | V4.0 | |
bookmarkRoot | V7.0 | |
calculate | V4.0 | |
Collab | V4.0 | |
creationDate | V4.0 | |
creator | V4.0 | |
delay | V4.0 | |
dirty | V4.0 | |
documentFileName | V4.0 | |
external | V4.0 | |
filesize | V4.0 | |
icons | V4.0 | |
info | V4.0 | |
keywords | V4.0 | |
modDate | V4.0 | |
numFields | V4.0 | |
numPages | V4.0 | |
pageNum | V4.0 | |
path | V4.0 | |
producer | V4.0 | |
subject | V4.0 | |
title | V4.0 | |
document methods | addAnnot | V7.0 |
addField | V4.0 | |
addIcon | V4.0 | |
calculateNow | V4.0 | |
createDataObject | V6.2 | |
deletePages | V4.0 | |
exportAsFDF | V4.0 | |
flattenPages | V7.1 | |
getAnnot | V7.0 | |
getAnnots | V7.0 | |
getField | V4.0 | |
getIcon | V4.0 | |
getNthFieldName | V4.0 | |
getOCGs | V4.0 | |
getPageBox | V4.0 | |
getPageNthWord | V4.0 | |
getPageNthWordQuads | V4.0 | |
getPageNumWords | V4.0 | |
getPageRotation | V7.0 | |
getPrintParams | V4.0 | |
getURL | V4.0 | |
importAnFDF | V4.0 | |
insertPages | V6.2 | |
mailForm | V4.0 | |
V4.0 | ||
removeField | V4.0 | |
replacePages | V6.2 | |
resetForm | V4.0 | |
submitForm | V4.0 | |
mailDoc | V4.0 | |
event properties | change | V4.0 |
changeEx | V4.0 | |
commitKey | V4.0 | |
fieldFull | V4.0 | |
keyDown | V4.0 | |
modifier | V4.0 | |
name | V4.0 | |
rc | V4.0 | |
selEnd | V4.0 | |
selStart | V4.0 | |
shift | V4.0 | |
source | V4.0 | |
target | V4.0 | |
targetName | V4.0 | |
type | V4.0 | |
value | V4.0 | |
willCommit | V4.0 | |
event methods | – | – |
field properties | alignment | V4.0 |
borderStyle | V4.0 | |
buttonAlignX | V4.0 | |
buttonAlignY | V4.0 | |
buttonFitBounds | V4.0 | |
buttonPosition | V4.0 | |
buttonScaleHow | V4.0 | |
buttonScaleWhen | V4.0 | |
calcOrderIndex | V4.0 | |
charLimit | V4.0 | |
comb | V4.0 | |
commitOnSelChange | V4.0 | |
currentValueIndices | V4.0 | |
defaultValue | V4.0 | |
doNotScroll | V4.0 | |
doNotSpellCheck | V4.0 | |
delay | V4.0 | |
display | V4.0 | |
doc | V4.0 | |
editable | V4.0 | |
exportValues | V4.0 | |
hidden | V4.0 | |
fileSelect | V4.0 | |
fillColor | V4.0 | |
lineWidth | V4.0 | |
highlight | V4.0 | |
multiline | V4.0 | |
multipleSelection | V4.0 | |
name | V4.0 | |
numItems | V4.0 | |
page | V4.0 | |
password | V4.0 | |
V4.0 | ||
radiosInUnison | V4.0 | |
readonly | V4.0 | |
rect | V4.0 | |
required | V4.0 | |
richText | V4.0 | |
rotation | V4.0 | |
strokeColor | V4.0 | |
style | V4.0 | |
textColor | V4.0 | |
textFont | V4.0 | |
textSize | V4.0 | |
type | V4.0 | |
userName | V4.0 | |
value | V4.0 | |
valueAsString | V4.0 | |
field methods | browseForFileToSubmit | V4.0 |
buttonGetCaption | V4.0 | |
buttonGetIcon | V4.0 | |
buttonSetCaption | V4.0 | |
buttonSetIcon | V4.0 | |
checkThisBox | V4.0 | |
clearItems | V4.0 | |
defaultIsChecked | V4.0 | |
deleteItemAt | V4.0 | |
getArray | V4.0 | |
getItemAt | V4.0 | |
insertItemAt | V4.0 | |
isBoxChecked | V4.0 | |
isDefaultChecked | V4.0 | |
setAction | V4.0 | |
setFocus | V4.0 | |
setItems | V4.0 | |
global methods | setPersistent | V4.0 |
Icon properties | name | V4.0 |
util methods | printd | V4.0 |
printf | V4.0 | |
printx | V4.0 | |
scand | V4.0 | |
identity properties | loginName | V4.2 |
Name | V4.2 | |
corporation | V4.2 | |
V4.2 | ||
collab properties | user | V6.2 |
ocg properties | name | V6.2 |
ocg methods | setAction | V6.2 |
Global methods
Method Names | Minimum Supported SDK Version |
AFNumber_Format | V4.0 |
AFNumber_Keystroke | V4.0 |
AFPercent_Format | V4.0 |
AFPercent_Keystroke | V4.0 |
AFDate_FormatEx | V4.0 |
AFDate_KeystrokeEx | V4.0 |
AFDate_Format | V4.0 |
AFDate_Keystroke | V4.0 |
AFTime_FormatEx | V4.0 |
AFTime_KeystrokeEx | V4.0 |
AFTime_Format | V4.0 |
AFTime_Keystroke | V4.0 |
AFSpecial_Format | V4.0 |
AFSpecial_Keystroke | V4.0 |
AFSpecial_KeystrokeEx | V4.0 |
AFSimple | V4.0 |
AFMakeNumber | V4.0 |
AFSimple_Calculate | V4.0 |
AFRange_Validate | V4.0 |
AFMergeChange | V4.0 |
AFParseDateEx | V4.0 |
AFExtractNums | V4.0 |
References
PDF reference 1.7
http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51502
PDF reference 2.0
https://www.iso.org/standard/63534.html
Foxit PDF SDK API reference
sdk_folder/doc/Foxit PDF SDK Java API Reference.html
Note: sdk_folder is the directory of unzipped package.
Support
Foxit support home link:
Sales contact phone number:
Phone: 1-866-680-3668
Support & General contact:
Phone: 1-866-MYFOXIT or 1-866-693-6948
Updated on March 21, 2024