Tech

Rendering Annotations in PDFs with Quick PDF Library

by Conor Smith | February 15, 2018

Including annotations and form field data in PDF outputs is a handy function to have in Quick PDF Library. But it is important to first understand how Quick PDF Library renders PDFs and secondly how to ensure that they render annotations and form field data correctly.

The PDF rendering engines that are available in Quick PDF Library render annotations or form fields through using straightforward functions. With only two or three lines of code, you can render or print a file which contains annotations or completed form fields. Below are the steps taken to include annotations and form fields in the output of your PDF file.

Annotations

For PDF files that contain annotations, you first have to call the Flatten function. To give some background into annotations: they are not part of the PDF content stream used for rendering. Annotations are stored in a separate PDF dictionary that contains information about every annotations position, color, style, etc. So before the rendering of all this information, it has to be pulled from the library and made part of the PDF content stream.

FlattenAnnot is the function we use to do this. Say we need to render page 3 of a PDF to include annotations that the file contains, here are the steps that we need to take:

QPL.SelectPage(3); // Selecting page 3 of the PDF document open in Quick PDF Library
annotCount = QPL.AnnotationCount; // Getting the annotation count that are on the page

for (int i = annotCount; i>0; i–) //notice that we are using a reverse loop
QPL.FlattenAnnot(i);

QPL.RenderPageToFile(92, 3, 5, “new file.png”)//render the page 3 as png image at 92 DPI

We use a reverse loop because, with every flattened annotation, the real current annotation count decreases and that may lead to memory issues if we would use a classic forward loop.

Interesting fact: In some programming languages reverse loops are faster than forward loops.

Form Fields

PDF files that contain form field data are in a similar situation to annotations. Again the form field data is not stored in a content stream, so it needs to be flattened. The issue may arise though, that form field data can have a hierarchical order. This means that one form field may be a parent field for a child field. If this is true in a PDF file, the parent field will be flattened, and all the information from the child fields is lost. This is something that we don’t want.

It looks tricky to implement but, with Quick PDF Library, there is a workaround. You just have to use function FlattenAllFormFields like this:

QPL.FlattenAllFormFields(0)
QPL.RenderPageToFile(92, 3, 5, “new file.png”)//render the page 3 as png image at 92 DPI

This function will flatten all fields in a PDF file, including all parent and child fields.