Exporting GridView to PDF


In this article I am going to explain how you could export gridview to a pdf file using iTextSharp.dll in a well aligned format. I would like to explain the concept by making use of a sample application.

Learn how to export gridview to a pdf file using iTextSharp.dll


The sample contains a simple aspx page with grid view and a button control. By default the gridview is populated in the page load event itself and when the user clicks on the 'Export' button, the gridview is exported to a pdf file. The prerequisite to export to PDF is the itextsharp.dll. You can either download it from sourceforge.net or you can use the one in the bin folder of the sample application provided as a download.

The following is a function which accepts a gridview control and a boolean parameter which specifies whether to export the pdf file in landscape or not.


protected void ExportToPDF(GridView gvReport, bool LandScape)
{
int noOfColumns = 0, noOfRows = 0;
DataTable tbl = null;

if (gvReport.AutoGenerateColumns)
{
tbl = gvReport.DataSource as DataTable; // Gets the DataSource of the GridView Control.
noOfColumns = tbl.Columns.Count;
noOfRows = tbl.Rows.Count;
}
else
{
noOfColumns = gvReport.Columns.Count;
noOfRows = gvReport.Rows.Count;
}

float HeaderTextSize = 8;
float ReportNameSize = 10;
float ReportTextSize = 8;
float ApplicationNameSize = 7;

// Creates a PDF document

Document document = null;
if (LandScape == true)
{
// Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
}
else
{
document = new Document(PageSize.A4, 0, 0, 15, 5);
}

// Creates a PdfPTable with column count of the table equal to no of columns of the gridview or gridview datasource.
iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);

// Sets the first 4 rows of the table as the header rows which will be repeated in all the pages.
mainTable.HeaderRows = 4;

// Creates a PdfPTable with 2 columns to hold the header in the exported PDF.
iTextSharp.text.pdf.PdfPTable headerTable = new iTextSharp.text.pdf.PdfPTable(2);

// Creates a phrase to hold the application name at the left hand side of the header.
Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

// Creates a PdfPCell which accepts a phrase as a parameter.
PdfPCell clApplicationName = new PdfPCell(phApplicationName);
// Sets the border of the cell to zero.
clApplicationName.Border = PdfPCell.NO_BORDER;
// Sets the Horizontal Alignment of the PdfPCell to left.
clApplicationName.HorizontalAlignment = Element.ALIGN_LEFT;

// Creates a phrase to show the current date at the right hand side of the header.
Phrase phDate = new Phrase(DateTime.Now.Date.ToString("dd/MM/yyyy"), FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));

// Creates a PdfPCell which accepts the date phrase as a parameter.
PdfPCell clDate = new PdfPCell(phDate);
// Sets the Horizontal Alignment of the PdfPCell to right.
clDate.HorizontalAlignment = Element.ALIGN_RIGHT;
// Sets the border of the cell to zero.
clDate.Border = PdfPCell.NO_BORDER;

// Adds the cell which holds the application name to the headerTable.
headerTable.AddCell(clApplicationName);
// Adds the cell which holds the date to the headerTable.
headerTable.AddCell(clDate);
// Sets the border of the headerTable to zero.
headerTable.DefaultCell.Border = PdfPCell.NO_BORDER;

// Creates a PdfPCell that accepts the headerTable as a parameter and then adds that cell to the main PdfPTable.
PdfPCell cellHeader = new PdfPCell(headerTable);
cellHeader.Border = PdfPCell.NO_BORDER;
// Sets the column span of the header cell to noOfColumns.
cellHeader.Colspan = noOfColumns;
// Adds the above header cell to the table.
mainTable.AddCell(cellHeader);

// Creates a phrase which holds the file name.
Phrase phHeader = new Phrase("Sample Export", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));
PdfPCell clHeader = new PdfPCell(phHeader);
clHeader.Colspan = noOfColumns;
clHeader.Border = PdfPCell.NO_BORDER;
clHeader.HorizontalAlignment = Element.ALIGN_CENTER;
mainTable.AddCell(clHeader);

// Creates a phrase for a new line.
Phrase phSpace = new Phrase("\n");
PdfPCell clSpace = new PdfPCell(phSpace);
clSpace.Border = PdfPCell.NO_BORDER;
clSpace.Colspan = noOfColumns;
mainTable.AddCell(clSpace);

