Click here to Skip to main content
13,767,441 members
Click here to Skip to main content
Add your own
alternative version

Stats

4.8K views
2 bookmarked
Posted 8 Nov 2018
Licenced CPOL

PDF ALL THE THINGS: Master PDF Files with ActivePDF Toolkit

, 8 Nov 2018
Rate this:
Please Sign up or sign in to vote.
In this article I review the DocGenius™ Toolkit by ActivePDF, a powerful .NET library for manipulating PDF documents.

Editorial Note

This Review is from our sponsors at CodeProject. These reviews are intended to provide you with information on products and services that we consider useful and of value to developers.

In this article I review the DocGenius™ Toolkit by ActivePDF, a powerful .NET library for manipulating PDF documents. Portable Document Format (PDF) is a document format standard that has existed for decades now and is rapidly growing in popularity as a way to securely share data across platforms and devices. Toolkit gives developers a fast and easy low-code way to create, convert, modify, view, extract, and automate PDF documents using a simple line of code. It provides hundreds of intuitive APIs that cover scenarios from adding attachments to generating barcodes.

Download ActivePDF Toolkit

The first step is to download Toolkit.

The installer is available at the following URL:

https://www.activepdf.com/products/toolkit

The installation is straightforward and walks you through all the necessary steps. Toolkit requires a license for activation. This is easily obtained at ActivePDF.com and a free trial key was emailed to me right away.

How to Create a PDF File

The first scenario I tried was creating a new PDF. The website has plenty of documentation including examples that you can view at: https://examples.activepdf.com/Toolkit/2018/

In Visual Studio 2017, I created a new Windows desktop console application. I added a reference to APToolkitNET.dll that was located under the DotNetComponent folder in the installation directory. Toolkit defaults to 72 pixels per inch, so I set up a variable to represent an inch:

const float INCH = 72f;

This is the code to create a new PDF that is 8.5" x 11" (the standard U.S. "letter" size for printing):

// Instantiate Object
APToolkitNET.Toolkit oTK = new APToolkitNET.Toolkit
{
    // Set the PDF page Height and Width (72 = 1")
    OutputPageHeight = 11f * INCH,
    OutputPageWidth = 8.5f * INCH
};

I specified the output file location and loaded the version of the toolkit into a variable. I also indicated I was ready to start producing a new page in the document (the first page):

int intOpenOutputFile = oTK.OpenOutputFile(strPath + "new.pdf");

// Each time a new page is required call NewPage
oTK.NewPage();

// Get the current version of Toolkit and save it to print on the PDF
string tkVer = oTK.ToolkitVersion;

I set the font and font-size, then printed two lines. The method used allows you to specify where the text will be generated.

There is also a method called PrintMultilineText that takes an area as a parameter and will wrap the text for you and left, right, or full justify it based on a parameter. The first parameter indicates a 1" margin on the left. The second parameter is the height from the bottom of the page:

oTK.SetFont("Helvetica", 24);
oTK.PrintText(INCH, 10f * INCH, $"Hello! Version {tkVer}");
oTK.PrintText(INCH, 9.5f * INCH, $"Date: {DateTime.Now}");

A document can be boring without an image, so I copied my profile picture into the same directory as the console app and used this statement to print the image on the PDF canvas:

oTK.PrintJPEG(strPath + "IMG.jpg", INCH, 8 * INCH, 110.0f, 107.0f, true);

The final step is to close the PDF document. This will process your requests and flush the file to disk:

oTK.CloseOutputFile();

I compiled and ran the console application, and it immediately generated a new PDF file. The following screenshot shows what was produced:

Figure 1: A PDF generated from scratch with ActivePDF Toolkit, a .NET C# library of PDF API calls for developers.

I was able to get up and running, successfully generating a PDF document with low code, in minutes.

How to Modify and Process an Existing PDF

The next task I tackled was processing an existing PDF. I chose to start with the new PDF I just created and do something simple: Add some metadata.

PDF documents contain information about the title, author, and keywords. I created a new console app, and this time instead of creating a new PDF document, I opened the old document:

APToolkitNET.Toolkit oTK = new APToolkitNET.Toolkit();      
oTK.OpenOutputFile(strPath + "copy.pdf");
oTK.OpenInputFile(strPath + "new.pdf");

Next, I used the API to add some simple metadata:

oTK.SetInfo("My First PDF", "Testing", "Jeremy Likness", "test, pdf, sample");

Finally, I copied the templates between the input and output files and closed the output to generate a new PDF:

oTK.CopyForm(0, 0);
oTK.CloseOutputFile();

I ran the console app which produced a new copy.pdf file.

I opened the PDF to verify that it looks exactly like the original. The one difference was evident when I opened the properties dialog. Notice the metadata is now populated:

Figure 2: PDF metadata generated from ActivePDF Toolkit for developers in low code environments.

It took me just five minutes to build the new app and modify the existing PDF.

