Monday, October 12, 2009

Export To PDF using itextsharp.dll

//Download the itextsharp.dll from site. (Its free) and use this dll on your project using AddReferenace

1)Put a Gird view control and Button control on your aspx page like this

2) Import these name spaces on your code behind

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;

3)Final stap for export to pdf


using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Data.SqlClient;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
public partial class ExportToPDF : System.Web.UI.Page
{
SqlConnection cn=new SqlConnection(ConfigurationManager.ConnectionStrings["connStr"].ConnectionString);
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
protected void Page_Load(object sender, EventArgs e)
{
if(!IsPostBack)
{

BindGrid();
}
}
//function to Bind the Grid
protected void BindGrid()
{
ds=new DataSet();
cmd=new SqlCommand("Select * from UserRegistration",cn);
adp=new SqlDataAdapter(cmd);
adp.Fill(ds);
grdExportToPDF.DataSource=ds;
grdExportToPDF.DataBind();




}

//Function for export to pdf
protected void btnExport_Click(object sender, EventArgs e)
{
Random rnd=new Random();
string FileName=DateTime.Now.ToShortDateString()+"_"+rnd.Next().ToString()+".pdf";
Response.ContentType="application/pdf";
Response.AddHeader("content-disposition","attechment,FileName="+FileName+"");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter sw=new StringWriter();
HtmlTextWriter hw=new HtmlTextWriter(sw);
grdExportToPDF.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();
}
//This function is use to override your control
public override void VerifyRenderingInServerForm(Control control)

{

}
}

No comments:

Post a Comment