// Sets the gridview column names as table headers.
for (int i = 0; i < noOfColumns; i++)
{
Phrase ph = null;

if (gvReport.AutoGenerateColumns)
{
ph = new Phrase(tbl.Columns[i].ColumnName, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}
else
{
ph = new Phrase(gvReport.Columns[i].HeaderText, FontFactory.GetFont("Arial", HeaderTextSize, iTextSharp.text.Font.BOLD));
}

mainTable.AddCell(ph);
}

// Reads the gridview rows and adds them to the mainTable
for (int rowNo = 0; rowNo < noOfRows; rowNo++)
{
for (int columnNo = 0; columnNo < noOfColumns; columnNo++)
{
if (gvReport.AutoGenerateColumns)
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
if (gvReport.Columns[columnNo] is TemplateField)
{
DataBoundLiteralControl lc = gvReport.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
string s = lc.Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
else
{
string s = gvReport.Rows[rowNo].Cells[columnNo].Text.Trim();
Phrase ph = new Phrase(s, FontFactory.GetFont("Arial", ReportTextSize, iTextSharp.text.Font.NORMAL));
mainTable.AddCell(ph);
}
}
}

// Tells the mainTable to complete the row even if any cell is left incomplete.
mainTable.CompleteRow();
}

// Gets the instance of the document created and writes it to the output stream of the Response object.
PdfWriter.GetInstance(document, Response.OutputStream);

// Creates a footer for the PDF document.
HeaderFooter pdfFooter = new HeaderFooter(new Phrase(), true);
pdfFooter.Alignment = Element.ALIGN_CENTER;
pdfFooter.Border = iTextSharp.text.Rectangle.NO_BORDER;

// Sets the document footer to pdfFooter.
document.Footer = pdfFooter;
// Opens the document.
document.Open();
// Adds the mainTable to the document.
document.Add(mainTable);
// Closes the document.
document.Close();

Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment; filename= SampleExport.pdf");
Response.End();
}


I will explain the constructors and methods which are part of itextsharp.dll and the purpose of them using in the code.


Document document = null;
if (LandScape == true)
{
// Sets the document to A4 size and rotates it so that the orientation of the page is Landscape.
document = new Document(PageSize.A4.Rotate(), 0, 0, 15, 5);
}
else
{
document = new Document(PageSize.A4, 0, 0, 15, 5);
}


Document is the object to which you'll add content: the document data.Upon creating the Document object, you can define the page size, the page color, and the margins of the first page of your PDF document.

In the above code we have created the document object with PageSize equal to A4 and the corresponding values related to marginLeft,marginRight,marginTop and marginBottom.


iTextSharp.text.pdf.PdfPTable mainTable = new iTextSharp.text.pdf.PdfPTable(noOfColumns);


If you want full control over the way the content in the pdf is rendered,we make use of the PdfPTable.when you create a PdfPTable,you always need to pass the number of columns to the constructor(creating a table with zero columns results in RuntimeException).You can add different objects to PdfPTable object using the AddCell() method.There is an object PdfPRow in the iTextSharp.text.pdf namespace but arent supposed to address it directly;iText uses this class internally to store the cells that belong to the same row.In other words,you don't have to worry about rows - you just have to make sure you're adding the correct number of cells.


Phrase phApplicationName = new Phrase("Sample Application", FontFactory.GetFont("Arial", ApplicationNameSize, iTextSharp.text.Font.NORMAL));


Phrase is the building block, containing a String in one specific font, font size, font style, and font color.


Phrase phHeader = new Phrase("Sample Export", FontFactory.GetFont("Arial", ReportNameSize, iTextSharp.text.Font.BOLD));

PdfPCell clHeader = new PdfPCell(phHeader);

mainTable.AddCell(clHeader);


PdfPCell is created with Phrase as parameter and then the cell is added to the PdfPTable using the AddCell method.


mainTable.CompleteRow();


Suppose your PdfPTable has 2 columns but you added only a single cell to the PdfPTable,calling the CompleteRow() method of the PdfPTable automatically adds the remaining empty cells to the table and completes the row.


PdfWriter.GetInstance(document, Response.OutputStream);


PdfWriter gets the instance of the document object,the second parameter tells the PdfWriter to which OutputStream the resulting document should be written.


document.Open();
document.Add(mainTable);
document.Close();


