Monday, May 6, 2013

how to export gridview data to pdf in

Title: How to export grid view data to PDF in

Most the report are send to customers as in excel format.But some scenarios they might ask PDF format.

Earlier we learned how to export grid view data to word document,Import excel data to SQL Server.In this post i will show how to export grid view data to PDF file in exporting to pdf i have created a pdf document with desired size .Then conversion has done using HTML parser
Note:itextsharp tool has been we need add those DLL into our application
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ExportToPDF.aspx.cs" Inherits="_ExportToPDF" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
<html xmlns="" >
<head runat="server">
<title>Export Gridview To PDF documnet</title>
<form id="form1" runat="server">
<asp:GridView ID="GvExportDetails" runat="server"
AutoGenerateColumns="False" DataSourceID="SqlDataSource1" EnableModelValidation="True"
<asp:BoundField DataField="ExportOrderID"
                 HeaderText="ExportOrderID" SortExpression="ExportOrderID"/>
<asp:BoundField DataField="ExportOrderName"
                HeaderText="ExportOrderName" SortExpression="ExportOrderName"/>
<asp:BoundField DataField="ExportPhone" HeaderText="ExportPhone" SortExpression="ExportPhone" />
<asp:BoundField DataField="ExportAddress" HeaderText="ExportAddress" SortExpression="ExportAddress" />
<asp:BoundField DataField="ExportAmount" HeaderText="ExportAmount" SortExpression="ExportAmount" />
<asp:SqlDataSource ID="SqlDataSource1" runat="server"
ConnectionString="<%$ ConnectionStrings:TestConnectionString %>"
SelectCommand="SELECT * FROM [Orders]"></asp:SqlDataSource>
<asp:Button ID="btnExportOrdersToPdf" runat="server"
             Text="OrderDetails to PDF" />
Code behind:
using System;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.HtmlControls;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

public partial class _ExportToPDF : System.Web.UI.Page 
protected void Page_Load(object sender, EventArgs e)
protected void btnExportOrdersToPdf_Click(object sender, EventArgs e)
Response.AddHeader("content-disposition", "attachment; filename=OrderDetailsReport.pdf");
Response.Charset = string.Empty;
Response.ContentType = "application/vnd.pdf";
StringWriter swr = new StringWriter();
HtmlTextWriter hwr = new HtmlTextWriter(swr);
StringReader srd = new StringReader(swr.ToString());
Document OrderDetialsReport = new Document(PageSize.A1, 12f, 12f, 12f, 10f);
HTMLWorker _htmlparser = new HTMLWorker(OrderDetialsReport);
PdfWriter.GetInstance(OrderDetialsReport, Response.OutputStream);
public override void VerifyRenderingInServerForm(Control control)
Note:Errors might be come like "registerforeventvalidation can only be called during render"
Post a Comment