Tuesday, August 18, 2015

iTextSharp: Add dynamic header

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 dynamic value in header. i.e. Company Name etc.

You can create properties in PageEvent class that inherits PdfPageEventHelper class.

public class ITextEvents : PdfPageEventHelper

   #region Fields
        private string _header;

        #region Properties
        public string Header
            get { return _header; }
            set { _header = value; }

 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 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;

iTextSharp Dynamic Header

I hope it helps!