How to add Header and footer to my PDF using Itext in java

 HeaderFooter event = new HeaderFooter();
  writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));
  writer.setPageEvent(event);

document itxt

ejemplo example of PDF


Footer Header utils:

import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter;

public class HeaderFooterPageEvent extends PdfPageEventHelper {

    public void onStartPage(PdfWriter writer, Document document) {
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Top Left"), 30, 800, 0);
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Top Right"), 550, 800, 0);
    }

    public void onEndPage(PdfWriter writer, Document document) {
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("http://www.xxxx-your_example.com/"), 110, 30, 0);
        ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("page " + document.getPageNumber()), 550, 30, 0);
    }

}

Use HeaderFooterPageEvent:

ByteArrayOutputStream bos = new ByteArrayOutputStream();
Document document = new Document(PageSize.A4, 20, 20, 50, 25);
PdfWriter writer = PdfWriter.getInstance(document, baos);
HeaderFooterPageEvent event = new HeaderFooterPageEvent();
writer.setPageEvent(event);

EDIT (add image sample):

public void onStartPage(PdfWriter writer, Document document) {
    String img = APPLICATION_SERVER_ROOT_PATH + File.separator + "assets" + File.separator + "images" + File.separator + "logo-tp-white.png";
    Image image;
    try {
        image = Image.getInstance(img);
        image.setAlignment(Element.ALIGN_RIGHT);
        image.setAbsolutePosition(20, 790);
        image.scalePercent(7.5f, 7.5f);
        writer.getDirectContent().addImage(image, true);
    } catch (IOException | DocumentException e) {
        log.error("L'image logo-tp-50x50.png a provoqué une erreur.", e);
    }

    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(""), 30, 800, 0);
    ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase(Constants.GLOBAL_HOST + " pour réussir votre prochain concours."), 400, 800, 0);
}

Tags:

Java

Itext