Click here to Skip to main content
15,884,099 members
Articles / Web Development / ASP.NET
Tip/Trick

Generating PDF using ItextSharp with Footer in C#

Rate me:
Please Sign up or sign in to vote.
4.67/5 (10 votes)
13 Apr 2013CPOL1 min read 146.3K   20   13
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:

C#
using iTextSharp.text.pdf; 
using iTextSharp.text;  

The code:

C#
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:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



Comments and Discussions

 
QuestionIt's worked Pin
Member 1046365410-Feb-21 21:09
Member 1046365410-Feb-21 21:09 
QuestionGreat work Pin
Member 1245602827-Apr-17 1:36
Member 1245602827-Apr-17 1:36 
QuestionHeader Footer iTextsharp Pin
Member 103046107-Jan-15 22:32
Member 103046107-Jan-15 22:32 
Works perfect great example thanks a lot saved me headache about having headers and footers
Questionkirilli Pin
Member 1006112718-Feb-14 6:09
Member 1006112718-Feb-14 6:09 
Questiondont want to create pdf on server side Pin
shuklasachin13116-Dec-13 23:39
shuklasachin13116-Dec-13 23:39 
Question[My vote of 1] Multiple Errors Pin
msdevtech1-Nov-13 10:12
msdevtech1-Nov-13 10:12 
Questionconversion pdf to doc Pin
Ashwani Gusain24-Aug-13 1:50
Ashwani Gusain24-Aug-13 1:50 
QuestionThanks Pin
vinayise12-May-13 23:13
vinayise12-May-13 23:13 
QuestionError in your example Pin
blowagie8-Apr-13 1:53
blowagie8-Apr-13 1:53 
AnswerRe: Error in your example Pin
Praveen Kumar Chauhan (PRK)8-Apr-13 6:15
professionalPraveen Kumar Chauhan (PRK)8-Apr-13 6:15 
GeneralRe: Error in your example Pin
blowagie8-Apr-13 8:21
blowagie8-Apr-13 8:21 
GeneralRe Error in your example Pin
Praveen Kumar Chauhan (PRK)8-Apr-13 20:09
professionalPraveen Kumar Chauhan (PRK)8-Apr-13 20:09 
GeneralRe: Error in your example Pin
Ashwani Gusain24-Aug-13 1:49
Ashwani Gusain24-Aug-13 1:49 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.