Click here to Skip to main content
11,637,662 members (77,991 online)
Click here to Skip to main content

Tagged as

Generating PDF using ItextSharp with Footer in C#

, 13 Apr 2013 CPOL 55.8K 13
Rate this:
Please Sign up or sign in to vote.
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author


You may also be interested in...

Comments and Discussions

 
QuestionHeader Footer iTextsharp Pin
Member 103046107-Jan-15 22:32
memberMember 103046107-Jan-15 22:32 
Questionkirilli Pin
Member 1006112718-Feb-14 6:09
memberMember 1006112718-Feb-14 6:09 
Questiondont want to create pdf on server side Pin
shuklasachin13116-Dec-13 23:39
membershuklasachin13116-Dec-13 23:39 
Question[My vote of 1] Multiple Errors Pin
msdevtech1-Nov-13 10:12
membermsdevtech1-Nov-13 10:12 
Questionconversion pdf to doc Pin
Ashwani Gusain24-Aug-13 1:50
memberAshwani Gusain24-Aug-13 1:50 
QuestionThanks Pin
vinayise12-May-13 23:13
membervinayise12-May-13 23:13 
QuestionError in your example Pin
blowagie8-Apr-13 1:53
memberblowagie8-Apr-13 1:53 
AnswerRe: Error in your example Pin
Praveen Kumar Chauhan (PRK)8-Apr-13 6:15
memberPraveen Kumar Chauhan (PRK)8-Apr-13 6:15 
GeneralRe: Error in your example Pin
blowagie8-Apr-13 8:21
memberblowagie8-Apr-13 8:21 
GeneralRe Error in your example Pin
Praveen Kumar Chauhan (PRK)8-Apr-13 20:09
memberPraveen Kumar Chauhan (PRK)8-Apr-13 20:09 
GeneralRe: Error in your example Pin
Ashwani Gusain24-Aug-13 1:49
memberAshwani Gusain24-Aug-13 1:49 

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

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

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.150728.1 | Last Updated 13 Apr 2013
Article Copyright 2013 by Praveen Kumar Chauhan (PRK)
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid