Monday, June 2, 2014

Export Gridview to pdf C#

Step1 : Download itextsharp.dll and paste at bin folder





<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="CS.aspx.cs" Inherits="_Default" %>





    GridView Export To PDF

   

   

            AutoGenerateColumns = "true" Font-Names = "Arial"
        Font-Size = "11pt" AlternatingRowStyle-BackColor = "#C2D69B"
        HeaderStyle-BackColor = "green" AllowPaging ="false"  
        OnPageIndexChanging = "OnPaging" >
     
   

   
     
     
   







using System;
using System.Configuration;
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.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.Text;


public partial class _Default : System.Web.UI.Page
{
    int grdvCount = 0;

    protected void Page_Load(object sender, EventArgs e)
    {
        //String strConnString = ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString;

        //SqlConnection strConnString = new SqlConnection(ConnectionString);
        SqlConnection con = new SqlConnection(ConnectionString);
        SqlCommand cmd = new SqlCommand();
        SqlDataAdapter sda = new SqlDataAdapter();
        DataSet ds = new DataSet();
        cmd.CommandType = CommandType.Text;
        cmd.CommandText = "SP_Plan_ErrorReport_FFSData";
        cmd.Connection = con;
        sda.SelectCommand = cmd;
        try
        {
            con.Open();
            sda.Fill(ds);
            GridView1.EmptyDataText = "No Records Found";
            GridView1.DataSource = ds;
            GridView1.DataBind();
            grdvCount=GridView1.Rows[0].Cells.Count;
            //Response.Write(GridView1.Rows[0].Cells.Count);
          // Response.End();

         
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            con.Close();
            con.Dispose();
        }
    }
    protected void btnExportPDF_Click(object sender, EventArgs e)
    {
        //GridView1.AllowPaging = Convert.ToBoolean(rbPaging.SelectedItem.Value);
        GridView1.DataBind();

         //Create a table
        iTextSharp.text.Table table = new iTextSharp.text.Table(grdvCount);
        table.Cellpadding = 5;

        //Set the column widths
        Response.Write(grdvCount);
       // Response.End();


        int[] widths = new int[grdvCount];
        for (int x = 0; x < grdvCount; x++)
        {
            widths[x] = 2500;
            //Response.Write(widths[x]);
            //Response.End();

            string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);
            iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);
            //cell.BackgroundColor = new Color (System.Drawing.ColorTranslator.FromHtml("#008000"));
            //light blue


            cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("#536895"));
           

            table.AddCell(cell);
        }
        table.SetWidths(widths);

        //Transfer rows from GridView to table
        for (int i = 0; i < GridView1.Rows.Count; i++)
        {
            if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
            {
                for (int j = 0; j < grdvCount; j++)
                {
                    string cellText = Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text);
                    iTextSharp.text.Cell cell = new iTextSharp.text.Cell(cellText);

                    //Set Color of Alternating row
                    if (i % 2 != 0)
                    {
                        cell.BackgroundColor = new Color(System.Drawing.ColorTranslator.FromHtml("LightBlue"));
                    }
                    table.AddCell(cell);
                }
            }
        }

        //Create the PDF Document
        Document pdfDoc = new Document(PageSize.A0, 10f, 10f, 10f, 0f);
        PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
        pdfDoc.Open();
        pdfDoc.Add(table);
        pdfDoc.Close();
        Response.ContentType = "application/pdf";
        Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
        Response.Cache.SetCacheability(HttpCacheability.NoCache);
        Response.Write(pdfDoc);
        Response.End();
    }
    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }
    protected void OnPaging(object sender, GridViewPageEventArgs e)
    {
        GridView1.PageIndex = e.NewPageIndex;
        GridView1.DataBind();
    }


    private string ConnectionString
    {
        get
        {
            string connectionString = ConfigurationManager.ConnectionStrings["ConnectionString1"].ConnectionString;
            return connectionString;
        }
    }
}

No comments: