Quickly and Easily Add Headers and Footers to PDFs in Java

Casie LiuCasie Liu
5 min read

When working with PDF documents, it's often useful to add headers and footers to every page — whether it's for showing the document title, chapter names, dates, or page numbers. If you're dealing with a large number of files or need consistent formatting across pages, doing this manually isn’t practical. In this article, let’s walk through how to add headers and footers to PDF using Java.

Before We Start: Install Java Library

In this tutorial, we’ll be using Spire.PDF for Java — a powerful yet easy-to-use PDF library. It allows us to read, edit, and convert PDF files with ease, and of course, it also supports adding headers and footers. With Spire.PDF, we can automate PDF processing tasks and skip the hassle of doing everything manually.

To get started, we just need to download the Spire.PDF package and add it to our Java project. There’s also a free version available, which comes without watermarks. Due to some feature limitations, it’s best suited for small projects or for testing the library.

Once everything is set up, we’re ready to start adding headers and footers to our PDF files automatically.

Add Header to PDF in Java without Effort

In a PDF document, we can add a header to the top of each page to include extra information beyond the main content — such as a company logo, the document’s creation date, or a short slogan. With the help of Spire.PDF, we can draw this content directly onto the page using drawline() and drawimage() methods.

Below is a complete code example. After the example, we’ll walk through how adding a header to a PDF actually works in Java.

Code Example: Add an Image and Text to the Header of PDF Pages

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;

import java.awt.*;

public class PDFHeader {

   public static void main(String[] args) {

       // Create a PdfDocument instance and load a PDF
       PdfDocument pdf = new PdfDocument();
       pdf.loadFromFile("/input/AI-Generated Art.pdf");

       // Load a header image
       PdfImage headerImage = PdfImage.fromFile("/logo1.png");

       // Retrieve the image width
       float width = headerImage.getWidth();
       PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
       float pointWidth = unitCvtr.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);

       // Specify the header text
       String headerText = "This is a hearder\ncreated by Java";

       // Create a font
       PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arail", Font.BOLD, 12),true);

       // Create a brush
       PdfBrush brush = PdfBrushes.getRed();
       PdfPen pen = new PdfPen(PdfBrushes.getBlack(), 1.0f);

       // Loop through all pages
       for (int i = 0; i < pdf.getPages().getCount(); i++)
       {
           // Get the specific page
           PdfPageBase page = pdf.getPages().get(i);

           // Draw image at the top
           page.getCanvas().drawImage(headerImage, page.getActualSize().getWidth() - pointWidth - 55, 20);

           // Draw text
           page.getCanvas().drawString(headerText, font, brush, 55, 30);

           // Draw a line
           page.getCanvas().drawLine(pen, new Point(55, 70), new Point((int)page.getActualSize().getWidth() - 55, 70));

       }

       // Save the PDF document
       pdf.saveToFile("/output/addpdfheader.pdf");
       pdf.dispose();
   }
}

Add Header Image and Header Text to a PDF Page Java

Detailed Steps Explained:

  • Create a PdfDocument instance and load a PDF.

  • Load a header image and retrieve the image width.

  • Specify the header text.

  • Create a PdfTrueTypeFont instance.

  • Create a brush.

  • Loop through all pages and get the specific page.

  • Draw an image at the top using the PdfPageBase.getCanvas().drawImage() method.

  • Draw text with the PdfPageBase.getCanvas().drawString() method.

  • Draw a line through the PdfPageBase.getCanvas().drawLine() method.

  • Save the PDF document.

In a PDF file, the footer usually contains elements like page numbers, copyright information, author names, and more. Page numbers are especially useful — they help readers navigate the document and greatly improve readability.

Now, let’s take a look at how we can use Java to automatically add footers to a PDF and save ourselves from the manual effort.

Example: Add Page Number and Total Pages to PDF Footer

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.geom.Point2D;

public class PDFFooter {

   public static void main(String[] args) {

       // Create a PdfDocument object and load a PDF
       PdfDocument pdf = new PdfDocument();
       pdf.loadFromFile("/input/AI-Generated Art.pdf");

       // Create a font
       PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.BOLD, 12),true);

       // Create a brush
       PdfBrush brush = PdfBrushes.getBlack();
       PdfPen pen = new PdfPen(PdfBrushes.getBlack(), 1.0f);

       // Create a page number field
       PdfPageNumberField pageNumberField = new PdfPageNumberField();

       // Create a page count field
       PdfPageCountField pageCountField = new PdfPageCountField();

       // Create a composite field to merge the page number field and page count field into a string
       PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} / Total Page {1}", pageNumberField, pageCountField);

       // Get the size of the text
       Dimension2D fontSize = font.measureString(compositeField.getText());

       // Get the page size
       Dimension2D pageSize = pdf.getPages().get(0).getSize();

       // Set the position of the composite field
       compositeField.setLocation(new Point2D.Double((pageSize.getWidth() - fontSize.getWidth())/2,  pageSize.getHeight() - 45));

       // Loop through each page
       for (int i = 0; i < pdf.getPages().getCount(); i++)
       {
           // Get the specified page
           PdfPageBase page = pdf.getPages().get(i);

           // Draw a line
           page.getCanvas().drawLine(pen, new Point(72, (int) (pageSize.getHeight() - 60)), new Point((int)pageSize.getWidth() - 72, (int) pageSize.getHeight()- 60));

           // Draw the composite field
           compositeField.draw(page.getCanvas());
       }

       // Save the PDF file
       pdf.saveToFile("/output/addpdffooter.pdf");
       pdf.dispose();
   }
}

Add Page Number and Page Count to a PDF Page Java

Key Steps Explained:

Since the rest of the steps are similar to adding a header, we won’t go over them again here. Instead, let’s focus on a few key parts of the process.

  • Create a PdfPageNumberField and a PdfPageCountField object.

  • Create a PdfCompositeField object to merge the two fields created before.

  • Get the size of the text.

  • Get the page size.

  • Set the position of the composite field using the PdfCompositeField.setLocation() method.

  • Draw the composite field to the footer area with the PdfCompositeField.draw() method.

The Conclusion

In this post, we looked at how to add headers and footers to a PDF using Java. With Spire.PDF, it’s easy to insert text, images, or fields into those areas and customize them however you like.

Hopefully, by the time you finish reading, you’ll find adding headers and footers to PDFs is no big deal at all.
Check out the rest of the blog for more PDF tips, and feel free to drop a comment below if you have any questions or just want to share your thoughts.

0
Subscribe to my newsletter

Read articles from Casie Liu directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Casie Liu
Casie Liu