News Category

Header and Footer

Header and Footer (4)

A footer is text or other content located at the bottom of a page, usually including page numbers, dates, authors, and other information. Footers contribute to the overall professional appearance of the document by maintaining a consistent layout across all pages. By incorporating footers, PDF documents become more professional, user-friendly, and compliant with legal requirements. This article demonstrates how to add a footer to an existing PDF document in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.4.4</version>
    </dependency>
</dependencies>
    

Background Knowledge

When using Spire.PDF for Java to process an existing PDF document, the origin of the coordinate system is located at the top left corner of the page, with the x-axis extending to the right and the y-axis extending downward. Adding a footer to a page means adding content, such as text, images, automatic fields and shapes, to a specified location in the bottom blank area of the page.

Java: Add a Footer to an Existing PDF Document

If the blank area is not large enough to accommodate the content you want to add, you can consider increasing the PDF page margins.

Add a Footer to an Existing PDF Document in Java

Spire.PDF for Java offers the PdfCanvas.drawString() method, PdfCanvas.drawImage() method, PdfCanvas.drawLine() method and its similar methods, allowing users to draw text, images and shapes on a PDF page at the specified location. To add dynamic data to the footer, such as page numbers, sections, dates, you need to use the automatic fields. Spire.PDF for Java provides the PdfPageNumberField class, PdfPageCountField calss, PdfSectionNumberField class etc. to achieve the addition of dynamic information.

The following are the steps to add a footer consisting of an image and page number to a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Load an image using PdfImage.fromFile() method.
  • Draw the image on the bottom blank area of a page using PdfPageBase.getCanvas().drawImage() method.
  • Create a PdfPageNumberField object, a PdfPageCountField object, and combine them in a PdfCompositefield object to return the string "Page X of Y".
  • Draw page number on the bottom blank area of a page using PdfCompositeField.draw() method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
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.PdfBrush;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfImage;
import com.spire.pdf.graphics.PdfTrueTypeFont;

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

public class AddFooterToPdf {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\sample.pdf");

        //Load an image
        PdfImage footerImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\bg.jpg");

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

        //Create a brush
        PdfBrush brush = PdfBrushes.getWhite();

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

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

        //Create a composite field to combine page count field and page number field in a single string
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "Page {0} of {1}", pageNumberField, pageCountField);

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

        //Get the page size
        Dimension2D pageSize = doc.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 the pages in the document
        for (int i = 0; i < doc.getPages().getCount(); i++)
        {
            //Get a specific page
            PdfPageBase page = doc.getPages().get(i);

            //Draw the image on the bottom blank area
            page.getCanvas().drawImage(footerImage, 55, pageSize.getHeight() - 65, pageSize.getWidth() - 110, 50);

            //Draw the composite field on the bottom blank area
            compositeField.draw(page.getCanvas());
        }

        //Save to file
        doc.saveToFile("output/AddFooter.pdf");
        doc.dispose();
    }
}

Java: Add a Footer to an Existing PDF Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Adding a header to a PDF document is a useful way to display important information such as the document title, author, and page numbers. A header is a section of text or graphics that appears at the top of each page in a document and can be customized according to your needs. This feature is particularly helpful when creating reports, contracts, or other professional documents that require a consistent format. In this article, you will learn how to add a header to an existing PDF document in Java using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>10.4.4</version>
    </dependency>
</dependencies>
    

Background Knowledge

When an existing PDF document is manipulated by Spire.PDF for Java, the origin of the coordinate system is located at the top left corner of the page, with the x-axis extending to the right and the y-axis extending downward. Adding a header to a page means adding content, such as text, images, automatic fields and shapes, to a specified location in the upper blank area of the page.

Java: Add a Header to an Existing PDF Document

If the blank area is not large enough to accommodate the content you want to add, you can consider increasing the PDF page margins.

Add a Header to an Existing PDF Document in Java

Spire.PDF for Java allows users to draw text, images and shapes on a PDF page using PdfCanvas.drawString() method, PdfCanvas.drawImage() method, PdfCanvas.drawLine() method and other similar methods. To add dynamic information to the header, such as page numbers, sections, dates, you need to resort to automatic fields. Spire.PDF for Java provides the PdfPageNumberField class, PdfSectionNumberField class, PdfCreationDateField class, etc. to achieve the dynamic addition of these data.

The following are the steps to add a header consisting of text, an image, a date, and a line to a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF document using PdfDocument.loadFromFile() method.
  • Create font, pen and brush objects that will be used to draw text or shapes.
  • Draw text on the top blank area of a page using PdfPageBase.getCanvas().drawString() method.
  • Draw a line on the top blank area of a page using PdfPageBase.getCanvas().drawLine() method.
  • Load an image using PdfImage.fromFile() method.
  • Draw the image on the top blank area of a page using PdfPageBase.getCanvas().drawImage() method.
  • Create a PdfCreationDateField object that reflects the creation time of the document.
  • Draw the creation time on the top blank area of a page using PdfCreationDateField.draw() method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
  • Java
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfCreationDateField;
import com.spire.pdf.graphics.*;

import java.awt.*;

public class AddHeaderToPdf {

