How to export gridview to pdf in asp.net? - CodingPot | Programming Blog - ASP.NET, C#, VB.NET, AngularJs, SQL Server, AJAX, JQuery Tutorials.

Friday 11 May 2018

How to export gridview to pdf in asp.net?

Hello guys, today we will learn “Export gridview to pdf in asp.net”. We will discuss some handful of techniques to export the gridview data to pdf file. In day to day application development, it’s most common task to get the report in the pdf format. Because of the user can easily download and print the generated report. In asp.net we don’t have any features to directly export the gridview data to PDF. So for this limitation here we will use third party library “ITextSharp” reference. The library file is download from here ITextSharp. First,download the library file from this site and then you are ready to create a new website in visual studio and add ITextSharp library and create your report.
How to export gridview to pdf in asp.net

Step 1: Open visual studio and create new empty project using C# language and select Framework, You can select the latest version of framework.

Step 2: In empty created project built in files and folders are automatically created like scripts folder, Web.config, package.config, etc files. For creating view file we should create “.aspx” file. So first we will create a new folder. Right-click on the project and choose to add option and select “New Folder” and give the name of “view”. After creating a view folder, right click on view folder and select Add option and then select “New Item”. The Add New Item Dialog is open you can see left side “Web” option is available so click on that option or expand the “Web” option then select “WebForm” option and give the name of page and click on Add button.

Step 3: Now we will add the Gridview control on the page to show List of records for bind data, first of all, we should create Database and table. You can create your database in visual studio using server explorer or create the database using SQL Server I have SQL server so I am using SQL if you don’t have SQL then you can create Database in another Database server.

Step 4: Create Database (“Example”) in SQL Server and create the new table of “tbl_employee”. After a table is created then insert manually data in this table or you can create insert functionality in an application. After inserting the data in a table we will bind the data in grid view.

ExportToPdf.aspx


<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="ExportToPdf.aspx.cs" Inherits="ExportGridViewToPdf.Views.ExportToPdf" %> <! DOCTYPE html> <html xmlns="https://www.w3.org/1999/xhtml"> <head runat="server"> <title>Export Gridview to Pdf</title> </head> <body> <form id="form1" runat="server"> <div> <asp: GridView ID="GridView1" runat="server" BackColor="#DEBA84" BorderColor="#DEBA84" BorderStyle="None" BorderWidth="1px" CellPadding="3" CellSpacing="2"> <FooterStyle BackColor="#F7DFB5" ForeColor="#8C4510" /> <HeaderStyle BackColor="#A55129" Font-Bold="True" ForeColor="White" /> <PagerStyle ForeColor="#8C4510" HorizontalAlign="Center" /> <RowStyle BackColor="#FFF7E7" ForeColor="#8C4510" /> <SelectedRowStyle BackColor="#738A9C" Font-Bold="True" ForeColor="White" /> <SortedAscendingCellStyle BackColor="#FFF1D4" /> <SortedAscendingHeaderStyle BackColor="#B95C30" /> <SortedDescendingCellStyle BackColor="#F1E5CE" /> <SortedDescendingHeaderStyle BackColor="#93451F" /> </asp:GridView> <br /> <asp:Button ID="Button1" runat="server" Font-Bold="True" OnClick="Button1_Click1" Text="Export To Pdf" /> </div> </form> </body> </html>
Step 5: The gridview is added now it’s time to bind data in Gridview using code behind or click on a mini icon on right top of gridview and choose a new data source and select your SQL Database and select the table which table data want to bind in gridview. We bind the data in gridview using code let’s see the code to bind gridview data.

protected void Page_Load(object sender, EventArgs e) { //Database connectionstring........ string connect = "Data Source=Gautam-PC;Initial Catalog=Example;Integrated Security=True"; if (!IsPostBack) { using (SqlConnection con = new SqlConnection(connect)) { SqlDataAdapter da = new SqlDataAdapter("select * from tbl_employee", con); DataSet ds = new DataSet(); da.Fill(ds); //.....Bind data in Gridview List.... GridView1.DataSource = ds; GridView1.DataBind (); } } }
Above we written the gridview bind data in the page_load event, set the connection string to connect Database then check page is not “IsPostBack” then written the select query using SqlDataAdapter class then fill the SqlDataAdapter object in the Dataset and set the Data source to Gridview and Databind to gridview.

Step 6: Run the application, you can see the data display in Gridview. If you want to design the proper gridview like background color, font size and color heading style and etc. now add the button at bottom of gridview. On click this button we write the code for export gridview to Pdf. Generate click event at the code behind and write the code for Export gridview to Pdf.

protected void Button1_Click1(object sender, EventArgs e) { PdfPTable pdfTable = new PdfPTable(GridView1.HeaderRow.Cells.Count); foreach (TableCell headerCell in GridView1.HeaderRow.Cells) { //...set font color in header row... Font font = new Font(); font.Color = new BaseColor(GridView1.HeaderStyle.ForeColor); PdfPCell pdfCell = new PdfPCell(new Phrase(headerCell.Text, font)); //...set background color in header row... pdfCell.BackgroundColor = new BaseColor(GridView1.HeaderStyle.BackColor); pdfTable.AddCell(pdfCell); } foreach (GridViewRow gridviewrow in GridView1.Rows) { foreach (TableCell tablecell in gridviewrow.Cells) { //...set font color in table cell... Font font = new Font(); font.Color = new BaseColor(GridView1.RowStyle.ForeColor); PdfPCell pdfCell = new PdfPCell(new Phrase(tablecell.Text)); //...set background color of table... pdfCell.BackgroundColor = new BaseColor(GridView1.RowStyle.BackColor); pdfTable.AddCell(pdfCell); } } //...create pdf document... Document pdfDocument = new Document(PageSize.A4, 10f, 10f, 10f, 10f); PdfWriter.GetInstance(pdfDocument, Response.OutputStream); pdfDocument.Open(); pdfDocument.Add(pdfTable); pdfDocument.Close(); Response.ContentType = "application/pdf"; //...set name of pdf document... Response.AddHeader("content-disposition", "attachment;filename=Employee.pdf"); Response.Write(pdfDocument); Response.Flush(); Response.End(); }
In above code first, we create the PdfTable object based on Gridview HeaderRow Cells count. In first for each loop Based on Gridview header row cells, we have created the Header of pdfTable and set the header background color. In second for each loop, we create the table cells in pdfTable based on Gridview Rows and each row has multiple cells and bind the cells in pdfTable with font and Background color.

At the end of Pdftable creation set the size of the pdf file using Document class with a parameter. The parameters are margin left, right, top and bottom of the page then set the content Type “application/pdf” and give the name(Employee.pdf) of Pdf file in “AddHeader()” method then Write, Flush and End function.

Run your application, Gridview show your data and at the bottom of Gridview one button(“Export to Pdf”) is available, click on that button and see your exported gridview data in pdf.
Thanks a lot.


2 comments: