Wednesday, June 18, 2008

Export GridView to PDF

Recently I have been trying to generate some reports to PDF file format from ASP. NET2.0 application. There are a lot of open source PDF libraries out there that you can use to export to PDF such as iTextSharp, Gios PDF .NET Library and PDFSharp. You can go to this link to find out more open source PDF libraries in C#.

Later I will show you a working solution on how to export GridView to PDF by using one of the free libraries – iTextSharp.

ITextSharp is a port of the iText open source java library written entirely in C# for the .NET platform. It is a library that allows developers to extend the capabilities of their web server applications with dynamic PDF document generation and generate PDF file on the fly.

Before that, you need to download the iTextSharp library. Here is the download link.

Add in the iTextSharp.dll as a reference into your web application.

Here is my sample of code:


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

protected void Page_Load(object sender, EventArgs e)
{
  ExportToPDF();
}

private void ExportToPDF()
{
  Document document = new Document(PageSize.A4, 0, 0, 50, 50);
  System.IO.MemoryStream msReport = new System.IO.MemoryStream();

  try {
    // creation of the different writers
    PdfWriter writer = PdfWriter.GetInstance(document, msReport);

    // we add some meta information to the document
    document.AddAuthor("eJuly");
    document.AddSubject("Export to PDF");

    document.Open();

    iTextSharp.text.Table datatable = new iTextSharp.text.Table(7);

    datatable.Padding = 2;
    datatable.Spacing = 0;

    float[] headerwidths = { 6, 20, 32, 18, 8, 8, 8 };
    datatable.Widths = headerwidths;

    // the first cell spans 7 columns
    Cell cell = new Cell(new Phrase("System Users Report", FontFactory.GetFont(FontFactory.HELVETICA, 16, Font.BOLD)));
    cell.HorizontalAlignment = Element.ALIGN_CENTER;
    cell.Leading = 30;
    cell.Colspan = 7;
    cell.Border = Rectangle.NO_BORDER;
    cell.BackgroundColor = new iTextSharp.text.Color(System.Drawing.Color.Gray);
    datatable.AddCell(cell);

    // These cells span 2 rows
    datatable.DefaultCellBorderWidth = 1;
    datatable.DefaultHorizontalAlignment = 1;
    datatable.DefaultRowspan = 2;
    datatable.AddCell("No.");
    datatable.AddCell(new Phrase("Full Name", FontFactory.GetFont(FontFactory.HELVETICA, 14, Font.NORMAL)));
    datatable.AddCell("Address");
    datatable.AddCell("Telephone No.");

    // This cell spans the remaining 3 columns in 1 row
    datatable.DefaultRowspan = 1;
    datatable.DefaultColspan = 3;
    datatable.AddCell("Just Put Anything");

    // These cells span 1 row and 1 column
    datatable.DefaultColspan = 1;
    datatable.AddCell("Col 1");
    datatable.AddCell("Col 2");
    datatable.AddCell("Col 3");

    datatable.DefaultCellBorderWidth = 1;
    datatable.DefaultRowspan = 1;

    for (int i = 1; i < 20; i++) {
      datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT;
      datatable.AddCell(i.ToString());
      datatable.AddCell("This is my name.");
      datatable.AddCell("I have a very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very, very long long address.");
      datatable.AddCell("0123456789");

      datatable.DefaultHorizontalAlignment = Element.ALIGN_CENTER;
      datatable.AddCell("No");
      datatable.AddCell("Yes");
      datatable.AddCell("No");
    }

    document.Add(datatable);
  }
  catch (Exception e) {
    Console.Error.WriteLine(e.Message);
  }

  // we close the document
  document.Close();

  Response.Clear();
  Response.AddHeader("content-disposition", "attachment;filename=Export.pdf");
  Response.ContentType = "application/pdf";
  Response.BinaryWrite(msReport.ToArray());
  Response.End();
}


Hope these codes can help those people who are new to asp.net developing and save some time on their searching solutions. You can also find the tutorial of iTextSharp at here.

Happy Programming!

21 comments:

Unknown on June 19, 2008 at 5:37 PM said...

Hello,

I am working for a company which has a product that will allow you to create PDF documents dynamically. Our products will allow you to create PDF documents programmatically from scratch, merge existing PDF documents, add contents to existing PDF files, stamping PDFs, appending existing PDF documents, form filling, rotating and scaling PDFs, etc.

You can also create the PDF reports using the data from a database directly by giving the connection string and the query. You will have to use the ReportWriter product for this. You can create a report layout in the designer (GUI) and give the connection string and query. This will create the PDF report dynamically getting the data from the database.

