In this article I will explain with an example, how to dynamically generate
PDF in Memory and send 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.
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.Data;
using System.IO;
using System.Text;
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.Data
Imports System.IO
Imports System.Text
Imports System.Net
Imports System.Net.Mail
Imports System.Net.Configuration
Imports System.Configuration
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Imports iTextSharp.tool.xml
Generating PDF in Memory and sending as email attachment using C# and VB.Net
Inside the Page_Load event handler, the DataTable is created with some dummy data and SendPDFEmail method is called.
Inside the SendPDFEmail function, using the StringBuilder class an HTML string is generated. This HTML string is basically a Receipt from a company containing the details of an Order.
Then, generated HTML string is converted to
PDF document using
ParseXHtml method of
XmlWorkerHelper class and saved into the
MemoryStream class object.
Finally, the email is being sent with the generated
PDF as an attachment and success the message is displayed in
JavaScript Alert Message Box using
RegisterStartupScript method.
C#
protected void Page_Load(object sender,EventArgs e)
{
if (!this.IsPostBack)
{
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[3] {
new DataColumn("OrderId"),
new DataColumn("Product"),
new DataColumn("Quanity")});
dt.Rows.Add(101,"Sun Glasses", 5);
dt.Rows.Add(102,"Jeans", 2);
dt.Rows.Add(103,"Trousers", 12);
dt.Rows.Add(104,"Shirts", 9);
this.SendPDFEmail(dt);
}
}
private void SendPDFEmail(DataTable dt)
{
string companyName = "ASPSnippets Private Limited";
int orderNo = 2303;
StringBuilder sb = new StringBuilder();
sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>");
sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan='2'><b>Order Sheet</b></td></tr>");
sb.Append("<tr><tdcolspan='2'></td></tr>");
sb.Append("<tr><td><b>Order No:</b>");
sb.Append(orderNo);
sb.Append("</td><td><b>Date: </b>");
sb.Append(DateTime.Now);
sb.Append(" </td></tr>");
sb.Append("<tr><tdcolspan='2'><b>Company Name :</b> ");
sb.Append(companyName);
sb.Append("</td></tr>");
sb.Append("</table>");
sb.Append("<br />");
sb.Append("<table border='1' cellspacing='0' cellpadding='2' width='100%'>");
sb.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
sb.Append("<th style='background-color: #D20B0C; color: #FFFFFF'>");
sb.Append(column.ColumnName);
sb.Append("</th>");
}
sb.Append("</tr>");
foreach (DataRow row in dt.Rows)
{
sb.Append("<tr>");
foreach (DataColumn column in dt.Columns)
{
sb.Append("<td>");
sb.Append(row[column]);
sb.Append("</td>");
}
sb.Append("</tr>");
}
sb.Append("</table>");
byte[] bytes = null;
using (StringReader sr = new StringReader(sb.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();
bytes = memoryStream.ToArray();
memoryStream.Close();
}
}
//ReadSmtpsection fromweb.Config file.
SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
using (MailMessage mm = new MailMessage(smtpSection.From, "receiver@gmail.com"))
{
mm.Subject = "iTextSharp PDF";
mm.Body = "iTextSharp PDF Attachment";
mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "iTextSharpPDF.pdf"));
mm.IsBodyHtml = false;
//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);
ClientScript.RegisterStartupScript(this.GetType(), "alert", "alert('Email sent.');", true);
}
}
}
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("OrderId"),
New DataColumn("Product"),
New DataColumn("Quanity")})
dt.Rows.Add(101, "Sun Glasses", 5)
dt.Rows.Add(102, "Jeans", 2)
dt.Rows.Add(103, "Trousers", 12)
dt.Rows.Add(104, "Shirts", 9)
Me.SendPDFEmail(dt)
End If
End Sub
Private Sub SendPDFEmail(dt As DataTable)
Dim companyName As String = "ASPSnippets Private Limited"
Dim orderNo As Integer = 2303
Dim sb As New StringBuilder()
sb.Append("<table width='100%' cellspacing='0' cellpadding='2'>")
sb.Append("<tr><td align='center' style='background-color: #18B5F0' colspan='2'><b>Order Sheet</b></td></tr>")
sb.Append("<tr><tdcolspan='2'></td></tr>")
sb.Append("<tr><td><b>Order No:</b>")
sb.Append(orderNo)
sb.Append("</td><td><b>Date: </b>")
sb.Append(DateTime.Now)
sb.Append(" </td></tr>")
sb.Append("<tr><tdcolspan='2'><b>Company Name :</b> ")
sb.Append(companyName)
sb.Append("</td></tr>")
sb.Append("</table>")
sb.Append("<br />")
sb.Append("<table border='1' cellspacing='0' cellpadding='2' width='100%'>")
sb.Append("<tr>")
For Each column As DataColumn In dt.Columns
sb.Append("<th style='background-color: #D20B0C; color: #FFFFFF'>")
sb.Append(column.ColumnName)
sb.Append("</th>")
Next
sb.Append("</tr>")
For Each row As DataRow In dt.Rows
sb.Append("<tr>")
For Each column As DataColumn In dt.Columns
sb.Append("<td>")
sb.Append(row(column))
sb.Append("</td>")
Next
sb.Append("</tr>")
Next
sb.Append("</table>")
Dim bytes As Byte() = Nothing
Using sr As New StringReader(sb.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()
bytes = memoryStream.ToArray()
memoryStream.Close()
End Using
End Using
'ReadSmtpsection fromweb.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 = "iTextSharp PDF"
mm.Body = "iTextSharp PDF Attachment"
mm.Attachments.Add(New Attachment(New MemoryStream(bytes), "iTextSharpPDF.pdf"))
mm.IsBodyHtml = False
'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)
ClientScript.RegisterStartupScript(Me.GetType(), "alert", "alert('Email sent.');", True)
End Using
End Using
End Sub
Screenshots
Email received with the PDF as attachment
The generated PDF document
Demo
Downloads