In this article I will explain with an example, how to export
GridView to
PDF and send
PDF file as email attachment in
ASP.Net using C# and VB.Net.
Download iTextSharp and XmlWorkerHelper Libraries
In order to install
iTextSharp and
XmlWorkerHelper library from
Nuget, please refer the following articles.
HTML Markup
The following HTML Markup consists of:
GridView – For displaying data.
Columns
The GridView consists of three BoundField columns.
Button – For sending exported
GridView in email attachment.
The Button has been assigned with a OnClick event handler.
<asp:GridView ID="gvCustomers" HeaderStyle-BackColor="#3AC0F2"
RowStyle-BackColor="#A1DCF2" AlternatingRowStyle-BackColor="White" AlternatingRowStyle-ForeColor="#000"
runat="server" AutoGenerateColumns="false">
<Columns>
<asp:BoundField DataField="Id" HeaderText="Id" ItemStyle-Width="80" />
<asp:BoundField DataField="Name" HeaderText="Name" ItemStyle-Width="150" />
<asp:BoundField DataField="Country" HeaderText="Country" ItemStyle-Width="150" />
</Columns>
</asp:GridView>
<br />
<asp:Button ID="btnExport" runat="server" Text="Export To PDF and Send email" OnClick="ExportToPDF" />
Mail Server Settings in Web.Config file
The following Mail Server settings need to be saved in the
Web.Config file.
Note: It is necessary to use the sender’s email address credentials while defining the Gmail SMTP Server Credentials as Gmail the sender’s email address must be same as the Gmail Username specified in credentials.
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="sender@gmail.com">
<network
host="smtp.gmail.com"
port="587"
enableSsl="true"
userName="sender@gmail.com"
password="GMAILor2STEP-PASSWORD"
defaultCredentials="true"/>
</smtp>
</mailSettings>
</system.net>
MailMessage class properties
Following are the required properties of the MailMessage class.
From – Sender’s email address.
To – Recipient(s) Email Address.
CC – Carbon Copies. (If any)
BCC – Blind Carbon Copies. (If any)
Subject – Subject of the Email.
Body – Body of the Email.
IsBodyHtml – Specify whether body contains text or HTML mark up.
Attachments – Attachments. (If any)
ReplyTo – ReplyTo Email address.
SmtpClient class methods
Following are the methods of the SMTP class.
Host – SMTP Server URL (Gmail: smtp.gmail.com)
Port – Port Number of the SMTP sever (Gmail: 587)
EnableSsl – Specify whether your host accepts SSL Connections (Gmail: True)
UseDefaultCredentials – Set to True in order to allow authentication based on the Credentials of the Account used to send emails
Credentials – Valid login credentials for the SMTP server (Gmail: email address and password)
Namespaces
You will need to import the following namespaces.
C#
using System.IO;
using System.Data;
using System.Net;
using System.Net.Mail;
using System.Net.Configuration;
using System.Configuration;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
VB.Net
Imports System.IO
Imports System.Data
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Configuration
Imports System.Configuration
Imports iTextSharp.text
Imports iTextSharp.tool.xml
Imports iTextSharp.text.pdf
Binding the GridView
Inside the
Page_Load event handler, the
GridView is populated with the records from dynamic
DataTable.
C#
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("Id"),
new DataColumn("Name"),
new DataColumn("Country")
});
dt.Rows.Add(1, "John Hammond", "United States");
dt.Rows.Add(2, "Mudassar Khan", "India");
dt.Rows.Add(3, "Suzanne Mathews", "France");
dt.Rows.Add(4, "Robert Schidner", "Russia");
gvCustomers.DataSource = dt;
gvCustomers.DataBind();
}
}
VB.Net
Protected Sub Page_Load(sender As Object, e As EventArgs) Handles Me.Load
If Not Me.IsPostBack Then
Dim dt As New DataTable()
dt.Columns.AddRange(New DataColumn(2) {
New DataColumn("Id"),
New DataColumn("Name"),
New DataColumn("Country")
})
dt.Rows.Add(1, "John Hammond", "United States")
dt.Rows.Add(2, "Mudassar Khan", "India")
dt.Rows.Add(3, "Suzanne Mathews", "France")
dt.Rows.Add(4, "Robert Schidner", "Russia")
gvCustomers.DataSource = dt
gvCustomers.DataBind()
End If
End Sub
Exporting GridView to PDF document and sending as File Attachment in Email
When
Export button is clicked, the email setting is read from
SmtpSection section of
Web.Config file.
The
StringWriter and
HtmlTextWriter class objects are created and the
GridView is exported to an
HTML string using
StringReader class.
Then, the
GridView is rendered into an
HTML string using RenderControl which accepts
HtmlTextWriter class object as parameter.
After that, the generated HTML is added to the
iTextSharp PDF document using
Document class.
The
PDF document is opened and the
GridView data is written using
ParseXHtml method of
XmlWorkerHelper class which converts it to
PDF document and saves it to the
MemoryStream class object.
Finally, email is being sent via GMAIL account along with the exported
GridView PDF document.
C#
protected void ExportToPDF(object sender, EventArgs e)
{
using (StringWriter sw = new StringWriter())
{
using (HtmlTextWriter hw = new HtmlTextWriter(sw))
{
gvCustomers.RenderControl(hw);
StringReader sr = new StringReader(sw.ToString());
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
using (MemoryStream memoryStream = new MemoryStream())
{
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
byte[] bytes = memoryStream.ToArray();
memoryStream.Close();
// Reading SmtpSection from web.Config file.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, "receiver@gmail.com"))
{
mm.Subject = "GridView Exported PDF";
mm.Body = "GridView Exported PDF Attachment";
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "GridViewPDF.pdf"));
mm.IsBodyHtml = true;
// Sending Email.
using (SmtpClient smtp = new SmtpClient())
{
smtp.Host = smtpSection.Network.Host;
smtp.Port = smtpSection.Network.Port;
smtp.EnableSsl = smtpSection.Network.EnableSsl;
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials;
smtp.Credentials = new NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password);
smtp.Send(mm);
}
}
}
}
}
}
public override void VerifyRenderingInServerForm(Control control)
{
/* Verifies that the control is rendered. */
}
VB.Net
Protected Sub ExportToPDF(sender As Object, e As EventArgs)
Using sw As New StringWriter()
Using hw As New HtmlTextWriter(sw)
gvCustomers.RenderControl(hw)
Using sr As New StringReader(sw.ToString())
Dim pdfDoc As New Document(PageSize.A4, 10.0F, 10.0F, 10.0F, 0F)
Using memoryStream As New MemoryStream()
Dim writer As PdfWriter = PdfWriter.GetInstance(pdfDoc, memoryStream)
pdfDoc.Open()
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr)
pdfDoc.Close()
Dim bytes As Byte() = memoryStream.ToArray()
' Reading SmtpSection from web.Config file.
Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
Using mm As New MailMessage(smtpSection.From, "receiver@gmail.com")
mm.Subject = "GridView Exported PDF"
mm.Body = "GridView Exported PDF Attachment"
mm.Attachments.Add(New Attachment(New MemoryStream(bytes), "GridViewPDF.pdf"))
mm.IsBodyHtml = True
' Sending Email.
Using smtp As New SmtpClient()
smtp.Host = smtpSection.Network.Host
smtp.Port = smtpSection.Network.Port
smtp.EnableSsl = smtpSection.Network.EnableSsl
smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
smtp.Credentials = New NetworkCredential(smtpSection.Network.UserName, smtpSection.Network.Password)
smtp.Send(mm)
End Using
End Using
End Using
End Using
End Using
End Using
End Sub
Public Overrides Sub VerifyRenderingInServerForm(control As Control)
' Verifies that the control is rendered.
End Sub
Screenshots
The Form
Received Email
Downloads