Saturday, June 29, 2013

How to Export Data of Datalist into Pdf in Asp.net using iTextSharp DLL

Introduction: In this post I will try to explain how we can export the data of Datalist to PDF in Asp.net.
Description:
In last article I have explain How to bind Datalist Controlin Asp.net. here I bind the datalist control using Sqldatasource. See below:
<form id="form1" runat="server">
    <div> <table border="1"><tr><td>
    <asp:DataList ID="dlstudent" runat="server" DataKeyField="STUDENT_ID" CellPadding="3"
            DataSourceID="SqlDataSource1">
            <HeaderStyle Font-Bold="True" BorderColor="Black" />                  
            <ItemTemplate>              
               <table><tr><td><b>Student Name</b> </td>
                <td><asp:Label ID="STUDENT_NAMELabel" runat="server"
                    Text='<%# Eval("STUDENT_NAME") %>' /></td></tr>
                <tr> <td><b>Student Address</b></td>
               <td><asp:Label ID="STUDENT_ADDRESSLabel" runat="server"
                    Text='<%# Eval("STUDENT_ADDRESS") %>' /></td> </tr>
                <tr><td><b>Student Class</b></td>
               <td><asp:Label ID="STUDENT_CLASSLabel" runat="server"
                    Text='<%# Eval("STUDENT_CLASS") %>' /></td> </tr></table>
            </ItemTemplate>       
                       </asp:DataList></td></tr></table>
        <asp:SqlDataSource ID="SqlDataSource1" runat="server"
            ConnectionString="<%$ ConnectionStrings:TestBlogConnectionString %>"
            SelectCommand="SELECT * FROM [STUDENT_DETAIL]"></asp:SqlDataSource>
        <br />
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="Export to Pdf" />
    </div>
    </form>


Now download the iTextsharp DLL. To download iTextsharp DLL Click Here.  After download it, put the DLL in Bin folder, build the project and use the namespace.
Now go to .aspx.cs page and write the below given code:

using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;

protected void Button1_Click(object sender, EventArgs e)
    {
        try
        {
            Response.ContentType = "application/pdf";
            Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.AddHeader("content-disposition", "attachment;filename=StudentDetails.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter writer = new StringWriter();
            HtmlTextWriter html = new HtmlTextWriter(writer);
            dlstudent.DataBind();
            dlstudent.RenderControl(html);
            StringReader sr = new StringReader(writer.ToString());
            Document pdf = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdf);
            PdfWriter.GetInstance(pdf, Response.OutputStream);
            pdf.Open();
            htmlparser.Parse(sr);
            pdf.Close();
            Response.Write(pdf);
            Response.End();
        }
        catch (Exception ex)
        {
        }
    }

In VB (.aspx.vb)

Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
Imports System.IO

Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        Try
            Response.ContentType = "application/pdf"
            Response.ContentEncoding = System.Text.Encoding.UTF8
            Response.AddHeader("content-disposition", "attachment;filename=StudentDetails.pdf")
            Response.Cache.SetCacheability(HttpCacheability.NoCache)
            Dim writer As New StringWriter()
            Dim html As New HtmlTextWriter(writer)
            dlstudent.DataBind()
            dlstudent.RenderControl(html)
            Dim sr As New StringReader(writer.ToString())
            Dim pdf As New Document(PageSize.A2, 7.0F, 7.0F, 7.0F, 0.0F)
            Dim htmlparser As New HTMLWorker(pdf)
            PdfWriter.GetInstance(pdf, Response.OutputStream)
            pdf.Open()
            htmlparser.Parse(sr)
            pdf.Close()
            Response.Write(pdf)
            Response.[End]()
        Catch ex As Exception
        End Try
    End Sub


Now build the project and check the result.

If you get any error "Control 'grdstudent' of type 'GridView' must be placed inside a form tag with runat=server" read this article:

http://articlemirror.blogspot.in/2013/07/control-grdstudent-of-type-gridview.html

Is it helpful?

If yes post your comment to admire my work. You can like me on Facebook, Google+, Linkedin and Twitter via hit on Follow us Button and also can get update follow by Email.

10 comments:

  1. Nice one vijay.waiting for more articles. :)

    ReplyDelete
  2. hi Vijay Saklani this not work in my PC

    ReplyDelete
    Replies
    1. The code is tested and its working properly... Can you tell me the error/problem that you are facing.

      Delete
  3. THIS CODE CAN NOT SOLED PROUBLOM BECOUSE DATA DONT LOD IN PDF

    ReplyDelete
  4. how i convert images inside datalist to pdf

    ReplyDelete
  5. How will i convert images inside datalist to pdf

    ReplyDelete
  6. i wille be create the pdf file but image and data can' be fatch\

    ReplyDelete
  7. Everything thing is working fine but nothing is being displayed in my pdf

    ReplyDelete
    Replies
    1. Code is working fine.. Can you share your code?

      Delete