1. Home
  2. Foxit PDF SDK for Windows
  3. Developer Guide for Foxit PDF SDK (.NET)
  1. Home
  2. Foxit PDF SDK for Mac
  3. Developer Guide for Foxit PDF SDK (.NET)
  1. Home
  2. Foxit PDF SDK for Linux
  3. Developer Guide for Foxit PDF SDK (.NET)

Developer Guide for Foxit PDF SDK (.NET)

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 an Amazon-invested leading software provider of solutions for reading, editing, creating, organizing, and securing PDF documents. Foxit PDF SDK libraries have been used in many of today’s leading apps, and they are proven, robust, and battle-tested to provide the quality, performance, and features that the industry’s largest apps demand. 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 Windows, Linux, Mac, iOS and Android
  • 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 .NET

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 includes a built-in, embeddable PDF Viewer, making the development process easier and faster. For more detailed information, please visit the website https://developers.foxitsoftware.com/pdfsdk/. In this guide, we focus on the introduction of Foxit PDF SDK for Windows platform with .NET framework.

Foxit PDF SDK for .NET is a Component for Windows which ships with simple-to-use APIs that can help .NET developers seamlessly integrate powerful PDF technology into their own projects based on .NET Framework 4.0 or higher. It offers the most common features in PDF SDK, such as PDF viewing, bookmark navigating, text selecting/copying/searching, annotations, and signature.

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 30-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 the developers who need to integrate Foxit PDF .NET SDK into their own applications. It aims at introducing the installation package, and the usage of SDK.

Getting Started

It’s very easy to setup Foxit PDF SDK and see it in action! This guide will provide you with a brief introduction on how to integrate Foxit PDF SDK into the projects based on .NET Framework 4.0 or higher. 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

Windows XP, Vista, 7, 8 and 10 (32-bit, 64-bit)

Windows Server 2003, 2008 and 2012 (32-bit and 64-bit)

The release package includes a 32 bit version and native 64 bit version DLL library for Windows 32/64.

Visual Studio 2010/2015 installed with .NET Framework 4.0 or higher

Note: This guide provides support for Windows 8/10 classic, but not for Store App or UWP app.

What is in the package

Download Foxit PDF SDK zip for .NET package and extract it to a new directory “foxitpdfsdk_6_3_win_dotnet”, which 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 6.3, so it shows 6_3 in the package name.

The release package contains the following folders:

docs: API references, quick start guide
lib: libraries and license files
samples: sample projects and demos

Figure 2-1

In the “examples” folder, there are two types of demos. “examples\simple_demo” contains more than 20 demos that cover a wide range of PDF applications. “examples\view_demo” contains a UI demo that realizes a lite PDF viewer.

How to run a demo

Simple demo projects provide examples to show .NET developers about how to effectively apply PDF SDK APIs to complete their applications.

To run a demo in Visual Studio 2010/2015/2017, you can follow the steps below:

    1. Load the visual studio solution file “simple_demo_vs2010.sln” or “simple_demo_vs2015.sln” or “simple_demo_vs2017.sln” depending on your Visual Studio version in the “examples\simple_demo” folder
    2. Build all the demos by clicking “Build > Build Solution”. Alternatively, if you merely want to build a specific demo, you can right-click it and then choose “Build” or load the “*.csproj” file in the folder of a specific demo project and then build it.

After building, the executable file “.exe” will be generated in the “examples\simple_demo\bin” folder (See Figure 2-2). And the names of the executable files depend on the build configurations.

Figure 2-2
    1. Run a specific executable file, just double-click it. If you want to see the detailed executing processes, you can run it in command line. Start “cmd.exe”, navigate to “examples\simple_demo\bin”, and run a specific executable file.Some demos will generate output files (pdf, text or image files) to a folder named by the project name under “example\simple_demo\output_files\” folder.In “examples\simple_demo\output_files\security” folder, if you want to open the “certificate_encrypt.pdf” document, you should install the certificates “foxit.cer” and “foxit_all.pfx” found in “examples\simple_demo\input_files” folder at first. Please follow the steps below:
      1. To install “foxit.cer”, double-click it to start the certificate import wizard. Then select “Install certificate… > Next > Next > Finish”.
      2. To install “foxit_all.pfx”, double-click it to start the certificate import wizard. Then select “Next > Next > (Type the password for the private key in the textbox) and click Next > Next > Finish”.
      3. Run the demo following the steps as the other demos.

      View Demo

      This view demo provides an example for .NET developers to realize a PDF reader using PDF SDK APIs.

      To run the demo in Visual Studio, load “PDFReader_VS2010.sln” or “PDFReader_VS2015.sln” or “PDFReader_VS2017.sln” in the “examples\view_demo\PDFReader” folder, and then click “Debug > Start Without Debugging” to run it. After the demo starts, you will see the following window as shown in Figure 2-3.

      Figure 2-3

      You can click on File > Open or click the directory icon to open a PDF file, for example, we open a PDF document named “AboutFoxit.pdf” found in “examples\simple_demo\input_files” folder.

      This demo provides the features like rendering a PDF document, zooming, page rotation, text selection and search, and page turning. For example, click the Next Page button to view the next page, which is shown in Figure 2 4.

      Figure 2-4

      How to create a simple project

      In this section, we will show you how to use Foxit PDF .NET SDK to create a simple project that renders the first page of a PDF to a bitmap and saves it as a JPG image. Please follow the steps below:

      1. Open Visual Studio and create a new C# Console Application named “test_dotnet”.
      2. Copy the “lib” folder from the “foxitpdfsdk_6_1_win_dotnet” folder to the project “test_ dotnet” folder.
      3. Add Foxit PDF SDK dynamic library to References. In order to use Foxit PDF SDK APIs in the project, you must first add a reference to it.
      1. In Solution Explorer, right-click the “test_dotnet” project and click Add Reference…
      2. In the Add Reference dialog, click Browse tab, navigate to the “test_dotnet\lib\x64_vc10” or “test_dotnet\lib\x86_vc10” folder depending on your build configurations, select fsdk_dotnet.dll dynamic library, and then click OK.

      Note: Please make sure that the “fsdk_dotnet.dll” architecture needs to match the platform target (Win32 or Win64) of the application.

    2. Add “System.Drawing” item to References.
      Right-click the “test_dotnet” project and click Add Reference… In the Add Reference dialog, click .NET tab and select System.Drawing, and then click OK.
    3. Add “fsdk.dll” as source file to the project.
      Right-click the “test_dotnet” project and click Add > Existing Item…, navigate to the “test_dotnet\lib\x64_vc10” or “test_dotnet\lib\x86_vc10” folder depending on your build configurations, select fsdk.dll dynamic library, and click Add.Note: Please make sure to set the property “Copy to Output Directory” of “fsdk.dll” to
      “Copy if newer”. Otherwise, you should copy it to the same folder with the executable file
      manually before running the project.
    4. Add using statement to the beginning of the “Program.cs”.
