Click here to Skip to main content
12,831,626 members (31,350 online)
Click here to Skip to main content
Add your own
alternative version

Tagged as


31 bookmarked
Posted 16 Aug 2011

Generating Report in PDF Format using iTextSharp Version

, 16 Aug 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
This project helps solve the problem we were having with iTextSharp version getting PDF report with formatting


Many of us tried to generate report in *.pdf format but there are no correct tools that just give this feature for free. Here I found one library iTextSharp.dll file which is for PDF reports but there are so many versions of it and it is really very hard to get the right DLL file to generate report, formatting, page numbers and all. So in this article, you will find all these things get done with a simple few lines of codes.


This project is done in ASP.NET using C# language. Here the database used is the Access database. But it really works with SQL Server too. I have tried SQL Server database too but it's easy for me to attach .mdb file in here. The article provides the easiest way to deal with multiple tables and retrieve data from multiple tables and generate the PDF file with header and footer. Also this article helps to insert the page number in each PDF page.

Using the Code

The whole project is attached in the zip file. You can just download and take benefit of this example in your project. The main gist code of the article is shown below. But before using this code, you have to add iTextSharp.dll version file in the Reference of your project and on the top of the *.cs page, you have to import this file. The whole thing is shown in the downloadable zip file. I am getting data from multiple tables joining. The tables being used are CustomerOrder and OrderedItem which are shown in the codes below too. Using DataRelation feature for combining two tables with the total sum are automatically calculated and shown in the report. The codes for this are:

string catQuery = @"select * from CustomerOrder";
OleDbCommand objCmd = new OleDbCommand(catQuery, cnx);
OleDbDataAdapter objDAcategory = new OleDbDataAdapter(objCmd);
objDAcategory.Fill(ds, "CustomerOrder");

string totQuery = @"select OrderID,sum(Amount) _
As [TotalAmount] from OrderedItem where IsActive = '1' group by OrderID";
objCmd = new OleDbCommand(totQuery, cnx);
OleDbDataAdapter objDAtotal = new OleDbDataAdapter(objCmd);
objDAtotal.Fill(ds, "OrderedItem");

string itemQuery = @"select * from OrderedItem where IsActive='1'";
objCmd = new OleDbCommand(itemQuery, cnx);
OleDbDataAdapter objDAitem = new OleDbDataAdapter(objCmd);
objDAitem.Fill(ds, "OrderedItem");

DataRelation dRel = new DataRelation("CustomerOrder_OrderedItem", _
ds.Tables["CustomerOrder"].Columns["OrderID"], _
cusDptInfo.DataSource = ds;

The following code is for writing data to the PDF file. Document variable pdfDoc has been defined as the A4 sized paper with all those border values.

HttpContext.Current.Response.Clear(); //clear anything in io buffer           
	("Content-Disposition", "attachment;filename=iTextSharpExample.pdf");
HttpContext.Current.Response.Charset = "";
HttpContext.Current.Response.ContentType = "application/pdf";
StringWriter stringwrite = new StringWriter();
HtmlTextWriter htmlwrite = new HtmlTextWriter(stringwrite);
StringReader sr = new StringReader(stringwrite.ToString());
Document pdfDoc = new Document(PageSize.A4, 50f, 50f, 40f, 40f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

The following piece of code is for counting the pagenumber.

string pcnt;
pcnt = (writer.CurrentPageNumber - 1).ToString();
pcnt = pcnt.Substring(1);

The following code shows how header and footer can be implemented in the PDF file with alignments and border style.

HeaderFooter header = new HeaderFooter
		(new Phrase("My Company \n Customer Order Details"), false) 
		{ Border = Rectangle.NO_BORDER, Alignment = Element.ALIGN_CENTER };
HeaderFooter footer = new HeaderFooter(new Phrase(pcnt), true) 
		{ Border = Rectangle.NO_BORDER, Alignment = Element.ALIGN_CENTER };
pdfDoc.Header = header;
pdfDoc.Footer = footer;

This piece of code is to include current date for report generator and it is shown in all the pages of the PDF file.

_events e = new _events();

e.TimerText = DateTime.Now.ToString("MM/dd/yyyy");

writer.PageEvent = e;


This aspx side code includes basically which piece of data from the tables are to be shown and how.

    <asp:Repeater runat="server" ID="cusDptInfo" 
	onitemdatabound="cusDptInfo_ItemDataBound" >
    <ItemTemplate ><font size="60%">
    <b><%# DataBinder.Eval(Container.DataItem, "FirstName") %> 
    <%# DataBinder.Eval(Container.DataItem, "LastName") %></b><br />
    <%# DataBinder.Eval(Container.DataItem, "GroupName") %><br />
    <%# DataBinder.Eval(Container.DataItem, "Email") %><br />
    <%# DataBinder.Eval(Container.DataItem, "CreationDate","{0:MM/dd/yyyy}") %><br />   
    <br /></font>
        <asp:Repeater ID="rptItemList" runat="server">
                <asp:Table ID="tblItemList" 
                runat="server" Font-Size="7%">
                        <asp:TableCell><%# DataBinder.Eval(Container.DataItem,"
                        Item")%> <%#DataBinder.Eval(Container.DataItem, "
                        Category","({0})")%><br /><font color="
                        gray" style="text-align:justify"><%# 
                        DataBinder.Eval(Container.DataItem, "ItemDescription") %>
                        <asp:TableCell HorizontalAlign="Right">
                        <%# DataBinder.Eval(Container.DataItem,"
                        Amount","{0:c}") %></asp:TableCell>
        <asp:Repeater ID="rptOrderedTotAmount" runat="server">
                <asp:Table ID="tblItemListt" runat="server" Font-Size="7%">
                        <asp:TableCell HorizontalAlign="Right">
                        <%# DataBinder.Eval(Container.DataItem, "TotalAmount","
                        <strong>Total: </strong>{0:c}") %></asp:TableCell>
                <br />


  • 16th August, 2011: Initial post


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Nepal Nepal
Nothing is particularly hard if you divide it into small jobs. -- Henry Ford

You may also be interested in...


Comments and Discussions

QuestionGenerating Report in PDF Format using iTextSharp Version Pin
galandim14-Aug-12 6:42
membergalandim14-Aug-12 6:42 
AnswerRe: Generating Report in PDF Format using iTextSharp Version Pin
Dhyanga22-Aug-12 4:09
memberDhyanga22-Aug-12 4:09 
QuestionWhat about this? Pin
Win32nipuh26-Aug-11 23:11
memberWin32nipuh26-Aug-11 23:11 
AnswerRe: What about this? Pin
Dhyanga11-Jul-12 8:07
memberDhyanga11-Jul-12 8:07 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.170326.1 | Last Updated 16 Aug 2011
Article Copyright 2011 by Dhyanga
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid