In this article I will explain with an example, how to generate (create) PDF and send as email attachment in ASP.Net using C# and VB.Net.
 
 

Download iTextSharp and XmlWorkerHelper Libraries

You can download the iTextSharp and XmlWorkerHelper libraries from the following links.
Note: You will need to add the reference of iTextSharp and XmlWorkerHelper libraries in your project.
 
 

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, first a DataTable is populated with some dummy records and then the DataTable is passed as parameter to the SendPDFEmail method.
Note: I have made use of ASP.Net PageLoad event but the same code can be used in Windows as well as Console applications.
         For more details on how to populate DataTable with dummy records, please refer my article Dynamically create DataTable and bind to GridView in ASP.Net.          
 
Inside the SendPDFEmail method, an HTML Table (Receipt from a company containing the details of an Order) is generated using the StringBuilder class.
Then, the PdfWriter instance is created using MemoryStream class which is necessary to generate the PDF in memory.
After that, the generated HTML is parsed and added to the PDF document.
Once the PDF document is ready, the MemoryStream is converted to BYTE Array and then added as an attachment to the MailMessage class object and finally the email is sent.
Note: For more details on sending email with attachment, please refer my article Send email with attachment in ASP.Net using C# VB.Net.
 
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(Order Sheet);
    sb.Append("<tr><td colspan='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><td colspan='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'>");
    sb.Append("<tr>");
    foreach (DataColumn column in dt.Columns)
    {
        sb.Append("<th style='background-color: #F7F7F7'>");
        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 ms = new MemoryStream())
        {
            PdfWriter writer = PdfWriter.GetInstance(pdfDoc, ms);
            pdfDoc.Open();
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
            pdfDoc.Close();
            bytes = ms.ToArray();
            ms.Close();
        }
    }
 
    //Read SMTP section from Web.Config.
    SmtpSection smtpSection = (SmtpSection)ConfigurationManager.GetSection("system.net/mailSettings/smtp");
    string host = smtpSection.Network.Host;
    int port = smtpSection.Network.Port;
    bool enableSsl = smtpSection.Network.EnableSsl;
    bool defaultCredentials = smtpSection.Network.DefaultCredentials;
    string userName = smtpSection.Network.UserName;
    string password = smtpSection.Network.Password;
 
    using (MailMessage mm = new MailMessage(smtpSection.From, "recipient@gmail.com"))
    {
         mm.Subject = "iTextSharp PDF";
         mm.Body = "iTextSharp PDF Attachment";
         mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "iTextSharpPDF.pdf"));
         mm.IsBodyHtml = false;
        using (SmtpClient smtp = new SmtpClient())
        {
            smtp.Host = host;
            smtp.Port = port;
            smtp.EnableSsl = enableSsl;
            smtp.UseDefaultCredentials = defaultCredentials;
            NetworkCredential networkCred = new NetworkCredential(userName, password);
            smtp.Credentials = networkCred;
            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: #F7F7F7' colspan='2'><b>Order Sheet</b></td></tr>")
    sb.Append("<tr><td colspan='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><td colspan='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'>")
    sb.Append("<tr>")
    For Each column As DataColumn In dt.Columns
        sb.Append("<th style='background-color: #F7F7F7'>")
        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 ms As New MemoryStream()
            Dim writer As PdfWriter PdfWriter.GetInstance(pdfDoc, ms)
            pdfDoc.Open()
            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr)
            pdfDoc.Close()
            bytes = ms.ToArray()
            ms.Close()
        End Using
    End Using
 
    'Read SMTP section from Web.Config.
    Dim smtpSection As SmtpSection = CType(ConfigurationManager.GetSection("system.net/mailSettings/smtp"), SmtpSection)
    Dim host As String = smtpSection.Network.Host
    Dim port As Integer = smtpSection.Network.Port
    Dim enableSsl As Boolean = smtpSection.Network.EnableSsl
    Dim defaultCredentials As Boolean = smtpSection.Network.DefaultCredentials
    Dim userName As String = smtpSection.Network.UserName
    Dim password As String = smtpSection.Network.Password
 
    Using mm As New MailMessage(smtpSection.From, "recipient@gmail.com")
         mm.Subject = "iTextSharp PDF"
         mm.Body = "iTextSharp PDF Attachment"
         mm.Attachments.Add(New Attachment(New MemoryStream(bytes), "iTextSharpPDF.pdf"))
         mm.IsBodyHtml = False
         Using smtp As New SmtpClient()
            smtp.Host = host
            smtp.Port = port
            smtp.EnableSsl = enableSsl
            smtp.UseDefaultCredentials = smtpSection.Network.DefaultCredentials
            Dim networkCred As New NetworkCredential(userName, password)
            smtp.Credentials = networkCred
            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

Generate (Create) PDF and send as email attachment in ASP.Net
 

The generated PDF

 
Generate (Create) PDF and send as email attachment in ASP.Net
 
 

Demo

 
 

Downloads