using System.Drawing;
using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
    1. Initialize Foxit PDF SDK library. It is necessary for apps to initialize Foxit PDF SDK using a license before calling any APIs. The trial license files can be found in the “libs” folder.
string sn = " ";
string key = " ";
ErrorCode error_code = Library.Initialize(sn, key);
if (error_code != ErrorCode.e_ErrSuccess)
{
   return;
}

Note: The value of “sn” can be got from “gsdk_sn.txt” (the string after “SN=”) and the value of “key” can be got from “gsdk_key.txt” (the string after “Sign=”)

    1. Load a PDF document, and parse the first page of the document. Let us assume that you have already put a “Sample.pdf” to the “test_dotnet\test_dotnet” folder.
PDFDoc doc = new PDFDoc("..\..\Sample.pdf");
error_code = doc.LoadW("");
if (error_code != ErrorCode.e_ErrSuccess)
{
    return;
}
 
// Get the first page of the document.
PDFPage page = doc.GetPage(0);
 
// Parse page.
page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.e_ParsePageNormal, null, false);
    1. Render a 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.
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics draw = Graphics.FromImage(bitmap);
draw.Clear(Color.White);
 
// Render page
Renderer render = new Renderer(bitmap, false);
render.StartRender(page, matrix, null);
 
// Add the bitmap to image and save the image.
foxit.common.Image image = new foxit.common.Image();
image.AddFrame(bitmap);
image.SaveAs("testpage.jpg");
    1. Click “Build > Build Solution” to build the project. The executable file “test_dotnet.exe” will be generated in “test_dotnet\test_dotnet\bin\Debug” or “test_dotnet\test_dotnet\bin\Release” folder depending on the build configurations.
      Note: Please check whether the “fsdk.dll” and “fsdk_dotnet.dll” have been copied to the same folder with the “test_dotnet.exe”. If not, you should put the dynamic libraries to the folder manually.
    2. Double-click the executable file “test_dotnet.exe” to run this project, and then the “testpage.jpg” will be generated in the current folder.

The final contents of “Program.cs” is as follow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
 
 
using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
 
namespace test_dotnet
{
    class Program
    {
        static void Main(string[] args)
        {
 
            // 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 = " ";
            ErrorCode error_code = Library.Initialize(sn, key);
            if (error_code != ErrorCode.e_ErrSuccess)
            {
                return;
            }
 
            using (PDFDoc doc = new PDFDoc("../../Sample.pdf"))
            {
                error_code = doc.LoadW("");
                if (error_code != ErrorCode.e_ErrSuccess)
                {
                    Library.Release();
                    return;
                }
 
                using (PDFPage page = doc.GetPage(0))
                {
                    // Parse page.
                    page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.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.
                    System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
                    Graphics draw = Graphics.FromImage(bitmap);
                    draw.Clear(Color.White);
 
                    // Render page
                    Renderer render = new Renderer(bitmap, false);
                    render.StartRender(page, matrix, null);
 
                    // Add the bitmap to image and save the image.
                    foxit.common.Image image = new foxit.common.Image();
                    image.AddFrame(bitmap);
                    image.SaveAs("testpage.jpg");
                }
            }
            Library.Release();
        }
    }
}

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 based on .NET Framework 4.0 or higher. 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 Foxit PDF SDK before calling any APIs. The function foxit.common.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 foxit.common.Library.Release to release it.

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

using foxit.common;
 
string sn = " ";
string key = " ";
ErrorCode error_code = Library.Initialize(sn, key);
if (error_code != ErrorCode.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, annotation, metadata and etc.

Example:

How to create a PDF document from scratch

using foxit.pdf;
...
PDFDoc doc = new PDFDoc();

Note: It creates a new PDF document without any pages.

How to load an existing PDF document from file path

using foxit.pdf;
using foxit.common;
...
 
PDFDoc doc = new PDFDoc("Sample.pdf");
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...

How to load an existing PDF document from a memory buffer

using foxit.pdf;
using foxit.common;
...
 
byte[] byte_buffer = File.ReadAllBytes(input_file);
IntPtr buffer = System.Runtime.InteropServices.Marshal.AllocHGlobal(byte_buffer.Length);
try {
 System.Runtime.InteropServices.Marshal.Copy(byte_buffer, 0, buffer, byte_buffer.Length);
}
Finally {
 System.Runtime.InteropServices.Marshal.FreeHGlobal(buffer);
}
PDFDoc doc = new PDFDoc(buffer, (uint)byte_buffer.Length);
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...

How to load an existing PDF document from a file read callback object

using foxit.pdf;
using foxit.common;
...
 
class FileReader : FileReaderCallback
 {
 private FileStream file_ = null;
 private long offset_ = 0;
 
 public FileReader(long offset)
 {
 this.offset_ = offset;
 }
 
 public Boolean LoadFile(String file_path)
 {
 file_ = new FileStream(file_path, FileMode.OpenOrCreate);
 return true;
 }
 
 public override long GetSize()
 {
 return this.offset_;
 }
 
 public override bool ReadBlock(IntPtr buffer, long offset, uint size)
 {
 int read_size = 0;
 file_.Seek(offset, SeekOrigin.Begin);
 byte[] array = new byte[size + 1];
 read_size = file_.Read(array, 0, (int)size);
 Marshal.Copy(array, 0, buffer, (int)size);
 return read_size == size ? true : false;
 }
 
 public override void Release()
 {
 this.file_.Close();
 }
 }
...
 
FileReader file_reader = new FileReader(offset);
 file_reader.LoadFile(file_name);
 
PDFDoc doc_real = new PDFDoc(file_reader, false)
 
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...

How to load PDF document and get the first page of the PDF document

using foxit.pdf;
using foxit.common;
...
 
PDFDoc doc = new PDFDoc("Sample.pdf");
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...
// Get the first page of the document.
PDFPage page = doc.GetPage(0);
// Parse page.
page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.e_ParsePageNormal, null, false);
...