You can add tables to the PDF using the table page element. Following is the sample code for adding a table to the PDF.

//Create a document object
Document doc = new Document();

//Create a page object
Page page = new Page();

//Create the table with three columns
Table table = new Table(0, 0, 250, 0);
table.Columns.Add(50);
table.Columns.Add(100);
table.Columns.Add(100);
string str = "ceTe software Support Team";
for (int i = 0; i < 8; i++)
{
Row row = table.Rows.Add();
row.Cells.Add((i + 1).ToString());
Cell cell1 = row.Cells.Add(str);
cell1.ColumnSpan = 2;
}

//set the height to required height
table.Height = table.GetRequiredHeight();

//Add the table to the page
page.Elements.Add(table);

//Add the page to the document
doc.Pages.Add(page);

//Open the PDF in the browser.
doc.DrawToWeb();

You can output the PDF to the browser or stream or byte array or you can save it to the disk.

We have products for .NET, Java, COM/ActiveX platforms.

For more information about our products you can refer to our company website at http://www.cete.com.

Thanks,

Ranga,
ceTe Software Support Team.

Unknown on August 2, 2008 at 1:57 AM said...

In the given code you are not using the gridview plz write me how to export gridview to Pdf formate in and out.

xiaoyu on August 2, 2008 at 11:34 AM said...

Hi ibvkk,

Thanks for your response.

From the given code, you can see that this is the part that I use to insert my value:

for (int i = 1; i < 20; i++) {
...
datatable.AddCell(i.ToString());
datatable.AddCell("This is my name.");
datatable.AddCell("0123456789");
...
}


You can loop your gridview, datagrid, dataset or datatable and add the value into the cell.

Hope this can help you.

Unknown on August 6, 2008 at 10:09 PM said...

rani said
//Create a page object
Page page = new Page();
its not exist in itextsharp file where will we find it

Unknown on August 6, 2008 at 10:12 PM said...

rani said
//Create a page object
Page page = new Page();

where it will exist
please send reply

xiaoyu on August 7, 2008 at 3:58 PM said...

4 Gunta: The codes that are given by rani is not for itextsharp, that is for ceTe software.

For itextsharp, you can refer to my sample code, or refer to their tutorial site

Unknown on August 7, 2008 at 6:29 PM said...

Hello,

You can refer to the help documentation of our product DynamicPDF for .NET on our website http://www.cete.com/Support/NET_Help_Library_08_05/webframe.html.

Thanks,

Ranga,
ceTe Software Support Team.

xiaoyu on August 7, 2008 at 6:48 PM said...

Hi Rani, thx for your information. I appreciate your help very much.

Anonymous said...

Nice codes. Thanks.

Repyingbadboy on September 21, 2008 at 2:47 PM said...

Hi ejuly
U said...
for (int i = 1; i < 20; i++) {
...
datatable.AddCell(i.ToString());
datatable.AddCell("This is my name.");
datatable.AddCell("0123456789");
...
}
You can loop your gridview, datagrid, dataset or datatable and add the value into the cell.

But I'm new in C# programing. Can u help to looping gridview??

xiaoyu on September 22, 2008 at 10:19 AM said...

Hi suman,

Here it is.

foreach (GridViewRow row in GridView1.Rows)
{
...
datatable.AddCell(row.Cells[1].Text);
datatable.AddCell(row.Cells[2].Text);
datatable.AddCell(row.Cells[3].Text);
...
}

// for BoundField
row.Cells[1].Text

// for asp web control
((Label)row.FindControl("lblName")).Text

Hope this can help you.

Repyingbadboy on September 22, 2008 at 2:18 PM said...

Nice and helpful code.
Thank you for your help.
It will me lot.

Amit Panwar on November 4, 2008 at 4:19 PM said...

This code is not working

Document document = new Document();

