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 (48) -

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

@

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 -  @ - http://rjanycecilia.soup.io

@

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

my web site -  @ - http://vcartermarshall.blog.interia.pl

@

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

@

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 ::  @ - http://nicoletysony.soup.io

@

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 ::  @ - http://darrelledytht.blog.interia.pl

@

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

My web-site  @ - http://tpeytonyoshiko.soup.io

@

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  @ - http://cjermeyestrella.soup.io

@

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:  @ - http://greenariellej.blog.interia.pl

@

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

Here is my webpage  @ - http://kfaustooceane.blog.interia.pl

@

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 ::  @ - http://moisesalishax.soup.io

@

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;  @ - http://bdylangail.blog.interia.pl

@

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:  @ - http://hjovanypolly.blog.interia.pl

@

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  @ - http://sarinanelsong.soup.io

@

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;  @ - http://elissamarcelw.soup.io

@

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:  @ - http://mterryclifford.soup.io

@

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 ::  @ - http://roymaevem.blog.interia.pl

@

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

Review my website;  @ - http://befrainmellie.soup.io

@

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  @ - http://cmollyfabiola.soup.io

@

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:  @ - http://kelsiekameronb.blog.interia.pl

@

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

Also visit my page -  @ - http://bayleeerickae.soup.io

@

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 ::  @ - http://nmicahmacey.blog.interia.pl

@

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 -  @ - http://hpercyviolet.blog.interia.pl

@

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:  @ - http://uisaiassyble.soup.io

@

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;  @ - http://flaviowilfredr.soup.io

Lolita

Great article, exactly what I wanted to find.

my web-site @ ( Lolita - http://gailmaribelw.soup.io )

@

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 -  @ - http://ywellingtonduncan.soup.io

@

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

Also visit my website ...  @ - http://kalexaneroxane.soup.io

@

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;  @ - http://erindestinyy.soup.io

@

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 ...  @ - http://lsummercoy.soup.io

@

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  @ - http://zashabrielle.blog.interia.pl

@

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 ...  @ - http://ehalliefelton.soup.io

Latanya

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 - http://giannireganl.soup.io )

@

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 ...  @ - http://benelzax.soup.io

@

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:  @ - http://hollisedisonf.soup.io

@

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 ...  @ - http://cethyldarrell.soup.io

@

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 ...  @ - http://briverlily.blog.interia.pl

@

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 -  @ - http://vbernicemaureen.soup.io

@

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  @ - http://wvladimirdesiree.blog.interia.pl

@

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 ::  @ - http://xmoriahmaida.blog.interia.pl

@

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

Review my page -  @ - http://cristobalforestv.soup.io

@

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;  @ - http://rgeorgianaamira.blog.interia.pl

@

Hey very interesting blog!

My blog post -  @ - http://marcellerebecam.soup.io

Gloria

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 - http://carleyleonu.soup.io )

@

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

my page:  @ - http://nnedralenny.soup.io

travel gear

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 - acecampinggear.org/.../

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