    public static void main(String[] args) {

        //Create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Load a PDF file
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\TargetMarket.pdf");

        //Load an image for the header
        PdfImage headerImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\logo.png");

        //Get image width in pixel
        float width = headerImage.getWidth();

        //Convert pixel to point
        PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
        float pointWidth = unitCvtr.convertUnits(width, PdfGraphicsUnit.Pixel, PdfGraphicsUnit.Point);

        //Specify text for the header
        String headerText = "E-iceblue Tech\nwww.e-iceblue.com";

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

        //Create a brush
        PdfBrush brush = PdfBrushes.getPurple();

        //Create a pen
        PdfPen pen = new PdfPen(brush, 1.0f);

        //Create a creation date field
        PdfCreationDateField creationDateField = new PdfCreationDateField(font, brush);
        creationDateField.setDateFormatString("yyyy-MM-dd");

        //Create a composite field to combine static string and date field
        PdfCompositeField compositeField = new PdfCompositeField(font, brush, "creation time: {0}", creationDateField);
        compositeField.setLocation(new Point(55, 48));

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

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

            //Draw text on the top blank area
            page.getCanvas().drawString(headerText, font, brush, 55, 20);

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

            //Draw the composite field on the top blank area
            compositeField.draw(page.getCanvas());
        }

        //Save to file
        doc.saveToFile("output/AddHeader.pdf");
        doc.dispose();
    }
}

Java: Add a Header to an Existing PDF Document

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

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

This article demonstrates how to use Spire. PDF for Java to add header and footer when creating new PDF document in Java applications.

Spire.PDF has a class named PdfPageTemplateElement, which represents a page template element that can be used as header, footer, watermark or stamp. The template can contain text, image as well as dynamic fields like PdfPageCountField, PdfPageNumberField, etc. We use text string for the header and dynamic fields for the footer in the following example.

import java.awt.*;
import java.awt.geom.Dimension2D;
import com.spire.pdf.*;
import com.spire.pdf.automaticfields.PdfAutomaticField;
import com.spire.pdf.automaticfields.PdfCompositeField;
import com.spire.pdf.automaticfields.PdfPageCountField;
import com.spire.pdf.automaticfields.PdfPageNumberField;
import com.spire.pdf.graphics.*;

public class PDFHeaderFooter {
    public static void main(String[] args) throws Exception {

        //create a PdfDocument object
        PdfDocument doc = new PdfDocument();

        //Set margins
        PdfMargins margin = new PdfMargins(60,60,40,40);

        //Call the method addHeaderAndFooter() to add header and footer
        addHeaderAndFooter(doc, PdfPageSize.A4, margin);

        //Add two pages to the PDF document and draw string to it.
        PdfPageBase page1 = doc.getPages().add();
        PdfPageBase page2 = doc.getPages().add();
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN, 14));
        String text1 = "Demo of Spire.PDF";
        String text2 = "How to add header and footer to PDF in JAVA";
        page1.getCanvas().drawString(text1, font, PdfBrushes.getBlack(),0,0);
        page2.getCanvas().drawString(text2, font, PdfBrushes.getBlack(),0,0);
      
        //Save the document
        doc.saveToFile("output/headerFooter.pdf");
        doc.close();

    }
static void addHeaderAndFooter(PdfDocument doc, Dimension2D pageSize, PdfMargins margin) {

      PdfPageTemplateElement header = new PdfPageTemplateElement(margin.getLeft(), pageSize.getHeight());
      doc.getTemplate().setLeft(header);

      PdfPageTemplateElement topSpace = new PdfPageTemplateElement(pageSize.getWidth(), margin.getTop());
      topSpace.setForeground(true);
      doc.getTemplate().setTop(topSpace);

      //Draw header label
      PdfTrueTypeFont font= new PdfTrueTypeFont(new Font("Arial",Font.PLAIN,12));

      PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);
      String label = "E-iceblue Co.,Ltd";
      Dimension2D dimension2D = new Dimension();
      dimension2D.setSize(font.measureString(label, format));
      float y = topSpace.getHeight() - font.getHeight() - 1;
      PdfPen pen = new PdfPen(new PdfRGBColor(Color.black), 0.75f);
      topSpace.getGraphics().setTransparency(0.5f);
      topSpace.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
      y = y - 1 - (float) dimension2D.getHeight();
      topSpace.getGraphics().drawString(label, font, PdfBrushes.getBlack(), margin.getLeft(), y, format);

      PdfPageTemplateElement rightSpace = new PdfPageTemplateElement(margin.getRight(), pageSize.getHeight());
      doc.getTemplate().setRight(rightSpace);


      //Draw dynamic fields as footer
      PdfPageTemplateElement footer = new PdfPageTemplateElement(pageSize.getWidth(), margin.getBottom());
      footer.setForeground(true);
      doc.getTemplate().setBottom(footer);

      y = font.getHeight() + 1;
      footer.getGraphics().setTransparency(0.5f);
      footer.getGraphics().drawLine(pen, margin.getLeft(), y, pageSize.getWidth() - margin.getRight(), y);
      y = y + 1;
      PdfPageNumberField pageNumber = new PdfPageNumberField();
      PdfPageCountField pageCount = new PdfPageCountField();
      PdfCompositeField pageNumberLabel = new PdfCompositeField();
      pageNumberLabel.setAutomaticFields(new PdfAutomaticField[]{pageNumber, pageCount});
      pageNumberLabel.setBrush(PdfBrushes.getBlack());
      pageNumberLabel.setFont(font);
      format = new PdfStringFormat(PdfTextAlignment.Right);
      pageNumberLabel.setStringFormat(format);
      pageNumberLabel.setText("page {0} of {1}");
      pageNumberLabel.setBounds(footer.getBounds());
      pageNumberLabel.draw(footer.getGraphics(), - margin.getLeft(), y);
  }

}

Effective screenshot after adding header and footer to the new PDF document in JAVA application:

Add header and footer to PDF in JAVA