How to Export Data in PDF using iTextSharp in Asp.Net


In this Example we will See How to Create Pdf File from Gridview or else database. For Export Data in Pdf file from Gridview we will use StringBuilder Controls to Save in Pdf file we will use Attachment in Code behind. So let’s start to Create Gridview Data from Database and Export in Pdf file through Code behind in dot net.

Step 1: Create you Table in Sql table and Name it “Employee”. And Fill Data in Table

CREATE TABLE [dbo].[Employee](
                [Number] [int] IDENTITY(1,1) NOT NULL,
                [Name] [varchar](50) NOT NULL,
                [Gender] [varchar](50) NOT NULL,
                [Email] [varchar](50) NOT NULL,
                [MobileNumber] [bigint] NOT NULL,
                [Bdate] [date] NULL,
 CONSTRAINT [PK_Employeee] PRIMARY KEY CLUSTERED
(
                [Number] ASC
)WITH (PAD_INDEX  = OFF, STATISTICS_NORECOMPUTE  = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS  = ON, ALLOW_PAGE_LOCKS  = ON) ON [PRIMARY]
) ON [PRIMARY]

GO

Step 2: Now Design you Webpage like below.

<div>
  <asp:GridView ID="GridView1" runat="server" BackColor="White" BorderColor="#336666"
            AutoGenerateColumns="False" BorderStyle="Double" BorderWidth="3px" CellPadding="4"
            GridLines="Horizontal" Width="1273px">
            <Columns>
                <asp:BoundField ItemStyle-Width="200px" DataField="Number" HeaderText="Number">
                    <ItemStyle Width="200px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField ItemStyle-Width="300px" DataField="Name" HeaderText="Name">
                    <ItemStyle Width="300px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField ItemStyle-Width="200px" DataField="Gender" HeaderText="Gender">
                    <ItemStyle Width="200px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField ItemStyle-Width="300px" DataField="Email" HeaderText="Email">
                    <ItemStyle Width="300px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField ItemStyle-Width="300px" DataField="MobileNumber" HeaderText="MobileNumber">
                    <ItemStyle Width="300px"></ItemStyle>
                </asp:BoundField>
                <asp:BoundField ItemStyle-Width="400px" DataField="BDate" HeaderText="Birth Date">
                    <ItemStyle Width="400px"></ItemStyle>
                </asp:BoundField>
            </Columns>
            <FooterStyle BackColor="White" ForeColor="#333333" />
            <HeaderStyle BackColor="#336666" Font-Bold="True" ForeColor="White" />
            <PagerStyle BackColor="#336666" ForeColor="White" HorizontalAlign="Center" />
            <RowStyle BackColor="White" ForeColor="#333333" />
            <SelectedRowStyle BackColor="#339966" Font-Bold="True" ForeColor="White" />
            <SortedAscendingCellStyle BackColor="#F7F7F7" />
            <SortedAscendingHeaderStyle BackColor="#487575" />
            <SortedDescendingCellStyle BackColor="#E5E5E5" />
            <SortedDescendingHeaderStyle BackColor="#275353" />
        </asp:GridView>
        <br />
<asp:Button ID="btnExportPDF" runat="server" Text="ExportToPDF" OnClick="btnExportPDF_Click" />
    </div>

Step 3: Now go to Code behind and we will code for Bind Data in Gridview. Get the Connection from Using Configuration Manager from Web.Config File.

string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;

Code for Bind Data in Gridview
string CS = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                binddata();
            }
        }
public void binddata()
        {
            SqlConnection con = new SqlConnection(CS);
            SqlCommand cmd = new SqlCommand();
            cmd.CommandText = "Select * from Employeee";
            cmd.Connection = con;
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            if (dt.Rows.Count > 0)
            {
                GridView1.DataSource = dt;
                if (GridView1.Columns.Count > 0)
                {
                    GridView1.DataBind();
                }
            }
        }
Now on Button click event Code for Creating Pdf File and For selecting Data from Gridview or else Database. 

protected void btnExportPDF_Click(object sender, EventArgs e)
        {
            binddata();
            GridView1.AllowPaging = false;
            GridView1.DataBind();
            BaseFont bf = BaseFont.CreateFont(Environment.GetEnvironmentVariable("windir") + @"\fonts\ArialUni.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
            iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count);
            int[] widths = new int[GridView1.Columns.Count];
            for (int x = 0; x < GridView1.Columns.Count; x++)
            {
                widths[x] = (int)GridView1.Columns[x].ItemStyle.Width.Value;
                string cellText = Server.HtmlDecode(GridView1.HeaderRow.Cells[x].Text);
                //Set Font and Font Color
                iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.NORMAL);
                font.Color = new Color(GridView1.HeaderStyle.ForeColor);
                iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
                //Set Header Row BackGround Color
                cell.BackgroundColor = new Color(GridView1.HeaderStyle.BackColor);
                table.AddCell(cell);
            }
            table.SetWidths(widths);
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                if (GridView1.Rows[i].RowType == DataControlRowType.DataRow)
                {
                    for (int j = 0; j < GridView1.Columns.Count; j++)
                    {
                        string cellText = Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text);
                        //Set Font and Font Color
                        iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.COURIER);
                        font.Color = new Color(GridView1.RowStyle.ForeColor);
                        iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(12, cellText, font));
                        //Set Color of row
                        if (i % 2 == 0)
                        {
                            //Set Row BackGround Color
                            cell.BackgroundColor = new Color(GridView1.RowStyle.BackColor);
                        }
                        table.AddCell(cell);
                    }
                }
            }
            //Create the PDF Document
            Document pdfDoc = new Document(PageSize.A4, 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();
        }
Now if you Want to Verify in your Webpage then you Can Override VerifyRenderingInServerForm() Method.

public override void VerifyRenderingInServerForm(Control control)
{
     /* Verifies that the control is rendered */
}

Now run your Code in webpage and see output.
 

Related Posts

Previous
Next Post »

Thanks for comments.....