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

Comments (48) -

  • brokoly

    5/21/2012 8:14:35 PM |

    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

    12/19/2012 1:07:51 PM |

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

  • Aniesh

    5/1/2013 7:39:14 PM |

    Can you please send the full code for this articale.


  • @

    6/24/2014 5:07:59 AM |

    Excellent blog here! Also your website loads up very fast! What web host are you using? Can I get your affiliate link to your host? I wish my web site loaded up as fast as yours lol

    Feel free to surf to my web-site -  @ -

  • @

    6/24/2014 5:09:37 AM |

    I visited several sites except the audio feature for audio songs present at this web page is actually superb.

    my web site -  @ -

  • @

    6/24/2014 5:10:52 AM |

    Thanks for finally writing about > BlueLemonCode.Com | Using iTextSharp with to add header in pdf file @</a>

  • @

    6/24/2014 5:12:11 AM |

    fantastic submit, very informative. I ponder why the opposite specialists of this sector do not understand this. You should continue your writing. I'm sure, you've a huge readers' base already!

    Also visit my web-site ::  @ -

  • @

    6/24/2014 5:16:12 AM |

    If you want to obtain much from this post then you have to apply such strategies to your won website.

    Feel free to surf to my blog ::  @ -

  • @

    6/24/2014 5:19:54 AM |

    Very soon this site will be famous amid all blogging visitors, due to it's pleasant articles

    My web-site  @ -

  • @

    6/24/2014 6:33:13 AM |

    This article offers clear idea in support of the new viewers of blogging, that truly how to do blogging and site-building.

    Here is my page  @ -

  • @

    6/24/2014 7:19:52 AM |

    Its like you read my mind! You appear to know a lot about this, like you wrote the book in it or something. I think that you could do with a few pics to drive the message home a bit, but other than that, this is fantastic blog. An excellent read. I will definitely be back.

    Review my page:  @ -

  • @

    6/24/2014 7:22:25 AM |

    I read this post completely regarding the resemblance of newest and previous technologies, it's awesome article.

    Here is my webpage  @ -

  • @

    6/24/2014 7:30:47 AM |

    Hi! I could have sworn I've been to this website before but after browsing through some of the post I realized it's new to me. Nonetheless, I'm definitely happy I found it and I'll be book-marking and checking back frequently!

    my blog ::  @ -

  • @

    6/24/2014 7:35:39 AM |

    Please let me know if you're looking for a author for your blog. You have some really great posts and I think I would be a good asset. If you ever want to take some of the load off, I'd love to write some articles for your blog in exchange for a link back to mine. Please blast me an e-mail if interested. Cheers!

    Also visit my web blog;  @ -

  • @

    6/24/2014 7:36:25 AM |

    Valuable info. Fortunate me I discovered your site by accident, and I am surprised why this coincidence didn't took place earlier! I bookmarked it.

    Also visit my weblog:  @ -

  • @

    6/24/2014 7:57:25 AM |

    Just wish to say your article is as astonishing. The clearness on your publish is just nice and that i could suppose you're a professional in this subject. Well along with your permission allow me to clutch your feed to stay up to date with coming near near post. Thanks 1,000,000 and please keep up the enjoyable work.

    Here is my web site  @ -

  • @

    6/24/2014 8:00:04 AM |

    I am really impressed with your writing skills and also with the layout on your weblog. Is this a paid theme or did you customize it yourself? Anyway keep up the excellent quality writing, it is rare to see a great blog like this one these days.

    Feel free to surf to my blog post;  @ -

  • @

    6/24/2014 8:00:15 AM |

    I have been browsing online more than 4 hours today, yet I never found any interesting article like yours. It is pretty worth enough for me. Personally, if all website owners and bloggers made good content as you did, the net will be much more useful than ever before.

    Also visit my web-site:  @ -

  • @

    6/24/2014 8:03:02 AM |

    It's a pity you don't have a donate button! I'd definitely donate to this outstanding blog! I suppose for now i'll settle for book-marking and adding your RSS feed to my Google account. I look forward to brand new updates and will talk about this website with my Facebook group. Chat soon!

    my web site ::  @ -

  • @

    6/24/2014 8:24:39 AM |

    I am actually thankful to the holder of this site who has shared this fantastic article at at this place.

    Review my website;  @ -

  • @

    6/24/2014 8:26:23 AM |

    Heya i am for the first time here. I found this board and I find It really useful & it helped me out much. I hope to give something back and help others like you aided me.

    Stop by my webpage  @ -

  • @

    6/24/2014 8:27:03 AM |

    Please let me know if you're looking for a article writer for your blog. You have some really good articles and I feel I would be a good asset. If you ever want to take some of the load off, I'd love to write some articles for your blog in exchange for a link back to mine. Please shoot me an e-mail if interested. Kudos!

    My webpage:  @ -

  • @

    6/24/2014 8:28:01 AM |

    I am truly thankful to the owner of this site who has shared this wonderful post at here.

    Also visit my page -  @ -

  • @

    6/24/2014 8:32:11 AM |

    My brother suggested I would possibly like this blog. He was once entirely right. This put up actually made my day. You cann't consider just how so much time I had spent for this info! Thank you!

    my web page ::  @ -

  • @

    6/24/2014 8:40:49 AM |

    Fantastic beat ! I wish to apprentice even as you amend your web site, how could i subscribe for a blog web site? The account helped me a applicable deal. I were tiny bit acquainted of this your broadcast provided vivid transparent concept

    Feel free to surf to my blog -  @ -

  • @

    6/24/2014 8:43:35 AM |

    It's going to be finish of mine day, however before end I am reading this wonderful piece of writing to improve my know-how.

    My homepage:  @ -

  • @

    6/24/2014 8:44:11 AM |

    Appreciating the hard work you put into your blog and detailed information you offer. It's good to come across a blog every once in a while that isn't the same unwanted rehashed material. Excellent read! I've saved your site and I'm adding your RSS feeds to my Google account.

    Feel free to visit my web blog;  @ -

  • @

    6/24/2014 8:48:28 AM |

    I was recommended this blog by my cousin. I am not sure whether this post is written by him as nobody else know such detailed about my difficulty. You're amazing! Thanks!

    Also visit my blog -  @ -

  • @

    6/24/2014 8:53:46 AM |

    Superb, what a weblog it is! This blog presents helpful data to us, keep it up.

    Also visit my website ...  @ -

  • @

    6/24/2014 8:56:30 AM |

    Oh my goodness! Impressive article dude! Thank you so much, However I am going through issues with your RSS. I don't understand why I cannot join it. Is there anybody getting the same RSS issues? Anybody who knows the answer can you kindly respond? Thanks!!

    Here is my web site;  @ -

  • @

    6/24/2014 8:56:42 AM |

    Howdy, i read your blog occasionally and i own a similar one and i was just curious if you get a lot of spam remarks? If so how do you prevent it, any plugin or anything you can advise? I get so much lately it's driving me insane so any assistance is very much appreciated.

    my page ...  @ -

  • @

    6/24/2014 8:56:51 AM |

    When someone writes an paragraph he/she retains the idea of a user in his/her brain that how a user can understand it. Thus that's why this post is outstdanding. Thanks!

    my blog  @ -

  • @

    6/24/2014 9:00:48 AM |

    Hi! I'm at work browsing your blog from my new iphone! Just wanted to say I love reading your blog and look forward to all your posts! Keep up the superb work!

    my web blog ...  @ -

  • Latanya

    6/24/2014 9:01:16 AM |

    It's very simple to find out any matter on net as compared to textbooks, as I found this article at this website.

    Here is my homepage - @ ( Latanya - )

  • @

    6/24/2014 9:02:27 AM |

    Good post. I learn something new and challenging on websites I stumbleupon every day. It will always be helpful to read through content from other writers and use a little something from their web sites.

    Check out my web blog ...  @ -

  • @

    6/24/2014 9:04:08 AM |

    Hiya! Quick question that's entirely off topic. Do you know how to make your site mobile friendly? My website looks weird when browsing from my iphone4. I'm trying to find a template or plugin that might be able to fix this problem. If you have any recommendations, please share. Cheers!

    Feel free to visit my web-site:  @ -

  • @

    6/24/2014 9:06:43 AM |

    Awesome site you have here but I was wanting to know if you knew of any discussion boards that cover the same topics talked about in this article? I'd really like to be a part of community where I can get responses from other experienced individuals that share the same interest. If you have any recommendations, please let me know. Cheers!

    my blog post ...  @ -

  • @

    6/24/2014 9:11:00 AM |

    When some one searches for his vital thing, therefore he/she needs to be available that in detail, therefore that thing is maintained over here.

    Review my web page ...  @ -

  • @

    6/24/2014 9:12:28 AM |

    Magnificent goods from you, man. I have be mindful your stuff prior to and you are just too wonderful. I really like what you've obtained right here, really like what you're saying and the best way in which you are saying it. You are making it entertaining and you still care for to stay it wise. I cant wait to read much more from you. This is really a wonderful web site.

    Also visit my web-site -  @ -

  • @

    6/24/2014 9:21:52 AM |

    Howdy! This post couldn't be written any better! Reading through this post reminds me of my good old room mate! He always kept talking about this. I will forward this article to him. Fairly certain he will have a good read. Many thanks for sharing!

    Also visit my blog post  @ -

  • @

    6/24/2014 9:22:06 AM |

    Pretty nice post. I just stumbled upon your weblog and wanted to say that I have truly enjoyed browsing your blog posts. In any case I'll be subscribing to your feed and I hope you write again very soon!

    my blog ::  @ -

  • @

    6/24/2014 9:25:41 AM |

    Hello, yeah this article is actually pleasant and I have learned lot of things from it concerning blogging. thanks.

    Review my page -  @ -

  • @

    6/24/2014 9:28:20 AM |

    Hi there, always i used to check website posts here in the early hours in the daylight, for the reason that i love to learn more and more.

    Take a look at my webpage;  @ -

  • Gloria

    6/24/2014 9:34:29 AM |

    Excellent post. I was checking constantly this weblog and I am impressed! Extremely useful information particularly the remaining part Smile I maintain such information a lot. I was seeking this particular info for a long time. Thank you and good luck.

    Feel free to surf to my web-site :: @ ( Gloria - )

  • @

    6/24/2014 9:37:43 AM |

    Because the admin of this website is working, no question very shortly it will be famous, due to its quality contents.

    my page:  @ -

  • travel gear

    6/24/2014 7:50:37 PM |

    Do you mind if I quote a couple of your articles as long as I provide credit and sources back to your site? My blog is in the very same area of interest as yours and my visitors would genuinely benefit from a lot of the information you provide here. Please let me know if this ok with you. Thanks a lot!

    My page ::  travel gear -

Pingbacks and trackbacks (1)+

Comments are closed