Search - Articles
DevASP.NET for ASP.NET, VB.NET, XML and C# (C-Sharp) Developers Tuesday, March 03, 2009
Dev Articles
Search Directory
ASP.NET
VB.Net
C-Sharp
SQL Server
 

How to export DataTable to PDF in ASP.NET

Author: Rachel Nicole
Download Source Code : 1336_ExportDataTableToPdf.zip

The purpose of this article is to explain how we can export DataTable to PDF file.

 

I will get data in DataTable object from Products table of NORTHWIND database and convert this DataTable data into PDF file. I will use third party library called iTextSharp. It is free and open source library available on internet. You can download it and add reference in your project.

  1. Open Visual Studio 2010
  2. File > New > Web Site
  3. Visual Basic or Visual C#  > ASP.NET Empty Web Site
  4. Right click on web site > Add New Item > Web Form
  5. Right click on web site > Add Reference > Browse > iTextSharp.dll
  6. Add a Button in Web Form

    <asp:Button ID="Button1" runat="server" Text="Export DataTable To PDF file"
                onclick="Button1_Click" />
     
  7. Open code behind file and include following namespaces
     
    C#
     
    using System.Data;
    using System.Data.SqlClient;
    using System.IO;
    using iTextSharp.text;
    using iTextSharp.text.html.simpleparser;
    using iTextSharp.text.pdf;
     
    VB.NET
     
    Imports System.Data
    Imports System.Data.SqlClient
    Imports System.IO
    Imports iTextSharp.text
    Imports iTextSharp.text.html.simpleparser
    Imports iTextSharp.text.pdf
     
  8. Write below function in code behind file to get data from NORTHWIND database

    C#
     
    protected DataTable GetProductsData()
    {
        string cmdText = "SELECT * FROM Products";
        string myConnection = "Data Source=Local;Initial Catalog=C:\\SQL SERVER 2000 SAMPLE DATABASES\\NORTHWND.MDF;Integrated Security=True";
        SqlConnection connection = new SqlConnection(myConnection);
        SqlCommand command = new SqlCommand(cmdText, connection);
        connection.Open();
        SqlDataAdapter da = new SqlDataAdapter(command);
        DataTable dt = new DataTable();
        da.Fill(dt);
        connection.Close();
        return dt;
    }
     
    VB.NET

    Protected Function GetProductsData() As DataTable
        Dim cmdText As String = "SELECT * FROM Products"
        Dim myConnection As String = "Data Source=Local;Initial Catalog=C:\SQL SERVER 2000 SAMPLE DATABASES\NORTHWND.MDF;Integrated Security=True"
        Dim connection As New SqlConnection(myConnection)
        Dim command As New SqlCommand(cmdText, connection)
        connection.Open()
        Dim da As New SqlDataAdapter(command)
        Dim dt As New DataTable()
        da.Fill(dt)
        connection.Close()
        Return dt
    End Function
     
    Here is the Explanation of above function
     
    I am using Products table in NORTHWIND database to get data.
    GetProductsData() function returns Datatable.
    Write query to get data from database table.
    Establish your connection to the server.
    Create SqlCommand object by passing query and SqlConnection object.
    Get data in SqlDataAdapter object.
    Create DataTable Object and fill DataTable.
    Return DataTable object.
     
  9. Write below function in code behind file to export DataTable to PDF file

    C#
     
    protected void ExportDataTableToPdf()
    {
        DataTable dt = GetProductsData();
     
        GridView GridView1 = new GridView();
        GridView1.DataSource = dt;
        GridView1.DataBind();
     
        Response.Clear();
        Response.Buffer = true;
        Response.Charset = "";
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=Products.pdf");
        StringWriter sWriter = new StringWriter();
        HtmlTextWriter hTWriter = new HtmlTextWriter(sWriter);
        GridView1.RenderControl(hTWriter);
        StringReader sReader = new StringReader(sWriter.ToString());
        Document pdf = new Document(PageSize.A4);
        HTMLWorker worker = new HTMLWorker(pdf);
        PdfWriter.GetInstance(pdf, Response.OutputStream);
        pdf.Open();
        worker.Parse(sReader);
        pdf.Close();
        Response.Write(pdf);
        Response.Flush();
        Response.End();
    }
     
    Vb.NET

    Protected Sub ExportDataTableToPdf()
        Dim dt As DataTable = GetProductsData()
     
        Dim GridView1 As New GridView()
        GridView1.DataSource = dt
        GridView1.DataBind()
     
        Response.Clear()
        Response.Buffer = True
        Response.Charset = ""
        Response.ContentType = "application/pdf"
        Response.AddHeader("content-disposition", "attachment;filename=Products.pdf")
        Dim sWriter As New StringWriter()
        Dim hTWriter As New HtmlTextWriter(sWriter)
        GridView1.RenderControl(hTWriter)
        Dim sReader As New StringReader(sWriter.ToString())
        Dim pdf As New Document(PageSize.A4)
        Dim worker As New HTMLWorker(pdf)
        PdfWriter.GetInstance(pdf, Response.OutputStream)
        pdf.Open()
        worker.Parse(sReader)
        pdf.Close()
        Response.Write(pdf)
        Response.Flush()
        Response.End()
    End Sub
     
    Here is the explanation of the above function.
     
    Call GetProductsData() function and assign data to a DataTable object.
    I am creating a GridView control to bind DataTable to it.
    First clear all content output from buffer stream.
    Set Buffer property of Response object to “True” so that it buffer output and send it after complete response processing.
    Set the Charset property to empty.
    Set the ContentType property of Response object for PDF.
    Call the AddHeader() method of Response object.
    Create a StringWrite object. Now create HtmlTexWrite object by passing StringWriter object as parameter. HtmlTexWrite object writes text to ASP.NET Server control output stream.
    Now call the RenderControl() method of the server control which outputs the content of server control to provided HtmlTextWriter object.
    Create a Document object by defining page size.
    Create a HTMLWorker object by providing document object.
    Call the GetInstance() method of PdfWrite class by providing Document and OutputSream as parameters
    Open Document, call the Parse() method of HTMLWorker object and close document.
    Call the Write() method of Response object by providing Document object.
    Flush() method will send all currently buffered output to the client.
    End() method will stop execution. 
     
  10. Write Button click event to call function

    C#
     
    protected void Button1_Click(object sender, EventArgs e)
    {
        ExportDataTableToPdf();
    }
     
    VB.NET
     
    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As EventArgs) Handles Button1.Load
        ExportDataTableToPdf()
    End Sub
     
  11. View web site in browser
   
Add Article Comment:
Name :
Email Address :
   
Comments :
 
   
<< Exception handling in ASP.NET

Disclaimer - Privacy
© 2002-2017 DevASP.net