Export GridView populated using jQuery AJAX to PDF using iTextSharp in ASP.Net

nsgawli
 
on Nov 24, 2014 03:08 AM
9157 Views

I am using ITextSharp to create a pdf. But when I am binding data to Gridview dynamically which was actually a result of ajax webmethod, its showing a blank PDF file. So how can I export dynamically binded data to GridView to PDF. Is there any other way to export dynamically binded gridview data to PDF? Thanks in advance..

 

 

Download FREE API for Word, Excel and PDF in ASP.Net: Download
Azim
 
on Nov 24, 2014 04:37 AM
on Nov 24, 2014 08:24 AM

Please refer this code

HTML

Add EnableEventValidation and ValidateRequest in page directive.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" ValidateRequest="false"
    Inherits="_Default" EnableEventValidation="false" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <style type="text/css">
        body
        {
            font-family: Arial;
            font-size: 10pt;
        }
    </style>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
    <script src="ASPSnippets_Pager.min.js" type="text/javascript"></script>
    <script type="text/javascript">
        $(function () {
            $.ajax({
                type: "POST",
                url: "CS.aspx/GetCustomers",
                data: '{}',
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: OnSuccess,
                failure: function (response) {
                    alert(response.d);
                },
                error: function (response) {
                    alert(response.d);
                }
            });

            $('[id*=btnExport]').click(function () {
                $('[id*=hdExportData]').val($("#divTable").html());
               // alert($("#divTable").html());
            });
        });

        function OnSuccess(response) {
            var xmlDoc = $.parseXML(response.d);
            var xml = $(xmlDoc);
            var customers = xml.find("Table");
            var row = $("[id*=gvCustomers] tr:last-child").clone(true);
            $("[id*=gvCustomers] tr").not($("[id*=gvCustomers] tr:first-child")).remove();
            $.each(customers, function () {
                var customer = $(this);
                $("td", row).eq(0).html($(this).find("CustomerId").text());
                $("td", row).eq(1).html($(this).find("Name").text());
                $("td", row).eq(2).html($(this).find("Country").text());
                $("[id*=gvCustomers]").append(row);
                row = $("[id*=gvCustomers] tr:last-child").clone(true);
            });
        }

        
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div id="divTable">
        <asp:GridView ID="gvCustomers" runat="server" AutoGenerateColumns="false" Font-Names="Arial"
            Font-Size="10pt" RowStyle-BackColor="#A1DCF2" HeaderStyle-BackColor="#3AC0F2"
            HeaderStyle-ForeColor="Black">
            <Columns>
                <asp:BoundField ItemStyle-Width="150px" DataField="CustomerId" HeaderText="CustomerId" />
                <asp:BoundField ItemStyle-Width="150px" DataField="Name" HeaderText="Name" />
                <asp:BoundField ItemStyle-Width="150px" DataField="Country" HeaderText="Country" />
            </Columns>
        </asp:GridView>
    </div>
    <br />
    <asp:HiddenField ID="hdExportData" runat="server" />
    <asp:Button ID="btnExport" Text="Export To Pdf" runat="server" OnClick="ExportPDF" />
    </form>
</body>
</html>

Namepace

using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.Web.Services;
using System.IO;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;

C#

protected void Page_Load(object sender, EventArgs e)
{
    if (!IsPostBack)
    {
        this.BindDummyRow();
    }
}

private void BindDummyRow()
{
    DataTable dummy = new DataTable();
    dummy.Columns.Add("CustomerID");
    dummy.Columns.Add("Name");
    dummy.Columns.Add("Country");
    dummy.Rows.Add();
    gvCustomers.DataSource = dummy;
    gvCustomers.DataBind();
}


[WebMethod]
public static string GetCustomers()
{
    string query = "SELECT * FROM Customers";
    SqlCommand cmd = new SqlCommand(query);
    return GetData(cmd).GetXml();
}
private static DataSet GetData(SqlCommand cmd)
{
    string strConnString = ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection con = new SqlConnection(strConnString))
    {
        using (SqlDataAdapter sda = new SqlDataAdapter())
        {
            cmd.Connection = con;
            sda.SelectCommand = cmd;
            using (DataSet ds = new DataSet())
            {
                sda.Fill(ds);
                return ds;

            }
        }
    }
}

protected void ExportPDF(object sender, EventArgs e)
{
    using (StringWriter sw = new StringWriter())
    {
        using (HtmlTextWriter hw = new HtmlTextWriter(sw))
        {

            StringBuilder sb = new StringBuilder();
            //hdExportData.RenderControl(hw);
            sb.Append(Request.Form[this.hdExportData.UniqueID]);

            StringReader sr = new StringReader(sb.ToString());
            Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();

            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            Response.Write(pdfDoc);
            Response.End();
        }
    }
}

public override void VerifyRenderingInServerForm(Control control)
{

    /* Verifies that the control is rendered */

}

Web.Config

If you are using .Net 4.0 Framework.

<system.web>
    <httpRuntime requestValidationMode = "2.0" />
    <compilation debug="true" targetFramework="4.0"/>
</system.web>
Database
I have made use of the following table Customers with the schema as follows.
I have already inserted few records in the table.
 
You can download database SQL from here.
GridView PDF