opens the document object,adds the PdfPTable named 'mainTable' to the document and closes the document.

The remaining code which you should already be familiar is used to set the content type and header of the response object.

This is my first article so please excuse me if there are any mistakes.Hope this article was helpful to you.

Below are the download links:

VisualStudio2010Solution
GridView to PDF


Attachments

  • VisualStudio2010Solution (29759-22427-VisualStudio2010Solution.rar)
  • GridView to PDF (29759-30458-GridToPDF.zip)
  • Comments

    Author: Mohammad Vahaj uddin03 Sep 2009 Member Level: Silver   Points : 0

    wonderfull marvellous job

    Author: Williams04 Sep 2009 Member Level: Gold   Points : 0

    Thank you Mohammad for your compliment.

    Author: Mohan04 Sep 2009 Member Level: Gold   Points : 1

    Wonderful article and way of coding.
    Is Itestshrp dll is freeware or trailversion dll?

    Author: Williams04 Sep 2009 Member Level: Gold   Points : 0

    Hi Mohan itextsharp is a freeware.Thanks for your compliment.

    Author: Dil Jan01 Oct 2009 Member Level: Silver   Points : 1

    Thank you, Thank you very much.
    My problem solved with the help of your article.

    Author: suresh babu15 Mar 2011 Member Level: Silver   Points : 1

    A nice article and a very clear way of explanation. please continue sharing your learnings in the same way.

    Guest Author: tripti kumbhat01 Mar 2012

    thank you so much sir.

    Guest Author: Leandro03 May 2012

    wonderfull marvellous job
    wonderfull marvellous job
    wonderfull marvellous job
    wonderfull marvellous job
    wonderfull marvellous job
    wonderfull marvellous job

    Author: Williams06 May 2012 Member Level: Gold   Points : 0

    Thank You Leandro.

    Guest Author: Nge Nge02 Aug 2012

    Hi Williams

    I am trying on this way to export Pdf. But I am getting the error on the following statement.
    DataBoundLiteralControl lc = GridView1.Rows[rowNo].Cells[columnNo].Controls[0] as DataBoundLiteralControl;
    string s = lc.Text.Trim();
    The error is "Object reference not set to an instance of an object."
    How should I solve this? Actually My DataGrid has 12 rows and 8 columns of data.

    Author: Nwe Nwe19 Nov 2012 Member Level: Silver   Points : 0

    Excellent Article.
    Thanks a lot for sharing.

    Author: Williams20 Nov 2012 Member Level: Gold   Points : 0

    Thanks a lot for all your feedback.

    Guest Author: Mahesh11 Jan 2013

    I downloaded the project and opened in visual studio 2010. When I build the solution it is throwing error saying that gvExport is not found.But It seems to me that gvExport datagrid is defined in the default.aspx page. Could you please notify me where I am doing mistake.

    Author: Williams15 Jan 2013 Member Level: Gold   Points : 0

    Hi Mahesh i have attached a new VisualStudio2010 working project,you can download it and use it for your requirement.

    Thanks

    Guest Author: noora08 Dec 2013

    great code, but how can i change the width of each column?

    Guest Author: Malvinder Singh08 Jan 2014

    Superb explanation.
    How to set the width of the columns, fetched from database.

    Guest Author: Sanjay Gupta09 Feb 2014

    Nice Idea to export gridview header in pdf.

    Guest Author: markiv14 Feb 2014

    How can I use your code to export the pdf on click of an asp:image button ?

    Guest Author: Amit Singh26 Feb 2014

    Good article. I am working for Windows forms for the same functionality; but your code is for web-applications.

    Can you provide me any sources for exporting datagrid to PDF in C# window forms? I would be thankful to you.

    Guest Author: Amit Singh26 Feb 2014

    Good article dude. I am working for windows forms for the same functionality; but your code is for web-applications.

    Can you provide me any sources for exporting datagrid to PDF in C# window forms?

    Author: shalini rathore20 Mar 2014 Member Level: Gold   Points : 0

    hello,

    Really good article,well explained.Hope it helps others.
    keep contributing.

    Regards
    Shalini

    Author: Williams17 Jun 2014 Member Level: Gold   Points : 0

    Hi vinayak

    The download link is provided at the bottom of the article.Please use it to download the source code related to the article.



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: