Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Generating PDF using ItextSharp with Footer in C#

0.00/5 (No votes)
13 Apr 2013 1  
Generate PDF using ItextSharp with header and footer

Introduction

Here, I want to share some tips regarding ItextSharp, as one of my client requirements is to generate an invoice in PDF format. I went through the internet to get the best option for PDF generation, of-course I am a big fan of Crystal Reports for PDF generation not only for its simplicity but also for its quality. But the problem with Crystal Reports is that it should be installed on your hosting server to work with your website. So I tried the itextSharp library. After going through many articles on the internet, I was able to generate an invoice as I expected. As most of the information regarding itextSharp is in pieces online, I decided to write a basic requirement for a page, the report in one place, i.e., Header, Body, and Footer.

Background

I will start with the requirements. To use itextSharp, you need to download the iTextSharp library as it is available for free. You can download it from here.

Using the Code

After downloading iTextSharp, simply add a reference to the iTextSharp library to your project. Use the following namespace before you start writing your code:

using iTextSharp.text.pdf; 
using iTextSharp.text;  

The code:

protected void pdfBt_Click(object sender, EventArgs e)
{
    Document doc = new Document(iTextSharp.text.PageSize.A4);
    System.IO.FileStream file = 
    	new System.IO.FileStream(Server.MapPath("~/Pdf/PdfSample") + 
    	DateTime.Now.ToString("ddMMyyHHmmss") + ".pdf", 
    	System.IO.FileMode.OpenOrCreate);
    PdfWriter writer = PdfWriter.GetInstance(doc, file);
   // calling PDFFooter class to Include in document
    writer.PageEvent = new PDFFooter();
    doc.Open();
    PdfPTable tab = new PdfPTable(3);
    PdfPCell cell = new PdfPCell(new Phrase("Header", 
                        new Font(Font.FontFamily.HELVETICA, 24F)));
    cell.Colspan = 3;
    cell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
    //Style
    cell.BorderColor = new BaseColor(System.Drawing.Color.Red);
    cell.Border = Rectangle.BOTTOM_BORDER; // | Rectangle.TOP_BORDER;
    cell.BorderWidthBottom = 3f;
    tab.AddCell(cell);
    //row 1
    tab.AddCell("R1C1");
    tab.AddCell("R1C2");
    tab.AddCell("R1C3");
    //row 2
    tab.AddCell("R2C1");
    tab.AddCell("R2C2");
    tab.AddCell("R2C3");
    cell = new PdfPCell();
    cell.Colspan = 3;
    iTextSharp.text.List pdfList = new List(List.UNORDERED);
    pdfList.Add(new iTextSharp.text.ListItem(new Phrase("Unorder List 1")));
    pdfList.Add("Unorder List 2");
    pdfList.Add("Unorder List 3");
    pdfList.Add("Unorder List 4");
    cell.AddElement(pdfList);
    tab.AddCell(cell);
    doc.Add(tab);
    doc.Close();
    file.Close();    
}

public class PDFFooter : PdfPageEventHelper
{
    // write on top of document
    public override void OnOpenDocument(PdfWriter writer, Document document)
    {
        base.OnOpenDocument(writer, document);
        PdfPTable tabFot = new PdfPTable(new float[] { 1F });
        tabFot.SpacingAfter = 10F;
        PdfPCell cell;
        tabFot.TotalWidth = 300F;
        cell = new PdfPCell(new Phrase("Header"));
        tabFot.AddCell(cell);
        tabFot.WriteSelectedRows(0, -1, 150, document.Top , writer.DirectContent);
    }

    // write on start of each page
    public override void OnStartPage(PdfWriter writer, Document document)
    {
        base.OnStartPage(writer, document);
    }

    // write on end of each page
    public override void OnEndPage(PdfWriter writer, Document document)
    {   
        base.OnEndPage(writer, document);
        PdfPTable tabFot = new PdfPTable(new float[] { 1F });
        PdfPCell cell;
        tabFot.TotalWidth = 300F;
        cell = new PdfPCell(new Phrase("Footer"));
        tabFot.AddCell(cell);
        tabFot.WriteSelectedRows(0, -1, 150, document.Bottom, writer.DirectContent);
    }

    //write on close of document
    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        base.OnCloseDocument(writer, document);
    }        
} 

Points of Interest

The above code is used to create PDF to disk with the help of the FileStream class. You can use the MemoryStream class to send PDF as response, as shown below:

System.IO.MemoryStream str = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(doc, str);
Response.AddHeader("Content-Disposition", "attachment;filename=report.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(str.ToArray());
str.Close();
Response.End(); 

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here