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

How to create pdf file using iTextSharp 5.1


add reference of iTextSharp dll in your project.
you can download iTextsharp dll from http://sourceforge.net/projects/itextsharp/



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

// Create a new PdfWriter object, specifying the output stream
var output = new FileStream(Server.MapPath("MyFirstPDF.pdf"), FileMode.Create);
PdfWriter.GetInstance(document, output);

// Open the Document for writing
document.Open();

... Step 3: Add elements to the document! ...

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

// Add the Paragraph object to the document
document.Add(welcomeParagraph);

// Close the Document - this saves the document contents to the output stream
document.Close();