Backend Development 8 min read

Add Custom PDF Headers and Footers with Java and Free Spire.PDF

This tutorial explains how to programmatically add headers and footers—including text, images, page numbers, and separator lines—to every page of a PDF using Java and the free Spire.PDF library, with complete code examples and visual results.

Java Captain
Java Captain
Java Captain
Add Custom PDF Headers and Footers with Java and Free Spire.PDF
Source: https://www.cnblogs.com/Yesi/p/18094584

When processing PDF documents, you may need to add a header and footer to each page to display useful information such as the document title, chapter name, date, or page number. This article shows how to achieve this automatically with Java.

Required tool: Free Spire.PDF for Java (free library). Download the latest version and add it to your Java project manually or via Maven.

Method Overview:

The example uses the PdfCanvas class methods DrawString() , DrawImage() and DrawLine() to draw text, images and lines at specified positions on PDF pages.

For dynamic information such as page numbers, total pages, or section numbers, you can use the PdfPageNumberField , PdfPageCountField and PdfSectionNumberField classes provided by Free Spire.PDF, then draw them with the Draw() method.

Example Code:

1. Insert Header with Java

<code>import com.spire.pdf.PdfDocument;</code>
<code>import com.spire.pdf.PdfPageBase;</code>
<code>import com.spire.pdf.graphics.*;</code>
<code>import java.awt.*;</code>
<code>public class PDFHeader {</code>
<code>    public static void main(String[] args) {</code>
<code>        // Load PDF document</code>
<code>        PdfDocument pdf = new PdfDocument();</code>
<code>        pdf.loadFromFile("考核.pdf");</code>
<code>        // Load image</code>
<code>        PdfImage headerImage = PdfImage.fromFile("logo.jpg");</code>
<code>        float width = headerImage.getWidth();</code>
<code>        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();</code>
<code>        float pointWidth = unitCvtr.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);</code>
<code>        // Header text</code>
<code>        String headerText = "年度绩效考核\nAAA有限责任公司";</code>
<code>        // Create font</code>
<code>        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", Font.BOLD, 12), true);</code>
<code>        // Create brush and pen</code>
<code>        PdfBrush brush = PdfBrushes.getRed();</code>
<code>        PdfPen pen = new PdfPen(PdfBrushes.getBlack(), 1.0f);</code>
<code>        // Iterate all pages</code>
<code>        for (int i = 0; i < pdf.getPages().getCount(); i++) {</code>
<code>            PdfPageBase page = pdf.getPages().get(i);</code>
<code>            page.getCanvas().drawImage(headerImage, page.getActualSize().getWidth() - pointWidth - 55, 20);</code>
<code>            page.getCanvas().drawString(headerText, font, brush, 55, 30);</code>
<code>            page.getCanvas().drawLine(pen, new Point(55, 70), new Point((int)page.getActualSize().getWidth() - 55, 70));</code>
<code>        }</code>
<code>        pdf.saveToFile("PDF页眉.pdf");</code>
<code>        pdf.dispose();</code>
<code>    }</code>
<code>}</code>

The code iterates through all pages of the PDF and adds text, an image, and a separator line to the header area of each page.

2. Insert Footer with Java

<code>import com.spire.pdf.PdfDocument;</code>
<code>import com.spire.pdf.PdfPageBase;</code>
<code>import com.spire.pdf.automaticfields.PdfCompositeField;</code>
<code>import com.spire.pdf.automaticfields.PdfPageCountField;</code>
<code>import com.spire.pdf.automaticfields.PdfPageNumberField;</code>
<code>import com.spire.pdf.graphics.*;</code>
<code>import java.awt.*;</code>
<code>import java.awt.geom.Dimension2D;</code>
<code>import java.awt.geom.Point2D;</code>
<code>public class PDFFooter {</code>
<code>    public static void main(String[] args) {</code>
<code>        PdfDocument pdf = new PdfDocument();</code>
<code>        pdf.loadFromFile("考核.pdf");</code>
<code>        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("宋体", Font.BOLD, 12), true);</code>
<code>        PdfBrush brush = PdfBrushes.getBlack();</code>
<code>        PdfPen pen = new PdfPen(PdfBrushes.getBlack(), 1.0f);</code>
<code>        PdfPageNumberField pageNumberField = new PdfPageNumberField();</code>
<code>        PdfPageCountField pageCountField = new PdfPageCountField();</code>
<code>        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "第{0}页/共{1}页", pageNumberField, pageCountField);</code>
<code>        Dimension2D fontSize = font.measureString(compositeField.getText());</code>
<code>        Dimension2D pageSize = pdf.getPages().get(0).getSize();</code>
<code>        compositeField.setLocation(new Point2D.Double((pageSize.getWidth() - fontSize.getWidth())/2, pageSize.getHeight() - 45));</code>
<code>        for (int i = 0; i < pdf.getPages().getCount(); i++) {</code>
<code>            PdfPageBase page = pdf.getPages().get(i);</code>
<code>            page.getCanvas().drawLine(pen, new Point(72, (int)(pageSize.getHeight() - 60)), new Point((int)pageSize.getWidth() - 72, (int)pageSize.getHeight() - 60));</code>
<code>            compositeField.draw(page.getCanvas());</code>
<code>        }</code>
<code>        pdf.saveToFile("PDF页脚.pdf");</code>
<code>        pdf.dispose();</code>
<code>    }</code>
<code>}</code>

The code adds a line and a composite field showing "Page X of Y" to the footer of each page.

Summary

Using the free Spire.PDF for Java library, you can draw custom elements such as text, images, lines, and automatic page fields onto the top or bottom of PDF pages without altering the original layout, thereby improving readability and professionalism.

JavaprogrammingPDFfooterheaderspire.pdf
Java Captain
Written by

Java Captain

Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.