Wednesday, March 21, 2012

Export Grid view Data to PDf file


In Asp.net we don’t  have the direct feature export to pdf  from grid view that is the reason we will use the third party tool Itext sharp reference to export the pdf file.First we need to download the dll from ITextSharp . Once you download is completed go to the solution explorer and right click the reference and add the Itext dll as a reference.
Now design the aspx Webpage as follows :

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div  >
<table>
<tr>
<td align="right">
<asp:ImageButton ID="btnPDF" runat="server" ImageUrl="~/adobe_pdf_icon.png" Width="32px"
Height="32px" onclick="btnPDF_Click"/>
</td>
</tr>
<tr>
<td>

<asp:GridView runat="server" ID="GvEmpdetails"  AllowPaging="true" AllowSorting="true" AutoGenerateColumns="false">
<RowStyle BackColor="#EFF3FB" />
<FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" />
<HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" />
<AlternatingRowStyle BackColor="White" />
<Columns>
<asp:BoundField DataField="EmpId" HeaderText="EmpId" />
<asp:BoundField DataField="Name" HeaderText="Name" />
<asp:BoundField DataField="Salary" HeaderText="Salary" />

</Columns>
</asp:GridView>

</td>
</tr>
</table>

</div>
</form>
</body>
</html>
Now in code behind add these references
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;

After that write the following code in code behind.1) bind the data to grid view in the Page_load and 2)  write the code  in the btnpdf click
DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            string connetion = ConfigurationManager.ConnectionStrings["Bloggerconnection"].ToString();
            //creating connetion object
            SqlConnection con = new SqlConnection(connetion);
            //DCreating data adapter object and connecting to database
            SqlDataAdapter da = new SqlDataAdapter("select * from [Practice].[dbo].[Tbl_Employee]", con);
           
            //fill the Dataresult of data adpter in to the datatable
            da.Fill(dt);
            GvEmpdetails.DataSource = dt;
            GvEmpdetails.DataBind();
          
        }


        protected void btnPDF_Click(object sender, ImageClickEventArgs e)
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment;filename=UserDetails.pdf");
            Response.Cache.SetCacheability(HttpCacheability.NoCache);
            StringWriter sw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(sw);
            GvEmpdetails.AllowPaging = false;
            GvEmpdetails.DataSource = dt;
            GvEmpdetails.DataBind();
            GvEmpdetails.RenderControl(hw);
            GvEmpdetails.HeaderRow.Style.Add("width", "15%");
            GvEmpdetails.HeaderRow.Style.Add("font-size", "10px");
            GvEmpdetails.Style.Add("text-decoration", "none");
            GvEmpdetails.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
            GvEmpdetails.Style.Add("font-size", "8px");
            StringReader sr = new StringReader(sw.ToString());
            Document pdfDoc = new Document(PageSize.A2, 7f, 7f, 7f, 0f);
            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
            pdfDoc.Open();
            htmlparser.Parse(sr);
            pdfDoc.Close();
            Response.Write(pdfDoc);
            Response.End();
        }

        public override void VerifyRenderingInServerForm(Control control) { }

If you observe above last method of code added one function that is VerifyRenderingInServerForm this function is used to avoid the error like “control must be placed in inside of form tag”. If we set VerifyRenderingInServerForm function then compiler will think that controls rendered before exporting and our functionality will work perfectly

 Output :

1 comment:

  1. C# for exporting GridView to PDF document using the GridView control,
    ExportToPdf exporter = new ExportToPdf(this.ketticGridView1);

    ReplyDelete