Today’s time PDF is playing one of the most important role
in our life. So whenever we develop any asp.net application on that case we
always face some situation where we needed to export our data in PDS format.
So in this article I will show you how you can export the GridView bind data in PDF format using third party control iTextsharp.
In my previous article I have shown you how you can Bind
DataGridView In Windows Application Using C#. Some of the other articles
are as follows JavaScript
Confirm Message From Code Behind in Asp.Net Using C#, How
to call javascript function from code behind Using C# in Asp.Net, Display
Alert Message on Page Load in MVC Application Using Javasscript.
So for this article first you needed to download the iTextsharplibrary. Download iTextsharp and extract the zip file. In this file you will
three dll files. So for completing the task add the reference of itextsharp-dll-core directory dll.
Now after this create a new asp.net application and add the
blow code in your .aspx page.
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="PDFExport.aspx.cs" Inherits="ProjectDemo_Asp.et.PDFExport"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Code to
Export GridView to PDF in Asp.Net Using C# and Vb.Net</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
BorderStyle="Solid" EmptyDataText="There are no data records to display.">
<Columns>
<asp:BoundField DataField="author_name" HeaderText="NAME" />
<asp:BoundField DataField="publisher_name" HeaderText="PUBLISHER NAME"
/>
<asp:BoundField DataField="publication_year" HeaderText="PUBLISH
YEAR" />
<asp:BoundField DataField="retail_price" HeaderText="PRICE" />
</Columns>
<HeaderStyle BackColor="#66CCFF" />
</asp:GridView>
<br />
<asp:Button ID="Button1" runat="server" onclick="Button1_Click"
Text="Export To PDF" />
</div>
</form>
</body>
</html>
|
Now we will go to code page and add the below code.
C#.Net
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.OleDb;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;//This name space present in
"itextsharp-dll-core"
namespace ProjectDemo_Asp.et
{
public partial class PDFExport : System.Web.UI.Page
{
public
string connectionstring = "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=|DataDirectory|\\bookstore.mdb;Persist Security Info=False;";
protected
void Page_Load(object
sender, EventArgs e)
{
if
(!IsPostBack)
{
DataTable
_objdt = new DataTable();
_objdt =
GetDataFromDataBase();
if
(_objdt.Rows.Count > 0)
{
GridView1.DataSource =
_objdt;
GridView1.DataBind();
}
}
}
/// <summary>
/// Function for binding retribing the data from database
/// </summary>
/// <returns></returns>
public
DataTable GetDataFromDataBase()
{
DataTable
_objdt = new DataTable();
string
querystring = "select * from Books;";
OleDbConnection
_objcon = new OleDbConnection(connectionstring);
OleDbDataAdapter
_objda = new OleDbDataAdapter(querystring,
_objcon);
_objcon.Open();
_objda.Fill(_objdt);
return
_objdt;
}
/// <summary>
/// Click event to export the grivview data into pdf format
/// </summary>
/// <param
name="sender"></param>
/// <param
name="e"></param>
protected
void Button1_Click(object
sender, EventArgs e)
{
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=report_grid.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
StringWriter
s_w = new StringWriter();
HtmlTextWriter
h_w = new HtmlTextWriter(s_w);
GridView1.AllowPaging = false;
/*binding
data to grid view*/
DataTable
_objdt = new DataTable();
_objdt = GetDataFromDataBase();
GridView1.DataSource = _objdt;
GridView1.DataBind();
GridView1.RenderControl(h_w);
GridView1.HeaderRow.Style.Add("width", "15%");
GridView1.HeaderRow.Style.Add("font-size", "10px");
GridView1.Style.Add("text-decoration", "none");
GridView1.Style.Add("font-family", "Arial, Helvetica, sans-serif;");
GridView1.Style.Add("font-size", "8px");
StringReader
sr = new StringReader(s_w.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)
{
/* Verifies that the control is rendered */
}
}
}
|
VB.Net
Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Web
Imports System.Web.UI
Imports System.Web.UI.WebControls
Imports System.Data
Imports System.Data.OleDb
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.text.html.simpleparser
'This name space present in "itextsharp-dll-core"
Namespace ProjectDemo_Asp.et
Partial Public Class PDFExport
Inherits
System.Web.UI.Page
Public
connectionstring As String
= "Provider=Microsoft.ACE.OLEDB.12.0;Data
Source=|DataDirectory|\bookstore.mdb;Persist Security Info=False;"
Protected
Sub Page_Load(ByVal
sender As Object,
ByVal e As
EventArgs)
If
Not IsPostBack Then
Dim
_objdt As New
DataTable()
_objdt =
GetDataFromDataBase()
If
_objdt.Rows.Count > 0 Then
GridView1.DataSource =
_objdt
GridView1.DataBind()
End
If
End
If
End Sub
'''
<summary>
'''
Function for binding retribing the data from database
'''
</summary>
'''
<returns></returns>
Public
Function GetDataFromDataBase() As DataTable
Dim
_objdt As New
DataTable()
Dim
querystring As String
= "select * from Books;"
Dim
_objcon As New
OleDbConnection(connectionstring)
Dim
_objda As New
OleDbDataAdapter(querystring, _objcon)
_objcon.Open()
_objda.Fill(_objdt)
Return
_objdt
End Function
'''
<summary>
''' Click
event to export the grivview data into pdf format
'''
</summary>
'''
<param name="sender"></param>
'''
<param name="e"></param>
Protected
Sub Button1_Click(ByVal
sender As Object,
ByVal e As
EventArgs)
Response.ContentType = "application/pdf"
Response.AddHeader("content-disposition", "attachment;filename=report_grid.pdf")
Response.Cache.SetCacheability(HttpCacheability.NoCache)
Dim
s_w As New
StringWriter()
Dim
h_w As New
HtmlTextWriter(s_w)
GridView1.AllowPaging = False
'binding
data to grid view
Dim
_objdt As New
DataTable()
_objdt = GetDataFromDataBase()
GridView1.DataSource = _objdt
GridView1.DataBind()
GridView1.RenderControl(h_w)
GridView1.HeaderRow.Style.Add("width", "15%")
GridView1.HeaderRow.Style.Add("font-size", "10px")
GridView1.Style.Add("text-decoration", "none")
GridView1.Style.Add("font-family", "Arial, Helvetica, sans-serif;")
GridView1.Style.Add("font-size", "8px")
Dim
sr As New
StringReader(s_w.ToString())
Dim
pdfDoc As New
Document(PageSize.A2, 7.0F, 7.0F, 7.0F, 0.0F)
Dim
htmlparser As New
HTMLWorker(pdfDoc)
PdfWriter.GetInstance(pdfDoc,
Response.OutputStream)
pdfDoc.Open()
htmlparser.Parse(sr)
pdfDoc.Close()
Response.Write(pdfDoc)
Response.[End]()
End Sub
Public
Overrides Sub
VerifyRenderingInServerForm(ByVal control As Control)
'
Verifies that the control is rendered
End Sub
End Class
End Namespace
|
Now run the application without adding the below mention
code function.
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered */
}
|
Click on export button, you will get below mention error.
DOWNLOAD
Dear Reader Please let me know you comment.
ReplyDeleteVery useful article on GridView to pdf
ReplyDeleteASP.Net Training in Chennai
Thanks for your comment.
DeleteThanks sir.,
ReplyDeletevery helpful for me. This explanation must be provided by microsoft ...
Thanks for you valuable comment.
DeleteReally useful and I am glad and appreciate that shared your valuable knowledge
ReplyDeleteIts always interesting to know about some different ideas
ReplyDeleteNice post with lot of information and it is very helpful..Thanks for sharing
ReplyDeleteExcellent post with useful information..And the combination of elements are very different and unique
ReplyDeleteThanks for your valuable comment. keep visiting
DeleteVery good write-up. I definitely appreciate this website. Continue the good work!
ReplyDeleteThanks for your valuable comment.
Deleteinteresting piece of information, I had come to know about your web-page from my friend pramod, jaipur,i have read atleast eight posts of yours by now, and let me tell you, your blog gives the best and the most interesting information. This is just the kind of information that i had been looking for, i'm already your rss reader now and i would regularly watch out for the new posts, once again hats off to you! Thanks a million once again.
ReplyDeleteThanks for your valuable comment.
Deletehttps://zulqarnainbharwana.com/celts/
ReplyDeleteINDIAN VISA PASSPORT CENTER has been offering its services like Indian Visa sevices, Indian passport services, OCI services Indian passport renewal services in usa. If you want to get these service then INDIAN VISA PASSPORT CENTER is the best platform.
ReplyDeletehttps://Indianvp.com/