Dec
6
2011

Using iTextSharp with asp.net to add header in pdf file

Introduction

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

Background

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 asp.net 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);
 writer.Write(File.ReadAllText(@"E:\MyFolder\filename.txt"));
 StringReader sr = new StringReader(sw.ToString());
 
 //Parse into IElement
 List<IElement> elements =HTMLWorker.ParseToList(sr,null);       
 //Open the Document
 itextDoc.Open();
 //loop through all elements
 foreach (IElement el in elements)
 {
     //add individual element to Document
     itextDoc.Add(el);
 }                 
 //Close the document
 itextDoc.Close();
 //set the Response object
 Response.ContentType = "application/pdf";
 Response.AddHeader("content-disposition", "attachment;filename=TestPage.pdf");
 Response.End();

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;
        pdfCell1.Border=0;                
        pdfCell2.Border=0;
        pdfCell3.Border=0;
        //add all three cells into PdfTable
        pdfTab.AddCell(pdfCell1);
        pdfTab.AddCell(pdfCell2);
        pdfTab.AddCell(pdfCell3);
        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);
        pdfContent.Stroke();        
    }
}

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 :)

Comments (3) -

brokoly

Was not mentioned that stubs should be written for the followings:
public void OnChapter(PdfWriter writer, Document document, float paragraphPosition, Paragraph title) { }
    public void OnChapterEnd(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnCloseDocument(PdfWriter writer, Document document) { }
    public void OnGenericTag(PdfWriter writer, Document document, Rectangle rect, string text) { }
    public void OnOpenDocument(PdfWriter writer, Document document) { }
    public void OnParagraph(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnParagraphEnd(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnSection(PdfWriter writer, Document document, float paragraphPosition, int depth, Paragraph title) { }
    public void OnSectionEnd(PdfWriter writer, Document document, float paragraphPosition) { }
    public void OnStartPage(PdfWriter writer, Document document) { }

Swati

Thanks for such a simple and helpful information! Keep writing!

Aniesh

Can you please send the full code for this articale.

Thanks
anish

Pingbacks and trackbacks (1)+

About Me

You are visiting personal website of Kedar (KK)

Please go here to know more about me

Disclaimer

The opinions expressed here represent my own and not those of my past or present employers.

The concept/code provided on this site may not work as described. If you are using any code provided on this site. Then, please test it thoroughly. I shall not be responsible for any issues arising in the code. 

Month List