System.IO.MemoryStream msReport = new System.IO.MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
document.Open();
iTextSharp.text.Table datatable = new iTextSharp.text.Table(8);
datatable.Padding = 4;
datatable.Spacing = 0;
//datatable.setBorder(Rectangle.NO_BORDER);
float[] headerwidths = { 50, 50, 50, 50, 50, 40, 40, 45 };
datatable.Widths = headerwidths;
datatable.WidthPercentage = 100;
Cell cell = new Cell(new Phrase("Applicant Wise Report", FontFactory.GetFont(FontFactory.HELVETICA, 15 ,Font.BOLD)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.Leading = 15;
cell.Colspan = 8;
cell.Border = Rectangle.NO_BORDER;
cell.BackgroundColor = new Color(0xC0, 0xC0, 0xC0);
datatable.AddCell(cell);
datatable.DefaultCellBorderWidth = 1;
datatable.DefaultHorizontalAlignment = 1;
datatable.DefaultRowspan = 1;
datatable.AddCell(new Phrase("Name", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));
datatable.AddCell(new Phrase("Address", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));
datatable.AddCell(new Phrase("State", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));
datatable.AddCell(new Phrase("City", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));
datatable.AddCell(new Phrase("Email ID", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));
datatable.AddCell(new Phrase("Exam Attended", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));
datatable.AddCell(new Phrase("Result Status", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));
datatable.AddCell(new Phrase("Exam Date", FontFactory.GetFont(FontFactory.TIMES, 11, Font.BOLD)));

datatable.DefaultCellBorderWidth = 1;
datatable.DefaultRowspan = 1;
if (Dt.Rows.Count > 0)
{
for (int i = 0; i <= Dt.Rows.Count - 1; i++)
{
datatable.DefaultHorizontalAlignment = Element.ALIGN_LEFT;
string name = Convert.ToString(Dt.Rows[i][0]);
datatable.AddCell(new Cell(new Phrase(name, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))),i+1,0);
string address = Convert.ToString(Dt.Rows[i][1]);
datatable.AddCell(new Cell(new Phrase(address, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))), i + 1, 1);
string state = Convert.ToString(Dt.Rows[i][2]);
datatable.AddCell(new Cell(new Phrase(state, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))), i + 1, 2);
string city = Convert.ToString(Dt.Rows[i][3]);
datatable.AddCell(new Cell(new Phrase(city, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))), i + 1, 3);
string mailid = Convert.ToString(Dt.Rows[i][4]);
datatable.AddCell(new Cell(new Phrase(mailid, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))), i + 1, 4);
string exam = Convert.ToString(Dt.Rows[i][5]);
datatable.AddCell(new Cell(new Phrase(exam, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))), i + 1, 5);
string result = Convert.ToString(Dt.Rows[i][6]);
datatable.AddCell(new Cell(new Phrase(result, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))), i + 1, 6);
string examdate = Convert.ToString(Dt.Rows[i][7]);
datatable.AddCell(new Cell(new Phrase(examdate, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))), i + 1, 7);

}

document.Add(datatable);
}


document.Close();
Response.Clear();
Response.AddHeader("content-disposition", "attachment;filename=ApplicantWiseReport.pdf");
Response.ContentType = "application/pdf";
Response.BinaryWrite(msReport.ToArray());
Response.End();

xiaoyu on November 6, 2008 at 12:03 PM said...

Hi Amit Panwar , sorry for the late reply.

I had tried your codes and I found 2 bugs:

1) datatable.WidthPercentage -> 'iTextSharp.text.Table' does not contain a definition for this. You should remove this line from your codes.

2) datatable.AddCell(new Cell(new Phrase(name, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))),i+1,0);

The characters in bold cause an error msg saying that "Adding a cell at the location (1,0) with a colspan of 1 and a rowspan of 1 is illegal (beyond boundaries/overlapping)."

To solve this, you can simply remove them. The correct codes sud be looks as below:

datatable.AddCell(new Cell(new Phrase(name, FontFactory.GetFont(FontFactory.TIMES, 10, Font.NORMAL))));

Hope this helps :)

Anonymous said...

Hi,
Is it possible to print form controls on the pdf file?
I have to print radio buttons.
I havent find any solution that can send form controls to the pdf file. Any comment or suggestion wud be appreciated. Reply ASAP.

Varun Maggo on April 19, 2011 at 2:32 PM said...

I want to thank you so much!

Varun Maggo on April 19, 2011 at 2:32 PM said...

you rock!

kurkoc on May 27, 2011 at 6:35 AM said...

thanks..good article and very helpful..i want to ask a question...i want to see some characters on output pdf for example (ı,s,o,u...)..what should i do?

thanks again.

xiaoyu on May 27, 2011 at 9:31 AM said...

hi kurkoc, these will do:

// create a table
iTextSharp.text.Table datatable = new iTextSharp.text.Table(7)

// adding a cell
datatable.AddCell("Address");
datatable.AddCell("Telephone No.");

Anonymous said...

Nice and thanks!

Anonymous said...

Ladylike Post. This record helped me in my college assignment. Thnaks Alot

 

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
Sign up for PayPal and start accepting credit card payments instantly. http://www.emailcashpro.com
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template