Page events for headers and footers
Some examples for questions such as:
Click How to create a table with 2 rows that can be used as a footer?
- Click How to add HTML headers and footers to a page?
- Click How to generate a report with dynamic header in PDF using itextsharp?
tablefooter
JAVA
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package com.itextpdf.samples.sandbox.events;
import com.itextpdf.kernel.colors.ColorConstants;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Cell;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import java.io.File;
public class TableFooter {
public static final String DEST = "./target/sandbox/events/table_footer.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new TableFooter().manipulatePdf(DEST);
}
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc, PageSize.A4);
doc.setMargins(36, 36, 72, 36);
Table table = new Table(1).useAllAvailableWidth();
Cell cell = new Cell().add(new Paragraph("This is a test doc"));
cell.setBackgroundColor(ColorConstants.ORANGE);
table.addCell(cell);
cell = new Cell().add(new Paragraph("This is a copyright notice"));
cell.setBackgroundColor(ColorConstants.LIGHT_GRAY);
table.addCell(cell);
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new TableFooterEventHandler(table));
for (int i = 0; i < 150; i++) {
doc.add(new Paragraph("Hello World!"));
}
doc.add(new AreaBreak());
doc.add(new Paragraph("Hello World!"));
doc.add(new AreaBreak());
doc.add(new Paragraph("Hello World!"));
doc.close();
}
private static class TableFooterEventHandler implements IEventHandler {
private Table table;
public TableFooterEventHandler(Table table) {
this.table = table;
}
@Override
public void handleEvent(Event currentEvent) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
PdfDocument pdfDoc = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
new Canvas(canvas, new Rectangle(36, 20, page.getPageSize().getWidth() - 72, 50))
.add(table)
.close();
}
}
}
C#
C#
using System;
using System.IO;
using iText.Kernel.Colors;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
namespace iText.Samples.Sandbox.Events
{
public class TableFooter
{
public static readonly String DEST = "results/sandbox/events/table_footer.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new TableFooter().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc, PageSize.A4);
doc.SetMargins(36, 36, 72, 36);
Table table = new Table(1).UseAllAvailableWidth();
Cell cell = new Cell().Add(new Paragraph("This is a test doc"));
cell.SetBackgroundColor(ColorConstants.ORANGE);
table.AddCell(cell);
cell = new Cell().Add(new Paragraph("This is a copyright notice"));
cell.SetBackgroundColor(ColorConstants.LIGHT_GRAY);
table.AddCell(cell);
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new TableFooterEventHandler(table));
for (int i = 0; i < 150; i++)
{
doc.Add(new Paragraph("Hello World!"));
}
doc.Add(new AreaBreak());
doc.Add(new Paragraph("Hello World!"));
doc.Add(new AreaBreak());
doc.Add(new Paragraph("Hello World!"));
doc.Close();
}
private class TableFooterEventHandler : IEventHandler
{
private Table table;
public TableFooterEventHandler(Table table)
{
this.table = table;
}
public void HandleEvent(Event currentEvent)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
PdfCanvas canvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
new Canvas(canvas, new Rectangle(36, 20, page.GetPageSize().GetWidth() - 72, 50))
.Add(table)
.Close();
}
}
}
}
tableheader
JAVA
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package com.itextpdf.samples.sandbox.events;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.element.Table;
import com.itextpdf.layout.layout.LayoutArea;
import com.itextpdf.layout.layout.LayoutContext;
import com.itextpdf.layout.layout.LayoutResult;
import com.itextpdf.layout.renderer.DocumentRenderer;
import com.itextpdf.layout.renderer.TableRenderer;
import java.io.File;
public class TableHeader {
public static final String DEST = "./target/sandbox/events/table_header.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new TableHeader().manipulatePdf(DEST);
}
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
TableHeaderEventHandler handler = new TableHeaderEventHandler(doc);
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);
// Calculate top margin to be sure that the table will fit the margin.
float topMargin = 20 + handler.getTableHeight();
doc.setMargins(topMargin, 36, 36, 36);
for (int i = 0; i < 50; i++) {
doc.add(new Paragraph("Hello World!"));
}
doc.add(new AreaBreak());
doc.add(new Paragraph("Hello World!"));
doc.add(new AreaBreak());
doc.add(new Paragraph("Hello World!"));
doc.close();
}
private static class TableHeaderEventHandler implements IEventHandler {
private Table table;
private float tableHeight;
private Document doc;
public TableHeaderEventHandler(Document doc) {
this.doc = doc;
initTable();
TableRenderer renderer = (TableRenderer) table.createRendererSubTree();
renderer.setParent(new DocumentRenderer(doc));
// Simulate the positioning of the renderer to find out how much space the header table will occupy.
LayoutResult result = renderer.layout(new LayoutContext(new LayoutArea(0, PageSize.A4)));
tableHeight = result.getOccupiedArea().getBBox().getHeight();
}
@Override
public void handleEvent(Event currentEvent) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
PdfDocument pdfDoc = docEvent.getDocument();
PdfPage page = docEvent.getPage();
PdfCanvas canvas = new PdfCanvas(page.newContentStreamBefore(), page.getResources(), pdfDoc);
PageSize pageSize = pdfDoc.getDefaultPageSize();
float coordX = pageSize.getX() + doc.getLeftMargin();
float coordY = pageSize.getTop() - doc.getTopMargin();
float width = pageSize.getWidth() - doc.getRightMargin() - doc.getLeftMargin();
float height = getTableHeight();
Rectangle rect = new Rectangle(coordX, coordY, width, height);
new Canvas(canvas, rect)
.add(table)
.close();
}
public float getTableHeight() {
return tableHeight;
}
private void initTable()
{
table = new Table(1);
table.useAllAvailableWidth();
table.addCell("Header row 1");
table.addCell("Header row 2");
table.addCell("Header row 3");
}
}
}
C#
C#
using System;
using System.IO;
using iText.Kernel.Events;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Layout;
using iText.Layout.Renderer;
namespace iText.Samples.Sandbox.Events
{
public class TableHeader
{
public static readonly String DEST = "results/sandbox/events/table_header.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new TableHeader().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
TableHeaderEventHandler handler = new TableHeaderEventHandler(doc);
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, handler);
// Calculate top margin to be sure that the table will fit the margin.
float topMargin = 20 + handler.GetTableHeight();
doc.SetMargins(topMargin, 36, 36, 36);
for (int i = 0; i < 50; i++)
{
doc.Add(new Paragraph("Hello World!"));
}
doc.Add(new AreaBreak());
doc.Add(new Paragraph("Hello World!"));
doc.Add(new AreaBreak());
doc.Add(new Paragraph("Hello World!"));
doc.Close();
}
private class TableHeaderEventHandler : IEventHandler
{
private Table table;
private float tableHeight;
private Document doc;
public TableHeaderEventHandler(Document doc)
{
this.doc = doc;
InitTable();
TableRenderer renderer = (TableRenderer) table.CreateRendererSubTree();
renderer.SetParent(new DocumentRenderer(doc));
// Simulate the positioning of the renderer to find out how much space the header table will occupy.
LayoutResult result = renderer.Layout(new LayoutContext(new LayoutArea(0, PageSize.A4)));
tableHeight = result.GetOccupiedArea().GetBBox().GetHeight();
}
public void HandleEvent(Event currentEvent)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
PdfDocument pdfDoc = docEvent.GetDocument();
PdfPage page = docEvent.GetPage();
PdfCanvas canvas = new PdfCanvas(page.NewContentStreamBefore(), page.GetResources(), pdfDoc);
PageSize pageSize = pdfDoc.GetDefaultPageSize();
float coordX = pageSize.GetX() + doc.GetLeftMargin();
float coordY = pageSize.GetTop() - doc.GetTopMargin();
float width = pageSize.GetWidth() - doc.GetRightMargin() - doc.GetLeftMargin();
float height = GetTableHeight();
Rectangle rect = new Rectangle(coordX, coordY, width, height);
new Canvas(canvas, rect)
.Add(table)
.Close();
}
public float GetTableHeight()
{
return tableHeight;
}
private void InitTable()
{
table = new Table(1).UseAllAvailableWidth();
table.AddCell("Header row 1");
table.AddCell("Header row 2");
table.AddCell("Header row 3");
}
}
}
}
textfooter
JAVA
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package com.itextpdf.samples.sandbox.events;
import com.itextpdf.io.font.constants.StandardFonts;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.font.PdfFont;
import com.itextpdf.kernel.font.PdfFontFactory;
import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
public class TextFooter {
public static final String DEST = "./target/sandbox/events/text_footer.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new TextFooter().manipulatePdf(DEST);
}
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(doc));
for (int i = 0; i < 3; i++) {
doc.add(new Paragraph("Test " + (i + 1)));
if (i != 2) {
doc.add(new AreaBreak());
}
}
doc.close();
}
private static class TextFooterEventHandler implements IEventHandler {
protected Document doc;
public TextFooterEventHandler(Document doc) {
this.doc = doc;
}
@Override
public void handleEvent(Event currentEvent) {
PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
Rectangle pageSize = docEvent.getPage().getPageSize();
PdfFont font = null;
try {
font = PdfFontFactory.createFont(StandardFonts.HELVETICA_OBLIQUE);
} catch (IOException e) {
// Such an exception isn't expected to occur,
// because helvetica is one of standard fonts
System.err.println(e.getMessage());
}
float coordX = ((pageSize.getLeft() + doc.getLeftMargin())
+ (pageSize.getRight() - doc.getRightMargin())) / 2;
float headerY = pageSize.getTop() - doc.getTopMargin() + 10;
float footerY = doc.getBottomMargin();
Canvas canvas = new Canvas(docEvent.getPage(), pageSize);
canvas
// If the exception has been thrown, the font variable is not initialized.
// Therefore null will be set and iText will use the default font - Helvetica
.setFont(font)
.setFontSize(5)
.showTextAligned("this is a header", coordX, headerY, TextAlignment.CENTER)
.showTextAligned("this is a footer", coordX, footerY, TextAlignment.CENTER)
.close();
}
}
}
C#
C#
using System;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace iText.Samples.Sandbox.Events
{
public class TextFooter
{
public static readonly String DEST = "results/sandbox/events/text_footer.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new TextFooter().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, new TextFooterEventHandler(doc));
for (int i = 0; i < 3; i++)
{
doc.Add(new Paragraph("Test " + (i + 1)));
if (i != 2)
{
doc.Add(new AreaBreak());
}
}
doc.Close();
}
private class TextFooterEventHandler : IEventHandler
{
protected Document doc;
public TextFooterEventHandler(Document doc)
{
this.doc = doc;
}
public void HandleEvent(Event currentEvent)
{
PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
Rectangle pageSize = docEvent.GetPage().GetPageSize();
PdfFont font = null;
try {
font = PdfFontFactory.CreateFont(StandardFonts.HELVETICA_OBLIQUE);
} catch (IOException e)
{
// Such an exception isn't expected to occur,
// because helvetica is one of standard fonts
Console.Error.WriteLine(e.Message);
}
float coordX = ((pageSize.GetLeft() + doc.GetLeftMargin())
+ (pageSize.GetRight() - doc.GetRightMargin())) / 2;
float headerY = pageSize.GetTop() - doc.GetTopMargin() + 10;
float footerY = doc.GetBottomMargin();
Canvas canvas = new Canvas(docEvent.GetPage(), pageSize);
canvas
// If the exception has been thrown, the font variable is not initialized.
// Therefore null will be set and iText will use the default font - Helvetica
.SetFont(font)
.SetFontSize(5)
.ShowTextAligned("this is a header", coordX, headerY, TextAlignment.CENTER)
.ShowTextAligned("this is a footer", coordX, footerY, TextAlignment.CENTER)
.Close();
}
}
}
}
variableheader
JAVA
JAVA
/*
This file is part of the iText (R) project.
Copyright (c) 1998-2023 Apryse Group NV
Authors: Apryse Software.
For more information, please contact iText Software at this address:
sales@itextpdf.com
*/
package com.itextpdf.samples.sandbox.events;
import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Canvas;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.AreaBreak;
import com.itextpdf.layout.element.Paragraph;
import com.itextpdf.layout.properties.TextAlignment;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
public class VariableHeader {
public static final String DEST = "./target/sandbox/events/variable_header.pdf";
public static void main(String[] args) throws Exception {
File file = new File(DEST);
file.getParentFile().mkdirs();
new VariableHeader().manipulatePdf(DEST);
}
protected void manipulatePdf(String dest) throws Exception {
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
VariableHeaderEventHandler handler = new VariableHeaderEventHandler();
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);
for (int i = 2; i < 301; i++) {
List<Integer> factors = getFactors(i);
if (factors.size() == 1) {
doc.add(new Paragraph("This is a prime number!"));
}
for (int factor : factors) {
doc.add(new Paragraph("Factor: " + factor));
}
handler.setHeader(String.format("THE FACTORS OF %s", i));
if (300 != i) {
doc.add(new AreaBreak());
}
}
doc.close();
}
private static List<Integer> getFactors(int n) {
List<Integer> factors = new ArrayList<>();
for (int i = 2; i <= n; i++) {
while (n % i == 0) {
factors.add(i);
n /= i;
}
}
return factors;
}
private static class VariableHeaderEventHandler implements IEventHandler {
protected String header;
public void setHeader(String header) {
this.header = header;
}
@Override
public void handleEvent(Event currentEvent) {
PdfDocumentEvent documentEvent = (PdfDocumentEvent) currentEvent;
PdfPage page = documentEvent.getPage();
new Canvas(page, page.getPageSize())
.showTextAligned(header, 490, 806, TextAlignment.CENTER)
.close();
}
}
}
C#
C#
using System;
using System.Collections.Generic;
using System.IO;
using iText.IO.Font.Constants;
using iText.Kernel.Events;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;
namespace iText.Samples.Sandbox.Events
{
public class VariableHeader
{
public static readonly String DEST = "results/sandbox/events/variable_header.pdf";
public static void Main(String[] args)
{
FileInfo file = new FileInfo(DEST);
file.Directory.Create();
new VariableHeader().ManipulatePdf(DEST);
}
protected void ManipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));
Document doc = new Document(pdfDoc);
VariableHeaderEventHandler handler = new VariableHeaderEventHandler();
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, handler);
for (int i = 2; i < 301; i++)
{
List<int> factors = GetFactors(i);
if (factors.Count == 1)
{
doc.Add(new Paragraph("This is a prime number!"));
}
foreach (int factor in factors)
{
doc.Add(new Paragraph("Factor: " + factor));
}
handler.SetHeader(String.Format("THE FACTORS OF {0}", i));
if (300 != i)
{
doc.Add(new AreaBreak());
}
}
doc.Close();
}
private static List<int> GetFactors(int n)
{
List<int> factors = new List<int>();
for (int i = 2; i <= n; i++)
{
while (n % i == 0)
{
factors.Add(i);
n /= i;
}
}
return factors;
}
private class VariableHeaderEventHandler : IEventHandler
{
protected String header;
public void SetHeader(String header)
{
this.header = header;
}
public void HandleEvent(Event currentEvent)
{
PdfDocumentEvent documentEvent = (PdfDocumentEvent) currentEvent;
PdfPage page = documentEvent.GetPage();
new Canvas(page, page.GetPageSize())
.ShowTextAligned(header, 490, 806, TextAlignment.CENTER)
.Close();
}
}
}
}