Wednesday, August 29, 2012

Export gridview data to PDF using asp.net using C#

Here i will explain How to Export Gridview Data To PDF using ITextSharp. While Exporting I will explain the problems how to solve them. First download the ItextSharp from the above link.

Here i am binding Gridview In the Page_Load event



Out Put :






 ASPX Page :


<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true"
    CodeBehind="Default.aspx.cs" Inherits="ExpGvDataToPDF._Default" %>

<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
    <center>  
       <asp:Button ID="btnExport" runat="server" Text="Export To PDF" OnClick="btnExport_Click"/>
       <br />
       <br />
       <asp:GridView ID="ExpGvToPDFControl" runat="server" AllowPaging="True"                   AutoGenerateColumns="false" BackColor="White" BorderColor="#CC9966" BorderStyle="None"        BorderWidth="1px" CellPadding="4" onpageindexchanging="ExpGvToPDFControl_PageIndexChanging">
            <Columns>
            <asp:BoundField DataField="empid" HeaderText="EmpID" />
            <asp:BoundField DataField="fname" HeaderText="FirstName" />
            <asp:BoundField DataField="lname" HeaderText="LastName" />
            <asp:BoundField DataField="qualification" HeaderText="Qualifi" />
            <asp:BoundField DataField="designation" HeaderText="Designa" />
            <asp:BoundField DataField="sal" HeaderText="Salary" />
            <asp:BoundField DataField="DeptID" HeaderText="DeptID" />
            <asp:BoundField DataField="empmail" HeaderText="MailID" />
            </Columns>
           <FooterStyle BackColor="#FFFFCC" ForeColor="#330099" />
           <HeaderStyle BackColor="#990000" Font-Bold="True" ForeColor="#FFFFCC" />
           <PagerStyle BackColor="#FFFFCC" ForeColor="#330099" HorizontalAlign="Center" />
           <RowStyle BackColor="White" ForeColor="#330099" />
           <SelectedRowStyle BackColor="#FFCC66" Font-Bold="True" ForeColor="#663399" />
           <SortedAscendingCellStyle BackColor="#FEFCEB" />
           <SortedAscendingHeaderStyle BackColor="#AF0101" />
           <SortedDescendingCellStyle BackColor="#F6F0C0" />
           <SortedDescendingHeaderStyle BackColor="#7E0000" />
       </asp:GridView>  
   </center>
</asp:Content>


Code Behind File :

using iTextSharp.text;
using iTextSharp.text.pdf;

namespace ExpGvDataToPDF
{
    public partial class _Default : System.Web.UI.Page
    {
        private string constring =                   ConfigurationManager.ConnectionStrings["myconstring"].ConnectionString;
        SqlDataAdapter da;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                BindGrid();
            }
        }
       
        private void BindGrid()
        {
            try
            {
                DataSet ds = new DataSet();
                da = new SqlDataAdapter("select * from EMPTable", constring);
                da.Fill(ds, "GetEmpInfo");
                ExpGvToPDFControl.DataSource = ds.Tables[0];
                ExpGvToPDFControl.DataBind();
            }
            catch (Exception ex)
            {
                string ErrMsg = ex.Message;
            }  
        }

        protected void btnExport_Click(object sender, EventArgs e)
        {
            try
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition",
                                        "attachment;filename=EmpDetails.pdf");
                Response.Cache.SetCacheability(HttpCacheability.NoCache);
                StringWriter sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                ExpGvToPDFControl.AllowPaging = false;               
                BindGrid();
                ExpGvToPDFControl.RenderControl(hw);
                ExpGvToPDFControl.HeaderRow.Style.Add("width", "15%");
                ExpGvToPDFControl.HeaderRow.Style.Add("font-size", "10px");
                ExpGvToPDFControl.Style.Add("text-decoration", "none");
                ExpGvToPDFControl.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
                ExpGvToPDFControl.Style.Add("font-size", "8px");
                StringReader sr = new StringReader(sw.ToString());
                iTextSharp.text.Document pdfDoc =
              new iTextSharp.text.Document(PageSize.A4, 7f, 7f, 7f, 0f);
                iTextSharp.text.html.simpleparser.HTMLWorker htmlparser = new
              iTextSharp.text.html.simpleparser.HTMLWorker(pdfDoc);
                PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
                pdfDoc.Open();
                htmlparser.Parse(sr);
                pdfDoc.Close();
                Response.Write(pdfDoc);
                Response.End();
            }
            catch (Exception ex)
            {
                string ErrMsg = ex.Message;
            }
        }

        public override void VerifyRenderingInServerForm(Control control)
        {
            // verifies the control is rendered here
        }

        protected void ExpGvToPDFControl_PageIndexChanging(object sender,
                                  System.Web.UI.WebControls.GridViewPageEventArgs e)
        {
            ExpGvToPDFControl.PageIndex = e.NewPageIndex;
            BindGrid();
        }
    }
}

Errors 1 :

Control 'MainContent_ExpGvToPDFControl' of type 'GridView' must be placed inside a form tag with runat=server.





        
       public override void VerifyRenderingInServerForm(Control control)
        {
            // verifies the control is rendered here
        }

 Errors 2 :

The document has no pages.

  for the above error Bind the grid again with BindGrid(); Method

 

Some times it is required to show Heading In PDF so

  to add multiple headers to gridview GoHear

 

Download

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

  

2 comments :

  1. Why should we again apply the styles and Background to Gridview for PDF Export

    ReplyDelete
  2. Ok...but the PDF that is created is only for the first of three pages. How to generate PDF of *all three* pages???

    ReplyDelete