Yet Another Tech Blog

Using iTextSharp with to add header in pdf file


I recently posted an article about using iTextSharp to generate pdf document from different source text. In this short post, I am going to explain how can we add header in the generated PDF document. I assume you know about basics of using iTextSharp. If you are not, I strongly recommend reading my last post here


When generating PDF document, its often desirable that some specific header is included in the generated file. It could be to mention page number or some message or even some logo. We will see how to do that.

Article Body

We have already used iTextSharp dll in project in my last post. We had used this code to generate the PDF file by using a .txt file as a source

 Document itextDoc = new Document();
 PdfWriter pdfDoc = PdfWriter.GetInstance(itextDoc,Response.OutputStream);

 StringWriter sw = new StringWriter();
 HtmlTextWriter writer = new HtmlTextWriter(sw);
 StringReader sr = new StringReader(sw.ToString());
 //Parse into IElement
 List<IElement> elements =HTMLWorker.ParseToList(sr,null);       
 //Open the Document
 //loop through all elements
 foreach (IElement el in elements)
     //add individual element to Document
 //Close the document
 //set the Response object
 Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");

This is all fine. But this will create normal PDF file without any header. To include headers in all pages, We have to use PDFWriter PageEvents. To add PageEvent listner, a class has to be created which would implement IPdfPageEvent

For the purpose of adding header, we will write implementation for only 2 methods OnEndPage and OnOpenDocument. Enough theory! Lets see the code details

I have tried to code in much detail so it is easy to understand. As the iTextSharp is derived from iText Java library, you can read details of each class, their methods and purpose in Java documentation here

public class itextEvents : IPdfPageEvent

    //Create object of PdfContentByte
    PdfContentByte pdfContent;
    public void OnEndPage(iTextSharp.text.pdf.PdfWriter writer, iTextSharp.text.Document document)
        //We are going to add two strings in header. Create separate Phrase object with font setting and string to be included
        Phrase p1Header = new Phrase("BlueLemonCode generated page", FontFactory.GetFont("verdana",8));
        Phrase p2Header = new Phrase("confidential", FontFactory.GetFont("verdana",8));
        //create iTextSharp.text Image object using local image path
        iTextSharp.text.Image imgPDF = iTextSharp.text.Image.GetInstance(HttpRuntime.AppDomainAppPath + "\\images\\bluelemoncode.jpg");

        //Create PdfTable object
        PdfPTable pdfTab = new PdfPTable(3);
        //We will have to create separate cells to include image logo and 2 separate strings
        PdfPCell pdfCell1 = new PdfPCell(imgPDF);
        PdfPCell pdfCell2 = new PdfPCell(p1Header);
        PdfPCell pdfCell3 = new PdfPCell(p2Header);
        //set the alignment of all three cells and set border to 0
        pdfCell1.HorizontalAlignment = Element.ALIGN_LEFT;
        pdfCell2.HorizontalAlignment = Element.ALIGN_LEFT;
        pdfCell3.HorizontalAlignment = Element.ALIGN_RIGHT;
        //add all three cells into PdfTable
        pdfTab.TotalWidth = document.PageSize.Width - 20;
        //call WriteSelectedRows of PdfTable. This writes rows from PdfWriter in PdfTable
        //first param is start row. -1 indicates there is no end row and all the rows to be included to write
        //Third and fourth param is x and y position to start writing
        pdfTab.WriteSelectedRows(0, -1, 10, document.PageSize.Height - 15, writer.DirectContent);
        //set pdfContent value
        pdfContent = writer.DirectContent;
        //Move the pointer and draw line to separate header section from rest of page
        pdfContent.MoveTo(30, document.PageSize.Height - 35);
        pdfContent.LineTo(document.PageSize.Width - 40, document.PageSize.Height - 35);

as we are implementing interface IPdfPageEvent here, we will have to provide at least empty implementation of all the methods of IPdfPageEvent (which i have avoided posting here for clean code)

Finally, set the PageEvent of PdfWriter where we had created object of PdfWriter. So, the code becomes

Document itextDoc = new Document();
PdfWriter pdfDoc = PdfWriter.GetInstance(itextDoc,Response.OutputStream);
pdfDoc.PageEvent = new itextEvents();

I am using some random text file to generate PDF file and below is the file created by using above code. As you can see, the header contains image logo at extreme right, different text at middle and right of header. The header also has a line drawn at the bottom.


Note that the formatting of text inside generated PDF filecan be manipulated by implementing other methods of PageEvent like OnParagraph, OnSection. Also, we can include a watermark in all pages of of generated. We will leave some of these other features for next time.

Meanwhile, comments are welcome :)