Header and Footer

Header and Footer (2)

This article demonstrates how to add page numbers to an existing PDF document at the footer space using Spire.PDF for Java. You can determine where to insert page numbers according to your own requirement.

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.Rectangle2D;

public class AddPageNumbers {

    public static void main(String[] args) {

        //load a PDF document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pdf");

        //create a true type font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN, 10));

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

        //declare a float variable
        float y = (float) pageSize.getHeight() - 72;

        //loop through the pages
        for (int i = 0; i < doc.getPages().getCount(); i++) {

            //initialize PdfPageNumberField instance
            PdfPageNumberField number = new PdfPageNumberField();

            //initialize PdfPageCountField instance
            PdfPageCountField count = new PdfPageCountField();

            //create PdfCompositeField instance
            PdfCompositeField compositeField = new PdfCompositeField(font, PdfBrushes.getBlack(), "Page {0} of {1}", number, count);

            //set the text alignment within the composite field
            compositeField.setStringFormat(new PdfStringFormat(PdfTextAlignment.Right, PdfVerticalAlignment.Top));

            //get the text size
            Dimension2D textSize = font.measureString(compositeField.getText());

            //set the position and size of composite field
            compositeField.setBounds(new Rectangle2D.Float((float) pageSize.getWidth() - (float) textSize.getWidth() - 80, y, (float) textSize.getWidth(), (float) textSize.getHeight()));

            //draw composite filed on PDF page
            compositeField.draw(doc.getPages().get(i).getCanvas());
        }

        //save to another file
        doc.saveToFile("output/AddPageNumbers.pdf");
    }
}

Add Page Numbers to Exsiting PDF Documents in Java

Tuesday, 27 November 2018 09:47

Add header and footer to PDF in Java

Written by support iceblue

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