Note: If you have not gone through my previous post iTextSharp–Add header/footer to PDF, please go through it.
Most of the time, we’ll require to print the dynamic value in the header. i.e. Company Name etc. You can create properties in the PageEvent class that inherits the PdfPageEventHelper class.
public class ITextEvents : PdfPageEventHelper
{
#region Fields
private string _header;
#endregion
#region Properties
public string Header
{
get { return _header; }
set { _header = value; }
}
#endregion
public override void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
{
base.OnEndPage(writer, document);
iTextSharp.text.Font baseFontNormal = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
Phrase p1Header = new Phrase(Header, baseFontNormal);
//Other Code here that adds header. Refer previous article
}
}
Now add the below code to your code from where you’re generating PDF:
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDoc, msReport);
Common.ITextEvents objTextEvents = new Common.ITextEvents();
objTextEvents.Header = "Test Header";
pdfWriter.PageEvent = objTextEvents;
I hope it helps!
Leave a Reply