Wednesday 9 November 2011

How to add header and footer on pdf file using iTextSharp 5.1

first we create a class that in inherited by  PdfPageEventHelper. and  i create table in this class and write footer content.


 public partial class Footer : PdfPageEventHelper
    {
        public override void OnEndPage(PdfWriter writer, Document doc)
        {

            Paragraph footer= new Paragraph("THANK YOU", FontFactory.GetFont(FontFactory.TIMES, 10, iTextSharp.text.Font.NORMAL));
            footer.Alignment = Element.ALIGN_RIGHT;
            PdfPTable footerTbl = new PdfPTable(1);
            footerTbl.TotalWidth = 300;
            footerTbl.HorizontalAlignment = Element.ALIGN_CENTER;
            PdfPCell cell = new PdfPCell(footer);
            cell.Border = 0;
            cell.PaddingLeft = 10;
            footerTbl.AddCell(cell);
            footerTbl.WriteSelectedRows(0, -1, 415, 30, writer.DirectContent);
        }
    }

after this


Document document = new Document(PageSize.A4, 50, 50, 25, 25);

var output = new FileStream(Server.MapPath("Demo.pdf"), FileMode.Create);
  PdfWriter writer = PdfWriter.GetInstance(document, output);

// Open the Document for writing
document.Open();
//using footer class
 writer.PageEvent = new Footer();.

Paragraph welcomeParagraph = new Paragraph("Hello, World!");

document.Add(welcomeParagraph);

document.Close();

13 comments:

  1. Good Work... Working Fine... Thnx :)
    for Header The Code will be same but Position will be:

    "headerTbl.WriteSelectedRows(0, -1, 0, (doc.PageSize.Height - 10), writer.DirectContent);"

    ReplyDelete
  2. Thanks Gopal. It is really helpful. I was searching on web for so long for this particular issue.

    ReplyDelete
  3. Thanks a lot! There is not a lot of documentation on iTextSharp. This really helped! Thanks!

    ReplyDelete
  4. I am using this code i am getting last page printing footer value i need every page please give me solution..

    ReplyDelete
    Replies
    1. put the "writer.PageEvent = new Footer();" before the "document.open()"

      Delete
  5. Hi Gopal,
    I am trying create pdf using html template,Please can you share me the code.

    ReplyDelete
  6. Hi Gopal
    i am trying code but it add footer only in first page!
    can help me to add footer on all pdf pages that created by itextsharp \c#
    thanks

    ReplyDelete
    Replies
    1. put the "writer.PageEvent = new Footer();" before the "document.open()"

      Delete
  7. This comment has been removed by the author.

    ReplyDelete
  8. I have used the same code in my application. But the footer is coming only in the last page. How to solve this issue

    ReplyDelete
    Replies
    1. put the "writer.PageEvent = new Footer();" before the "document.open()"

      Delete