C# .NET - How to export datatable to PDF file/format using C#?

Asked By Muthu Kumar on 07-Sep-10 06:12 AM
Hi all,

I have one datatable in my application. Now I want to export the data available in the datatable to pdf format. How to export the data available in the datatable to pdf file using C#? Any ideas...appreciated...
Sagar P replied to Muthu Kumar on 07-Sep-10 06:33 AM
You could actually do that using iTextSharp dll which is explained in the following ones...

http://www.codeproject.com/KB/graphics/iTextSharpTutorial.aspx

http://hspinfo.wordpress.com/2008/01/12/how-to-convert-html-content-to-pdf-file/

CodePlex has a project on this too.
http://www.codeplex.com/Exporter

Sagar P replied to Muthu Kumar on 07-Sep-10 06:36 AM
Try this code;

protected void ExportToPDF(object sender, EventArgs e)

{

    //Get the data from database into datatable

    string strQuery = "select CustomerID, ContactName, City, PostalCode" +

      " from customers";

    SqlCommand cmd = new SqlCommand(strQuery);

    DataTable dt = GetData(cmd);

 

    //Create a dummy GridView

    GridView GridView1 = new GridView();

    GridView1.AllowPaging = false;

    GridView1.DataSource = dt;

    GridView1.DataBind();

 

    Response.ContentType = "application/pdf";

    Response.AddHeader("content-disposition",

      "attachment;filename=DataTable.pdf");

    Response.Cache.SetCacheability(HttpCacheability.NoCache);

    StringWriter sw = new StringWriter();

    HtmlTextWriter hw = new HtmlTextWriter(sw);

    GridView1.RenderControl(hw);

    StringReader sr = new StringReader(sw.ToString());

    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

    PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

    pdfDoc.Open();

    htmlparser.Parse(sr);

    pdfDoc.Close();

    Response.Write(pdfDoc);

    Response.End(); 

}