Adding Headers and Footers to an Existing PDF

Adding Headers and Footers to an Existing PDF

In my last post, we looked at the PDF Library’s basic text creation methods in an application written to solve a real world problemRecently, I was asked how to use the PDF Library to add headers and footers to existing PDFs without writing over the existing content. Of course, we can utilize the same API methods that we used in the previous example to create the text, but how will the application know if there is enough room to place the text and how can we get it to adjust position automatically?

This question gives us a chance to explore the techniques of examining PDF page boxes and measuring text. The PDF specification identifies five familiar page boundaries (or boxes) — MediaBox, CropBox, BleedBox, TrimBox, and ArtBox —  of which, the CropBox is the only required component and represents “the region to which the contents of the page shall be clipped (cropped) when displayed or printed.”

page-boundaries (002)

The PDF Library adds one more option – the Bounding Box or BBox. Unlike the PDF specification’s page boundaries, the Bounding Box is derived from the page content. PostScript users will be familiar with the concept, but in PDF Library terms, the Bounding Box is an array of four numbers giving the left, bottom, right, and top coordinates that encompass the marking content (all text, graphics, and images) on the page.

Once we have the Bounding Box and the Crop Box, we can compare the coordinates and determine how much space is available.

You can present some options to the user as to how they would like the header and footer to look, but for now we will just specify them directly:

To calculate the width of the text at a specific font and pointsize, we create our TextRun and call our function to measure the text and calculate the starting position:

We then use the TextRun Advance in the calculations:

And finally, add the text to the page:

The full code can be downloaded here.  It can be expanded to allow additional options such as color text and font embedding.

The same concept of examining the Bounding Box would be suitable for adding Bates numbers to a page. Perhaps we can take a look at that next time!

For more information on the PDF Library, click here or contact us!

Leave a Reply

Your email address will not be published. Required fields are marked *