How to Manipulate Form Fields

Most PDF documents and technology support form fields, depending on the technology provider at hand. A common business scenario involves processing a PDF form by pre-populating certain fields.

For example, an insurance company may wish to generate claim forms that are pre-filled with customer data, making them easier to fill out. I chose a publicly available form called a "W-9" that is used to report earnings to the IRS. You can download the latest W-9 form here: https://www.irs.gov/pub/irs-pdf/fw9.pdf

The first step is to load the form and iterate through the form fields. As with the previous example, I simply open the downloaded form named fw9.pdf, create an output file named fw9_filled.pdf and this will generate a copy without modifying the original PDF. The code to iterate the form fields looks like this:

var inputs = oTK.GetInputFields();
foreach(DictionaryEntry input in inputs)
{
    Console.WriteLine($"Found: {input.Key}");
}

I’m glad I ran this first because the form field names aren’t all intuitive and it took some guesswork to find the ones I wanted.

Figure 3: Form fields in fw9.pdf

The next goal was to programmatically enter my name and address. I used my name and ActivePDF’s address for this example.

The code indicates that Toolkit should format the fields and give them unique names to avoid collisions in the output document. This is useful when merging multiple PDFs into a single one to avoid conflicts. I then set the fields by passing the field name, the value, and a flag indicating the type of field:

oTK.DoFormFormatting = 1;
oTK.FormNumbering = 1;
oTK.SetFormFieldData("topmostSubform[0].Page1[0].f1_1[0]", "Jeremy Likness", 1);
oTK.SetFormFieldData("topmostSubform[0].Page1[0].Address[0].f1_7[0]", "28202 Cabot Rd Ste 155", 1);
oTK.SetFormFieldData("topmostSubform[0].Page1[0].Address[0].f1_8[0]", "Laguna Niguel, CA 92677", 1);

I ran the console app with the form code added:

Figure 4: Filled form

As you can see, I was successful with programmatically filling out the form.

How to Work with PDF Security Barricades

The W-9 form contains sensitive information such as a social security number and personal address, so it is important to secure the document. The process to encrypt the output PDF is straightforward. I added this line to the existing console application before opening any files:

oTK.SetPDFSecurity(5, "secretuser", "secretowner", true, false, true, false);

It’s important to note that the evaluation version automatically prepends "DEMO" to the passwords, making them "DEMOsecretuser" and "DEMOsecretowner." I also cleared the security settings at the end of the method:

oTK.ClearPDFSecurity();

Re-running the app encrypted the document and locked it with a password when I tried to open it.

Figure 5: Newly-encrypted PDF document with password after processing through ActivePDF Toolkit for developers.

After typing in the user password, the document successfully opened. I also set flags that prevent modifying the document or filling out form fields.

When the new document is opened, although the form fields I programmatically updated are pre-filled, there is no input available to make any further modifications. This protects the file from unwanted tampering or further unwanted modification from other users. Summary of Working with the .NET PDF Toolkit Product by ActivePDF

ActivePDF’s Toolkit provides a wealth of capabilities for creating, merging, and manipulating PDF documents. Features that weren’t covered in this article include page numbering, versioning, drawing, digital watermarking, setting page labels, and more.

The API is straightforward and intuitive and, coupled with the documentation and examples, make it incredibly easy to use. You can find example code here:

https://examples.activepdf.com/Toolkit/2018/

Start your first .NET project and manipulate PDF documents today with Toolkit inside your applications with a free trial available from ActivePDF.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Jeremy Likness
Instructor / Trainer Microsoft
United States United States
Note: articles posted here are independently written and do not represent endorsements nor reflect the views of my employer.

Jeremy Likness is a Cloud Developer Advocate for Azure at Microsoft. Jeremy has spent two decades building enterprise software with a focus on line of business web applications. Jeremy is the author of several highly acclaimed technical books including Designing Silverlight Business Applications and Programming the Windows Runtime by Example. He has given hundreds of technical presentations during his career as a professional developer. In his free time, Jeremy likes to CrossFit, hike, and maintain a 100% plant-based diet.

Jeremy's roles as business owner, technology executive and hands-on developer provided unique opportunities to directly impact the bottom line of multiple businesses by helping them grow and increase their organizational capacity while improving operational efficiency. He has worked with several initially small companies like Manhattan Associates and AirWatch before they grew large and experienced their transition from good to great while helping direct vision and strategy to embrace changing technology and markets. Jeremy is capable of quickly adapting to new paradigms and helps technology teams endure change by providing strong leadership, working with team members “in the trenches” and mentoring them in the soft skills that are key for engineers to bridge the gap between business and technology.

You may also be interested in...

Comments and Discussions

 
-- There are no messages in this forum --
Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web01-2016 | 2.8.181116.1 | Last Updated 8 Nov 2018
Article Copyright 2018 by Jeremy Likness
Everything else Copyright © CodeProject, 1999-2018
Layout: fixed | fluid