I am trying to follow the example given in https://developers.itextpdf.com/examples/page-events/clone-page-events-headers-and-footers#2656-variableheader.java to create a PDF document with variable header. But the events are not fired correctly. Here is the code I have tested with -
class Program
{
public static String DEST = "test.pdf";
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
manipulatePdf(DEST);
}
public 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;
}
protected static void manipulatePdf(String dest)
{
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(DEST));
Document doc = new Document(pdfDoc, PageSize.A4, true);
VariableHeaderEventHandler handler = new VariableHeaderEventHandler();
pdfDoc.AddEventHandler(PdfDocumentEvent.END_PAGE, handler);
List<int> factors;
for (int i = 2; i < 4; i++)
{
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();
}
protected class VariableHeaderEventHandler : IEventHandler
{
protected String header;
public void setHeader(String header)
{
this.header = header;
}
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)
{
}
}
}
}
If I run this code, all pages show header as "THE FACTORS OF 3". But they should show "THE FACTORS OF 2" for first page "THE FACTORS OF 3" for second page and "THE FACTORS OF 4" for third page. I am not sure how to fix it. Any suggestions?