Step 1: Download code and add Referance
of itextsharp.dll to your Project.
Step 2: Add Default.aspx Page with following aspx code.
<%@
Page Language="C#"
AutoEventWireup="true"
CodeFile="Default.aspx.cs"
Inherits="_Default"
%>
<!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
id="Head1"
runat="server">
<title></title>
</head>
<body>
<form id="form1"
runat="server">
<div>
<asp:GridView
ID="GridView1"
runat="server"
BackColor="White"
BorderColor="#3366CC"
BorderStyle="None"
BorderWidth="1px"
CellPadding="4"
EnableModelValidation="True">
<FooterStyle
BackColor="#99CCCC"
ForeColor="#003399"
/>
<HeaderStyle
BackColor="#003399"
Font-Bold="True"
ForeColor="#CCCCFF"
/>
<PagerStyle
BackColor="#99CCCC"
ForeColor="#003399"
HorizontalAlign="Left"
/>
<RowStyle
BackColor="White"
ForeColor="#003399"
/>
<SelectedRowStyle
BackColor="#009999"
Font-Bold="True"
ForeColor="#CCFF99"
/>
</asp:GridView>
<asp:Button
ID="Button1"
runat="server"
onclick="Button1_Click"
Text="export to pdf"
/>
</div>
</form>
</body>
</html>
Step 3: .cs file
using
System;
using
System.Collections.Generic;
using
System.Linq;
using
System.Web;
using
System.Web.UI;
using
System.Web.UI.WebControls;
using
System.Diagnostics;
using
System.Data;
using
System.Data.SqlClient;
using
System.IO;
using
iTextSharp.text;
using
iTextSharp.text.pdf;
using
iTextSharp.text.html;
using
iTextSharp.text.html.simpleparser;
using
System.Drawing;
public
partial class
_Default : System.Web.UI.Page
{
public static
SqlConnection conn = new
SqlConnection(@"server=.\SQL;User
Id=sa;Password=Password;Initial Catalog=pankaj");
protected void Page_Load(object
sender, EventArgs e)
{
if (!Page.IsPostBack)
{
// GridView GridView1 = new GridView();
GridView1.AllowPaging = false;
GridView1.DataSource = GetTable();
GridView1.DataBind();
}
}
static DataTable GetTable()
{
DataTable table =
new DataTable();
SqlCommand cmd = new
SqlCommand("select
* from User_Login", conn);
SqlDataAdapter da =
new SqlDataAdapter(cmd);
da.Fill(table);
return table;
}
protected void Button1_Click(object
sender, EventArgs e)
{
GridView GridView2 =
new GridView();
GridView2.AllowPaging
= false;
GridView2.HeaderStyle.BackColor = System.Drawing.Color.Magenta;
GridView2.DataSource
= GetTable();
GridView2.DataBind();
Response.ContentType
= "application/pdf";
Response.AddHeader("content-disposition",
"attachment;filename=User.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw =
new StringWriter();
HtmlTextWriter hw =
new HtmlTextWriter(sw);
GridView2.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();
}
}
For more find the attached code.