How to save a PDF to a file

using foxit.pdf;
using foxit.common;
...
 
PDFDoc doc = new PDFDoc("Sample.pdf");
error_code = doc.Load("");
if (error_code != ErrorCode.e_ErrSuccess) return;
...
// Do operations for the PDF document.
...
// Save the changes for the PDF document.
string newPdf = "the output path for the saved PDF";
doc.SaveAs(newPdf, (int)PDFDoc.SaveFlags.e_SaveFlagNoOriginal);

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

using foxit.pdf;
using foxit.common;
...
 
// 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

using foxit.pdf;
...
 
// Assuming PDFPage page has been loaded and parsed.
...
 
RectF ret = page.CalcContentBBox(PDFPage.CalcMarginMode.e_CalcContentsBox);
...

How to create a PDF page and set the size

using foxit.pdf;
...
 
// Assuming PDFDoc doc has been loaded.
 
PDFPage page = doc.InsertPage(index, PageWidth, PageHeight);

How to delete a PDF page

using foxit.pdf;
...
 
// 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

using foxit.pdf;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
// Flatten all contents of a PDF page.
page.Flatten(true, (int)PDFPage.FlattenOptions.e_FlattenAll);
 
// Flatten a PDF page without annotations.
page.Flatten(true, (int)PDFPage.FlattenOptions.e_FlattenNoAnnot);
 
// Flatten a PDF page without form controls.
page.Flatten(true, (int)PDFPage.FlattenOptions.e_FlattenNoFormControl);
 
// Flatten a PDF page without annotations and form controls (Equals to nothing to be flattened).
page.Flatten(true, (int)(PDFPage.FlattenOptions.e_FlattenNoAnnot | PDFPage.FlattenOptions.e_FlattenNoFormControl));
...

How to get and set page thumbnails in a PDF document

using foxit.pdf;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
// Get page thumbnails.
page.LoadThumbnail();
 
// Set thumbnails to the page. 
// Assuming Bitmap bitmap has been created.
page.SetThumbnail(bitmap);
...

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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
// 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.
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics draw = Graphics.FromImage(bitmap);
draw.Clear(Color.White);
// Render page.
Renderer render = new Renderer(bitmap, false);
render.StartRender(page, matrix, null);
...

How to render page and annotation

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
 
// 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.
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
Graphics draw = Graphics.FromImage(bitmap);
draw.Clear(Color.White);
 
