How to generate a report with dynamic header in PDF using iText 7?
I'm generating a PDF report with iTextSharp, the header of the report has the information of the customer. In the body of the report contains a list of customer transactions. My doubt is: How to generate a header dynamically for each client?
I need an example to generate a header dynamically to the report. Every new page Header need to have the data that client when changing client header should contain information on the new client.
Posted on StackOverflow on Feb 7, 2014 by user3154466
I've written a small example in Java which you can easily adapt to C# as iText and iText for C# share more or less the same syntax.
The example is called VariableHeader and these are the most interesting snippets:
First I create a custom implementation of the IEventHandler
interface and override the handleEvent()
method:
protected class VariableHeaderEventHandler implements IEventHandler {
protected String header;
public void setHeader(String header) {
this.header = header;
}
@Override
public void handleEvent(Event event) {
PdfDocumentEvent documentEvent = (PdfDocumentEvent) event;
try {
new PdfCanvas(documentEvent.getPage())
.beginText()
.setFontAndSize(PdfFontFactory.createFont(StandardFonts.HELVETICA), 12)
.moveText(450, 806)
.showText(header)
.endText()
.stroke();
} catch (IOException e) {
e.printStackTrace();
}
}
}
As you can see, the text of the header is stored in a variable that can be changed using the setHeader()
method we created.
The event is declared to the PdfDocument
like this:
VariableHeaderEventHandler handler = new VariableHeaderEventHandler();
pdfDoc.addEventHandler(PdfDocumentEvent.END_PAGE, handler);
I change the header before invoking the AreaBreak()
method:
handler.setHeader(String.format("THE FACTORS OF %s", i));
if (300 != i) {
doc.add(new AreaBreak());
}
In my simple example, I generate a document that lists the factors of all the numbers from 2 to 300: variable_header.pdf. The header of each page says "THE FACTORS OF X" where X is the number of which the factors are shown on that page.
You can easily adapt this to show different customer names instead of numbers.
Click this link if you want to see how to answer this question in iText 5.