How to Convert GridView Data in to PDF File

Self-Innovator
Posted by in ASP.NET category on for Beginner level | Points: 250 | Views : 8151 red flag

This article explains on how content from grid view an be converted in to a PDF file.

Introduction


In previous article, we looked at converting the content of a grid view to HTML table similarly now we will look into how the content of a grid view can be convert it to an PDF file.

Objective


This article gives a brief description on how content of a grid view can be converted to a PDF file.In most of the applications the users may have a project / client's requirement to convert grid in to excel or grid to word or grid to PDF.


Using the code


In the example below, we have used one check box list control with multiple options for users.Ex: Listing out the users personal info or contact info and one button control to convert content of grids  in to PDF format.

Before getting in to the topic i would like to provide an basic things which are necessary / required in order to make a conversion of grid view data in to PDF file which uses some third party (.dll files) and it's associated namespaces are required.

Converting the gird view data in to PDF file requires an itextSharp.dll (dynamic link library) file in order to make a conversion. This dll file can be downloaded from the below link
http://sourceforge.net/projects/itextsharp/

Table Design





NameSpaces

The below are the necessary namespaces required for an PDF application
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Text;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
using System.Drawing;
Db Connection String

The below line specifies the connection string to the database
 string Conn = ConfigurationManager.ConnectionStrings["MyDBConnection"].ConnectionString;
Global Variables

The below line specifies some required global variables
DataSet ds = new DataSet();
string Body;
bool flag;
Check Box List Selected Change Event

The below event will pop up the data of the users in a grid view format according to the  users choice which uses some user defined methods
 protected void chkContactDetails_SelectedIndexChanged(object sender, EventArgs e)
{
for (int i = 0; i < chkContactDetails.Items.Count; i++)
{
if (chkContactDetails.Items[i].Selected == true)
{
if (chkContactDetails.Items[i].Text == "Contact Details")
{
CntDetailsToPDF();
}
else if (chkContactDetails.Items[i].Text == "Personal Details")
{
PersDetailsToPDF();
}
}
else if (chkContactDetails.Items[i].Selected == false)
{
if (chkContactDetails.Items[i].Text == "Contact Details")
{
grdCntDetails.Visible = false;
}
else if (chkContactDetails.Items[i].Text == "Personal Details")
{
grdPersDetails.Visible = false;
}
}
}
}
User Defined Methods

The below are two user defined methods to pop up the data of the users and returns it as a data set which is then assigning it to a grid view. Users Contact Details and Personal Details
 protected DataSet CntDetailsToPDF()
{
try
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tbl_ConactDetails", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grdCntDetails.Visible = true;
grdCntDetails.DataSource = ds;
grdCntDetails.DataBind();
}
else
{
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return ds;
}
protected DataSet PersDetailsToPDF()
{
try
{
SqlConnection cnn = new SqlConnection(Conn);
SqlCommand cmd = new SqlCommand("select * from tbl_PersonalDetails", cnn);
SqlDataAdapter ada = new SqlDataAdapter(cmd);
if (ds != null)
{
ds = new DataSet();
}
ada.Fill(ds);
if (ds.Tables[0].Rows.Count > 0)
{
grdPersDetails.Visible = true;
grdPersDetails.DataSource = ds;
grdPersDetails.DataBind();
}
else
{
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
return ds;
}
Button Click Event

The below event will fire an user defined method to generate the PDF file with the content of a grid view. It call the  function fn_AttachToPDF.
protected void btnConvert_Click(object sender, EventArgs e)
{
for (int i = 0; i < chkContactDetails.Items.Count; i++)
{
if (chkContactDetails.Items[i].Selected == true)
{
flag = true;
break;
}
else
{
flag = false;
}
}
if (flag)
{
string PDF = fn_AttachToPDF();
PDF += "<br>Regards,<br> Admin";
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=ProfileDetails.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter();
StringReader sr = new StringReader(PDF.ToString());
sw.GetStringBuilder().ToString();
HtmlTextWriter hw = new HtmlTextWriter(sw);
grdCntDetails.RenderControl(hw);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0f);
HTMLWorker htmlParser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
pdfDoc.Open();
htmlParser.Parse(sr);
pdfDoc.Close();
Response.Write(pdfDoc);
Response.End();
}
else
{
ClientScript.RegisterStartupScript(this.GetType(), "Alert", "alert('Choose any contact details');", true);
}
}
fn_AttachToPDF

The below is the function which generates populates the data set of an users selected option.
 public string fn_AttachToPDF()
{
for (int i = 0; i < chkContactDetails.Items.Count; i++)
{
if (chkContactDetails.Items[i].Selected == true)
{
if (chkContactDetails.Items[i].Text == "Contact Details")
{
Body += ContactDtlsToPDF(grdCntDetails);
}
else if (chkContactDetails.Items[i].Text == "Personal Details")
{
Body += PersDtlsToPDF(grdPersDetails);
}
}
}
return Body;
}
User Defined Methods-ContactDtlsToPDF,PersDtlsToPDF
The below is the function which generates populates the data set of an users with his/her personal and contact details info.
private string ContactDtlsToPDF(GridView grdC)
{
ds = CntDetailsToPDF();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Body += ds.Tables[0].Rows[i]["Name"].ToString() + " " + ds.Tables[0].Rows[i]["Mobile"].ToString() + "<br/>";
}
return Body;
}
private string PersDtlsToPDF(GridView grdC)
{
ds=PersDetailsToPDF();
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
Body += ds.Tables[0].Rows[i]["Name"].ToString() + " " + ds.Tables[0].Rows[i]["Email"].ToString() + "<br/>";
}
return Body;
}
Required Render Method

The below method ensure the control is rendered with in a form tag.
 public override void VerifyRenderingInServerForm(Control control)
{
//Confirms that an HtmlForm control is rendered for the specified ASP.NET server control at run time.
}

Conclusion

By this article any users can implement the functionality of PDF generation in their web applications.

Screen Shots


Page copy protected against web site content infringement by Copyscape

About the Author

Self-Innovator
Full Name: Sayeed Ahmed
Member Level: Bronze
Member Status: Member
Member Since: 12/22/2011 7:45:35 AM
Country: India
Join Hands Change lives Thanks & Regards Straight Edge Society


Login to vote for this post.

Comments or Responses

Login to post response

Comment using Facebook(Author doesn't get notification)