// Render page
Renderer render = new Renderer(bitmap, false);
render.SetRenderContentFlags((int)Renderer.ContentFlag.e_RenderAnnot | (int)Renderer.ContentFlag.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 insert an attachment file into a PDF

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.objects;
 
// Assuming PDFDoc doc has been loaded.
 
string text_path = "The input path of the attached file you need to insert";
Attachments attachments = new Attachments(doc, new PDFNameTree());
attachment.AddFromFilePath("OriginalAttachmentsInfo", text_path);
...

How to remove a specific attachment of a PDF

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.objects;
 
// Assuming PDFDoc doc has been loaded.
...
Attachments attachment = new Attachments(doc, new PDFNameTree());
string strKey = attachment.GetKey(index);
attachment.RemoveEmbeddedFile(strKey);
...

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

using foxit.common;
using foxit.pdf;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
using (var text_page = new TextPage(page, (int)TextPage.TextParseFlags.e_ParseTextNormal))
{
int count = text_page.GetCharCount();
if (count > 0)
 {
 String chars = text_page.GetChars(0, count);
 writer.Write(chars);
 }
}
...

How to select text of a rectangle area in a PDF

using foxit.common;
using foxit.pdf;
using foxit.common.fxcrt;
...
 
RectF rect = new RectF(100, 50, 220, 100);
TextPage text_page = new TextPage(page, (int)foxit.pdf.TextPage.TextParseFlags.e_ParseTextNormal);
String str_text = text_page.GetTextInRect(rect);
...

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 page

using foxit.common;
using foxit.pdf;
...
 
// Assuming PDFDoc doc has been loaded.
 
using (TextSearch search = new TextSearch(doc, null))
{
 
 int start_index = 0;
 int end_index = doc.GetPageCount() - 1;
 search.SetStartPage(0);
 search.SetEndPage(doc.GetPageCount() - 1);
 
 String pattern = "Foxit";
 search.SetPattern(pattern);
 
 Int32 flags = (int)TextSearch.SearchFlags.e_SearchNormal;
 search.SetSearchFlags(flags);
 int match_count = 0;
 while (search.FindNext())
 {
 RectFArray rect_array = search.GetMatchRects();
 match_count++;
 }
...

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:

using foxit.common;
using foxit.pdf;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
// Get the text page object.
TextPage text_page = new TextPage(page, (int)foxit.pdf.TextPage.TextParseFlags.e_ParseTextNormal);
PageTextLinks page_textlinks = new PageTextLinks(text_page);
TextLink text_link = page_textlinks.GetTextLink(index); // specify an index.
string str_url = 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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.actions;
...
 
//Assuming PDFDoc doc has been loaded.
...
Bookmark root = doc.GetRootBookmark();
Bookmark first_bookmark = root.GetFirstChild();
if (first_bookmark != null)
{
TraverseBookmark(first_bookmark, 0);
}
 
Private void TraverseBookmark(Bookmark root, int iLevel)
{
if (root != null)
{
 Bookmark child = root.GetFirstChild();
 while (child != null)
 {
 TraverseBookmark(child, iLevel + 1);
 child = child.GetNextSibling();
 }
 }
}
...

Form

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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.interform;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// 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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.interform;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFDoc doc has been loaded.
 
Boolean hasForm = doc.HasForm();
If(hasForm)
Form form = new Form(doc);
int count = form.GetFieldCount("");
for (int i = 0; i < count; i++)
{
 Field field = form.GetField(i, "");
 ...
}

How to export the form data in a PDF to a XML file

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.interform;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFDoc doc has been loaded.
 
Boolean hasForm = doc.HasForm();
If(hasForm)
Form form = new Form(doc);
...
form.ExportToXML(XMLFilePath);
...

How to import form data from a XML file

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.interform;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFDoc doc has been loaded.
 
Boolean hasForm = doc.HasForm();
If(hasForm)
Form form = new Form(doc);
...
form.ImportFromXML(XMLFilePath);
...

How to get and set the properties of form fields

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.interform;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFDoc doc has been loaded.
 
Boolean hasForm = doc.HasForm();
If(hasForm)
Form form = new Form(doc);
Field field = form.GetField(0, "Text Field0");
field.GetAlignment();
field.GetAlternateName();
field.SetAlignment(Alignment.e_AlignmentLeft);
field.SetValue("3");
...

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 foxit.addon.xfa.AppProviderCallback and foxit.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.

Example:

How to load XFA Doc and represent an Interactive XFA form

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.addon;
using foxit.addon.xfa;
...
 
// Implement from AppProviderCallback
CFS_XFAAppHandler pXFAAppHandler = new CFS_XFAAppHandler(); 
Library.RegisterXFAAppProviderCallback(pXFAAppHandler);
string input_file = input_path + "xfa_dynamic.pdf";
using (PDFDoc doc = new PDFDoc(input_file))
{
 error_code = doc.Load(null);
 if (error_code != ErrorCode.e_ErrSuccess)
 {
 Console.WriteLine("The PDFDoc [{0}] Error: {1}\n", input_file, error_code);
 Library.Release();
 return;
 }
 
 // Implement from DocProviderCallback 
 CFS_XFADocHandler pXFADocHandler = new CFS_XFADocHandler(); 
 using (XFADoc xfa_doc = new XFADoc(doc, pXFADocHandler))
 {
 ...
 }
}

How to export and import XFA form data

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.addon;
using foxit.addon.xfa;
...
 
// Assuming FSXFADoc xfa_doc has been loaded.
 
...
xfa_doc.ExportData("xfa_form.xml", XFADoc.ExportDataType.e_ExportDataTypeXML);
 
xfa_doc.ResetForm();
doc.SaveAs("xfa_dynamic_resetform.pdf", (int)foxit.pdf.PDFDoc.SaveFlags.e_SaveFlagNormal);
 
xfa_doc.ImportData(output_path + "xfa_form.xml");
doc.SaveAs("xfa_dynamic_importdata.pdf", (int)foxit.pdf.PDFDoc.SaveFlags.e_SaveFlagNormal);
...

Form Filler

Form filler is the most commonly used feature for users. Form filler allows applications to fill forms dynamically. The key point for applications to fill forms is to construct some callback functions for PDF SDK to call. To fill the form, please construct a Filler object by current Form object or retrieve the Filler object by function Form.GetFormFiller if such object has been constructed. (There should be only one form filler object for an interactive form). For how to fill a form with form filler, you can refer to the view demo “view_demo” in the “examples\simple_demo” folder of the download package.

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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.interform;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFDoc doc has been loaded.
 
Control control = form.AddControl(page, "Text Field0", Field.Type.e_TypeTextField, new RectF(50f, 600f, 90f, 640f))
...

How to remove a text form field from a PDF

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.interform;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFDoc doc has been loaded.
 
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 an¬notation types as listed in Table 3-1. 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 Table 3 1 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 3-1

Annotation type Description Markup Supported by SDK
Text(Note) Text annotation Yes Yes
Link Link Annotations 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:

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.graphics;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
Annot annot = page.AddAnnot(Annot.Type.e_Link, new RectF(350, 350, 380, 400))
Link link = new Link(annot);
link.SetHighlightingMode(Annot.HighlightingMode.e_HighlightingToggle);
 
// Appearance should be reset.
link.ResetAppearanceStream();
...
using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.graphics;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
// Add highlight annotation.
Annot annot = page.AddAnnot(Annot.Type.e_Highlight, new RectF(10, 450, 100, 550));
Highlight highlight = new Highlight(annot);
highlight.SetContent("Highlight");
QuadPoints quad_points = new QuadPoints();
quad_points.first = new foxit.common.fxcrt.PointF(10, 500);
quad_points.second = new foxit.common.fxcrt.PointF(90, 500);
quad_points.third = new foxit.common.fxcrt.PointF(10, 480);
quad_points.fourth = new foxit.common.fxcrt.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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.graphics;
using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Assuming PDFPage page has been loaded and parsed.
// Assuming the annnots in the page have been loaded.
 
// Create a new note annot and set the properties for it.
Annot annot = page.AddAnnot(Annot.Type.e_Note, new RectF(10, 350, 50, 400));
Note note = new Note(annot);
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.
Annot annot_popup = page.AddAnnot(Annot.Type.e_Popup, new RectF(300, 450, 500, 550));
Popup popup = new Popup(annot); 
popup.SetBorderColor(0x00FF00);
popup.SetOpenStatus(false);
popup.SetModifiedDateTime(GetLocalDateTime());
note.SetPopup(popup);
 
// Appearance should be reset.
note.ResetAppearanceStream();
...

How to get a specific annotation in a PDF using device coordinates

using foxit;
using foxit.common;
using foxit.pdf;
using foxit.pdf.graphics;
using foxit.pdf.annots;
...
 
// Assuming PDFDoc doc has been loaded.
// 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());
 
// Assuming PointF point has been got.
 
float tolerance = 3.0f;
 
Annot annot = page.GetAnnotAtDevicePoint(point, tolerance, matrix);
...

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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
 
// Assuming PDFDoc doc has been loaded.
...
 
string fdf_file = "The FDF file path";
foxit.fdf.FDFDoc fdf_doc = new foxit.fdf.FDFDoc(fdf_file);
pdf_doc.ImportFromFDF(fdf_doc, (int)foxit.pdf.PDFDoc.DataType.e_Annots, new 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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using System.Drawing;
 
// Assuming PDFDoc doc has been loaded.
...
 
Image image = new Image();
 
// Get page count
int nPageCount = doc.GetPageCount();
for(int i=0;i<npagecount ;i++)
{
 using (PDFPage page = doc.GetPage(i))
 {
 // Parse page.
 page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.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.
 System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
 Graphics draw = Graphics.FromImage(bitmap);
 draw.Clear(Color.White);
 
 // Render page
 Renderer render = new Renderer(bitmap, false);
 render.StartRender(page, matrix, null);
 image.AddFrame(bitmap);
 }
}
...

How to convert an image file to PDF file

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using System.Drawing;
 
// Assuming PDFDoc doc has been loaded.
...
Image image = new Image(input_file);
int count = image.GetFrameCount();
 
for (int i = 0; i < count; i++) {
PDFPage page = doc.InsertPage(i, PDFPage.Size.e_SizeLetter);
page.StartParse((int)PDFPage.ParseFlags.e_ParsePageNormal, null, false);
 
// Add image to page
page.AddImage(image, i, new PointF(0, 0), page.GetWidth(), page.GetHeight(), true);
}
 
doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.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

using foxit.common;
using foxit.pdf;
...
 
// Assuming PDFDoc doc has been loaded.
 
WatermarkSettings settings = new WatermarkSettings();
settings.offset_x = 0;
settings.offset_y = 0;
settings.opacity = 90;
settings.position = Position.e_PosTopRight;
settings.rotation = -45.0f;
settings.scale_x = 1.0f;
settings.scale_y = 1.0f;
 
WatermarkTextProperties text_properties = new WatermarkTextProperties();
text_properties.alignment = Alignment.e_AlignmentCenter;
text_properties.color = 0xF68C21;
text_properties.font_style = WatermarkTextProperties.FontStyle.e_FontStyleNormal;
text_properties.line_space = 1;
text_properties.font_size = 12.0f;
text_properties.font = font;
 
Watermark watermark = new Watermark(doc, "Foxit PDF SDK\nwww.foxitsoftware.com", text_properties, settings);
watermark.InsertToPage(doc.GetPage(0));
 
// Save document to file
...

How to create an image watermark and insert it into the first page

using foxit.common;
using foxit.pdf;
...
 
// Assuming PDFDoc doc has been loaded.
// Assuming PDFPage page has been loaded and parsed.
 
WatermarkSettings settings = new WatermarkSettings();
settings.flags = (int)(WatermarkSettings.Flags.e_FlagASPageContents | WatermarkSettings.Flags.e_FlagOnTop);
settings.offset_x = 0.0f;
settings.offset_y = 0.0f;
settings.opacity = 20;
settings.position = Position.e_PosCenter;
settings.rotation = 0.0f;
 
Image image = new Image(image_file);
System.Drawing.Bitmap bitmap = image.GetFrameBitmap(0);
 
settings.scale_x = page.GetWidth() * 0.618f / bitmap.Width;
settings.scale_y = settings.scale_x;
 
Watermark watermark = new Watermark(doc, image, 0, settings);
watermark.InsertToPage(doc.GetPage(0));
 
// Save document to file.
...

How to remove all watermarks from a page

using foxit.common;
using foxit.pdf;
...
 
// 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 SDK provides applications to generate a barcode bitmap from a given string. The barcode types that Foxit SDK supports are listed in Table 3-2.

Table 3-2

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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
...
 
// Strings used as barcode content.
String sz_code_str = "TEST-SHEET";
 
// Barcode format types.
Barcode.Format sz_code_format = Barcode.Format.e_FormatCode39;
 
//Format error correction level of QR code.
Barcode.QRErrorCorrectionLevel qr_level = Barcode.QRErrorCorrectionLevel.e_QRCorrectionLevelLow;
 
//Image names for the saved image files for QR code.
String sz_bmp_qr_name = "/QR_CODE_TestForBarcodeQrCode_L.bmp";
 
// Unit width for barcode in pixels, preferred value is 1-5 pixels.
int unit_width = 2;
 
// Unit height for barcode in pixels, preferred value is >= 20 pixels.
int unit_height = 120;
 
Barcode barcode;
Barcode barcode = new Barcode();
 
System.Drawing.Bitmap bitmap = barcode.GenerateBitmap(sz_code_str, sz_code_format, unit_width, unit_height, qr_level);
...

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 user password “123” and owner password “456”

using foxit.common;
using foxit.pdf;
...
using (var handler = new StdSecurityHandler())
{
 using (var encrypt_data = new StdEncryptData(true, -4, SecurityHandler.CipherType.e_CipherAES, 16))
 {
 handler.Initialize(encrypt_data, “123”, “456);
 doc.SetSecurityHandler(handler);
 
 doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
 }
}
...

How to encrypt a PDF file with Certificate

using foxit.common;
using foxit.pdf;
...
PDFDoc doc = new PDFDoc(input_file);
ErrorCode error_code = doc.Load(null);
if (error_code != ErrorCode.e_ErrSuccess){
 return;
}
 
// Do encryption.
string cert_file_path = input_path + "foxit.cer";
 
var cms = new EnvelopedCms(new ContentInfo(seed));
cms.ContentEncryptionAlgorithm.Oid.Value = "1.2.840.113549.3.4";
cms.Encrypt(new CmsRecipient(new X509Certificate2(cert_file_path)));
byte[] bytes = cms.Encode();
 
byte[] data = new byte[20 + bytes.Length];
Array.Copy(seed, 0, data, 0, 20);
Array.Copy(bytes, 0, data, 20, bytes.Length);
SHA1 sha1 = new SHA1CryptoServiceProvider();
byte[] initial_key = new byte[16];
Array.Copy(sha1.ComputeHash(data), initial_key, initial_key.Length);
 
byte[][] bytes_array = new byte[1][];
bytes_array[0] = bytes;
var handler = new CertificateSecurityHandler()
var encrypt_data = new CertificateEncryptData()
encrypt_data.Set(true, SecurityHandler.CipherType.e_CipherAES, bytes_array);
handler.Initialize(encrypt_data, initial_key);
 
doc.SetSecurityHandler(handler);
doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
...

How to encrypt a PDF file with Foxit DRM

using foxit.common;
using foxit.pdf;
...
PDFDoc doc = new PDFDoc(input_file);
ErrorCode error_code = doc.Load(null);
if (error_code != ErrorCode.e_ErrSuccess){
 return;
}
 
// Do encryption.
var handler = new DRMSecurityHandler();
var encrypt_data = new DRMEncryptData(true,"Simple-DRM-filter", SecurityHandler.CipherType.e_CipherAES, 16, true, -4);
string file_id = "Simple-DRM-file-ID";
string initialize_key = "Simple-DRM-initialize-key";
handler.Initialize(encrypt_data, file_id, initialize_key);
doc.SetSecurityHandler(handler);
doc.SaveAs(output_file, (int)PDFDoc.SaveFlags.e_SaveFlagNormal);
...

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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
... 
 
// Assuming PDFDoc doc has been loaded.
 
PDFPage page = doc.GetPage(0);
 
// Parse PDF page.
page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.e_ParsePageNormal, null, false);
 
ReflowPage reflow_page = new ReflowPage(page);
 
// Set some arguments used for parsing the reflow page.
reflow_page.SetLineSpace(0);
reflow_page.SetZoom(100);
reflow_page.SetParseFlags((int)ReflowPage.Flags.e_WithImage);
 
// 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();
 
// Assuming Bitmap bitmap has been created.
 
// Render reflow page.
Renderer renderer = new Renderer(bitmap, false);
Matrix2D matrix = reflow_page.GetDisplayMatrix(0, 0);
renderer.StartRenderReflowPage(reflow_page, matrix, null);
...

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:

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.annots;
...
 
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;
Path.PointType type = Path.PointType.e_TypeMoveTo;
foxit.common.fxcrt.PointF pt = new foxit.common.fxcrt.PointF(x, y);
psi.AddPoint(pt, 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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.graphics;
using foxit.pdf.objects;
 
// Assuming PDFDoc doc has been loaded.
 
// file_name is PDF document which includes wrapper data.
PDFDoc doc = new PDFDoc(file_name);
ErrorCode code = doc.Load(null);
if (code != ErrorCode.e_ErrSuccess)
{
return;
}
if (!doc.IsWrapper())
{
return;
}
 
long offset = doc.GetWrapperOffset();
FileReader file_reader = new FileReader(offset);
file_reader.LoadFile(file_name);
...

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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.graphics;
using foxit.pdf.objects;
...
 
// Assuming PDFDoc doc has been loaded.
 
PDFDictionary doc_catalog_dict = doc.GetCatalog();
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 below 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

using foxit.common;
using foxit.pdf;
using foxit.pdf.graphics; 
using foxit.common.fxcrt;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
long position = page.GetLastGraphicsObjectPosition(GraphicsObject.Type.e_TypeText);
TextObject text_object = TextObject.Create();
text_object.SetFillColor(0xFFFF7F00);
 
// Prepare text state.
TextState state = new TextState();
Font font = new Font("Simsun", (int)Font.Styles.e_StylesSmallCap, Font.Charset.e_CharsetGB2312, 0);
state.font_size = 80.0f;
state.font = font;
state.textmode = TextState.Mode.e_ModeFill;
text_object.SetTextState(page, state, false, 750);
 
// Set text.
text_object.SetText("Foxit Software");
long last_position = page.InsertGraphicsObject(position, text_object);
...

How to add an image logo to a PDF page

using foxit.common;
using foxit.pdf;
using foxit.pdf.graphics; 
using foxit.common.fxcrt;
...
 
// Assuming PDFPage page has been loaded and parsed.
 
long position = page.GetLastGraphicsObjectPosition(GraphicsObject.Type.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();
 
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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.pdf.graphics;
using foxit.pdf.objects;
 
... 
// Assuming PDFPage page has been loaded and parsed.
 
long position = page.GetFirstGraphicsObjectPosition(GraphicsObject.Type.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

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
 ...
// Assuming PDFDoc doc has been loaded.
// Assuming PDFpage page has been loaded and parsed.
 
LayerTree layertree = new LayerTree(doc);
LayerNode root = layertree.GetRootNode();
...

How to set all the layer nodes information

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
...
// Assuming PDFDoc doc has been loaded.
// Assuming PDFpage page has been loaded and parsed.
 
public static void SetAllLayerNodesInformation(LayerNode layer_node) 
{
 if (layer_node.HasLayer()) 
 {
 layer_node.SetDefaultVisible(true);
 layer_node.SetExportUsage(LayerTree.UsageState.e_StateUndefined);
 layer_node.SetViewUsage(LayerTree.UsageState.e_StateOFF);
 LayerPrintData print_data = new LayerPrintData("subtype_print", LayerTree.UsageState.e_StateON);
 layer_node.SetPrintUsage (print_data);
 LayerZoomData zoom_data = new LayerZoomData(1, 10);
 layer_node.SetZoomUsage(zoom_data);
 string new_name = "[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++) 
 {
 using (LayerNode child = layer_node.GetChild(i))
 {
 SetAllLayerNodesInformation(child);
 }
 }
}
 
LayerTree layertree = new LayerTree(doc);
LayerNode root = layertree.GetRootNode();
if (root.IsEmpty())
{
 return;
}
SetAllLayerNodesInformation(root);
...

How to traverse layer tree and set the opposite visible state of every PDF layer

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
 ...
// Assuming PDFDoc doc has been loaded.
// Assuming PDFpage page has been loaded and parsed.
 
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 handler 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

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using foxit.common;
using foxit.pdf;
using foxit;
using foxit.pdf.annots;
using foxit.common.fxcrt;
using System.Runtime.InteropServices;
using foxit.pdf.interform;
 
static foxit.common.DateTime GetLocalDateTime()
{
 System.DateTimeOffset rime = System.DateTimeOffset.Now;
 foxit.common.DateTime datetime = new foxit.common.DateTime();
 datetime.year = (UInt16)rime.Year;
 datetime.month = (UInt16)rime.Month;
 datetime.day = (ushort)rime.Day;
 datetime.hour = (UInt16)rime.Hour;
 datetime.minute = (UInt16)rime.Minute;
 datetime.second = (UInt16)rime.Second;
 datetime.utc_hour_offset = (short)rime.Offset.Hours;
 datetime.utc_minute_offset = (ushort)rime.Offset.Minutes;
 return datetime;
}
 
static Signature AddSiganture(PDFPage pdf_page, string sub_filter) {
 float page_height = pdf_page.GetHeight();
 float page_width = pdf_page.GetWidth();
 RectF new_sig_rect = new RectF(0, (float)(page_height*0.9), (float)(page_width*0.4), page_height);
 // Add a new signature to page.
 Signature new_sig = pdf_page.AddSignature(new_sig_rect);
 if (new_sig.IsEmpty()) return null;
 // Set values for the new signature.
 new_sig.SetKeyValue(Signature.KeyName.e_KeyNameSigner, "Foxit PDF SDK");
 String new_value = String.Format("As a sample for subfilter \"{0}\"", sub_filter);
 new_sig.SetKeyValue(Signature.KeyName.e_KeyNameReason, new_value);
 new_sig.SetKeyValue(Signature.KeyName.e_KeyNameContactInfo, "support@foxitsoftware.com");
 new_sig.SetKeyValue(Signature.KeyName.e_KeyNameDN, "CN=CN,MAIL=MAIL@MAIL.COM");
 new_sig.SetKeyValue(Signature.KeyName.e_KeyNameLocation, "Fuzhou, China");
 new_value = String.Format("As a sample for subfilter \"{0}\"", sub_filter);
 new_sig.SetKeyValue(Signature.KeyName.e_KeyNameText, new_value);
 foxit.common.DateTime sign_time = GetLocalDateTime();
 new_sig.SetSignTime(sign_time);
 String image_file_path = input_path + "FoxitLogo.jpg";
 using (Image image = new Image(image_file_path))
 {
 new_sig.SetImage(image, 0);
 // Set appearance flags to decide which content would be used in appearance.
 int ap_flags = Convert.ToInt32(Signature.APFlags.e_APFlagLabel | Signature.APFlags.e_APFlagSigner |
 Signature.APFlags.e_APFlagReason | Signature.APFlags.e_APFlagDN |
 Signature.APFlags.e_APFlagLocation | Signature.APFlags.e_APFlagText |
 Signature.APFlags.e_APFlagSigningTime | Signature.APFlags.e_APFlagBitmap);
 new_sig.SetAppearanceFlags(ap_flags);
 }
 
 return new_sig;
}
 
static void AdobePPKLiteSignature(PDFDoc pdf_doc) {
 string filter = "Adobe.PPKLite";
 string sub_filter = "adbe.pkcs7.detached";
 
 using (PDFPage pdf_page = pdf_doc.GetPage(0))
 {
 // Add a new signature to first page.
 using (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);
 
 // Sign the new signature.
 String signed_pdf_path = output_directory + "signed_newsignature.pdf";
 
 String cert_file_path = input_path + "foxit_all.pfx";
 byte[] cert_file_password = Encoding.ASCII.GetBytes("123456");
 new_signature.StartSign(cert_file_path, cert_file_password,
 Signature.DigestAlgorithm.e_DigestSHA1, signed_pdf_path, IntPtr.Zero, null);
 Console.WriteLine("[Sign] Finished!");
 }
 }
}
 
static void Main(String[] args)
{
 ...
 AdobePPKLiteSignature(pdf_doc);
 ...
}

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:

using foxit.common;
using foxit.pdf;
using foxit;
using foxit.pdf.annots;
using foxit.common.fxcrt;
using foxit.pdf.annots;
using foxit.pdf.actions;
 
// Add link annotation
Link link = null;
Annot annot = null;
using (annot = page.AddAnnot(Annot.Type.e_Link, new RectF(350, 350, 380, 400)))
using (link = new Link(annot))
using (PDFDoc doc = page.GetDocument())
{
 foxit.pdf.actions.Action action = null;
 link.SetHighlightingMode(Annot.HighlightingMode.e_HighlightingToggle);
 
 // Add action for link annotation
 URIAction uriaction = null;
 using (action = foxit.pdf.actions.Action.Create(doc, foxit.pdf.actions.Action.Type.e_TypeGoto))
 using (uriaction = new URIAction(action))
 {
 uriaction.SetTrackPositionFlag(true);
 uriaction.SetURI("www.foxitsoftware.com");
 link.SetAction(uriaction);
 
 // Appearance should be reset.
 link.ResetAppearanceStream();
 }
}
using foxit.common;
using foxit.pdf;
using foxit;
using foxit.pdf.annots;
using foxit.common.fxcrt;
using foxit.pdf.annots;
using foxit.pdf.actions;
 
using foxit.common;
using foxit.pdf;
using foxit;
using foxit.pdf.annots;
using foxit.common.fxcrt;
using foxit.pdf.annots;
using foxit.pdf.actions;
 
Link link = null;
Annot annot = null;
using (annot = page.AddAnnot(Annot.Type.e_Link, new RectF(350, 350, 380, 400)))
using (link = new Link(annot))
using (PDFDoc doc = page.GetDocument())
{
 foxit.pdf.actions.Action action = null;
 link.SetHighlightingMode(Annot.HighlightingMode.e_HighlightingToggle);
 
 // Add action for link annotation
 GotoAction gotoaction = null;
 using (action = foxit.pdf.actions.Action.Create(doc, foxit.pdf.actions.Action.Type.e_TypeGoto))
 using (gotoaction = new GotoAction(action))
 {
 Destination dest = Destination.CreateXYZ(doc, 0, 0, 0, 0);
 gotoaction.SetDestination(dest);
 link.SetAction(gotoaction);
 // Appearance should be reset.
 link.ResetAppearanceStream();
 }
}

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 foxit.pdf.actions.JavaScriptAction is derived from Action and offers functions to get/set JavaScript action data.

Example:

How to add JavaScript Action to Document

using foxit.pdf.annots;
using foxit.pdf.actions;
 
// Load Document doc
...
using (JavaScriptAction javascipt_action = new JavaScriptAction(action))
{
 javascipt_action.SetScript("app.alert(\"Hello Foxit \");");
 using (AdditionalAction aa = new AdditionalAction(doc))
 {
 aa.SetAction(AdditionalAction.TriggerEvent.e_TriggerDocWillClose, javascipt_action);
 }
}
...

How to add JavaScript Action to Annotation

using foxit.pdf.annots;
using foxit.pdf.actions;
...
 
// Load Document and get a widget annotation.
...
using (JavaScriptAction javascipt_action = new JavaScriptAction(action))
{
 javascipt_action.SetScript("app.alert(\"Hello Foxit \");");
 using (AdditionalAction aa = new AdditionalAction(annot))
 {
 aa.SetAction(AdditionalAction.TriggerEvent.e_TriggerAnnotMouseButtonPressed, javascipt_action);
 }
}
...

How to add JavaScript Action to FormField

using foxit.pdf.interform;
using foxit.pdf.actions;
...
 
// Load Document and get a form field.
...
 
using (JavaScriptAction javascipt_action = new JavaScriptAction(action))
{
 javascipt_action.SetScript("AFSimple_Calculate(\"SUM\", new Array (\"Text Field0\", \"Text Field1\"));");
 using (AdditionalAction aa = new AdditionalAction(field))
 {
 aa.SetAction(AdditionalAction.TriggerEvent.e_TriggerFieldRecalculateValue, javascipt_action);
 }
}
...

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 foxit.addon.Redaction to create a redaction module. If module “Redaction” is not defined in the license information which is used in function common.Library.Initialize , that means user has no right in using redaction related functions and this constructor will throw exception foxit.common.ErrorCode.e_ErrInvalidLicense .
  • Then call function foxit.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 foxit.addon.Redaction.Apply to apply redaction in marked areas: remove the text or graphics under marked areas permanently.

Example:

How to redact the text “PDF” on the first page of a PDF

using foxit;
using foxit.common;
using foxit.common.fxcrt;
using foxit.pdf;
using foxit.addon;
using foxit.pdf.annots; 
 
... 
using (Redaction redaction = new Redaction(doc))
{
 using (PDFPage page = doc.GetPage(0))
 {
 // Parse PDF page.
 page.StartParse((int)foxit.pdf.PDFPage.ParseFlags.e_ParsePageNormal, null, false);
 TextPage text_page = new TextPage(page, (int)foxit.pdf.TextPage.TextParseFlags.e_ParseTextNormal);
 TextSearch text_search = new TextSearch(text_page);
 text_search.SetPattern("PDF");
 RectFArray rect_array = new RectFArray();
 while (text_search.FindNext())
 {
 RectFArray itemArray = text_search.GetMatchRects();
 rect_array.InsertAt(rect_array.GetSize(), itemArray);
 }
 if (rect_array.GetSize() > 0)
 {
 Redact redact = redaction.MarkRedactAnnot(page, rect_array);
 redact.ResetAppearanceStream();
 doc.SaveAs(output_path + "AboutFoxit_redected_default.pdf", (int)foxit.pdf.PDFDoc.SaveFlags.e_SaveFlagNormal);
 
 // set border color to Green
 redact.SetBorderColor(0x00FF00);
 // set fill color to Blue
 redact.SetFillColor(0x0000FF);
 // set rollover fill color to Red
 redact.SetApplyFillColor(0xFF0000);
 redact.ResetAppearanceStream();
 doc.SaveAs(output_path + "AboutFoxit_redected_setColor.pdf", (int)foxit.pdf.PDFDoc.SaveFlags.e_SaveFlagNormal);
 
 redact.SetOpacity((float)0.5);
 redact.ResetAppearanceStream();
 doc.SaveAs(output_path + "AboutFoxit_redected_setOpacity.pdf", (int)foxit.pdf.PDFDoc.SaveFlags.e_SaveFlagNormal);
 
 if (redaction.Apply())
 Console.WriteLine("Redact page(0) succeed.");
 else
 Console.WriteLine("Redact page(0) failed.");
 redact.Dispose();
 }
 }
}

 

References

[1] PDF reference 1.7
http://www.iso.org/iso/iso_catalogue/catalogue_tc/catalogue_detail.htm?csnumber=51502

[2] PDF reference 2.0
https://www.iso.org/standard/63534.html

[3] Foxit PDF SDK API reference
sdk_folder/doc/Foxit PDF SDK Dotnet API Reference.html

Note: sdk_folder is the directory of unzipped package.
Support
Foxit support home link:
http://www.foxitsoftware.com/support/

Sales contact phone number:
Phone: 1-866-680-3668
Email: sales@foxitsoftware.com

Support & General contact:

Phone: 1-866-MYFOXIT or 1-866-693-6948
Email: support@foxitsoftware.com

Updated on March 7, 2019

Was this article helpful?

Related Articles