Java add multiple headers to PDF

This article demonstrates how to use Spire. PDF for Java to add multiple headers to an existing PDF document in Java applications. The multiple headers on PDF means that different page has different header on the same PDF document.

import com.spire.pdf.*;
import com.spire.pdf.graphics.*;
import java.awt.*;
import java.awt.geom.*;

public class addDifferentHeaders {
    public static void main(String[] args) {
        String output = "output/addDifferentHeaders.pdf";

        //load the sample PDF document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("Sample.pdf");
        String header1 = "Add header by Spire.PDF";
        String header2 = "Different header";

        //define style
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial",  Font.BOLD,12));
        PdfBrush brush= PdfBrushes.getBlue();
        Rectangle2D rect = new Rectangle2D.Float();
        Dimension2D dimension2D = new Dimension();
        dimension2D.setSize(doc.getPageSettings().getSize().getWidth(),50f);
        rect.setFrame(new Point2D.Float(0, 20), dimension2D);
        PdfStringFormat format=new PdfStringFormat();
        format.setAlignment(PdfTextAlignment.Center);
        //draw header string for the first page
        doc.getPages().get(0).getCanvas().drawString(header1,font,brush,rect,format);

        //draw header string for the second page
        format.setAlignment( PdfTextAlignment.Left);
        doc.getPages().get(1).getCanvas().drawString(header2, font, brush, rect, format);

        //save the document
        doc.saveToFile(output, FileFormat.PDF);
    }
}

Java add multiple headers to PDF