Convert HTML String To PDF Via iTextSharp Library And Send As An Email Attachment

In this article we will see how we can convert string of data to PDF and then send email with attached copy of generated PDF.
Firstly, we can convert the string of data to PDF by using Popular Library for rendering PDF is ItextSharp. Secondly, we can attach the converted PDF file to email and send to the recipient by using built in C# Mail messages Class.
So, lets start to  build our first step,
Step 1: Convert  HTML String to PDF,
In this step we will first create button which will do the rest of work on Click event.
Let's create the button to perform the required operation.  
  1. <asp:Button ID="btn_PDFEmail" runat="server" Text="Convert HTML to PDF and Send Email with Attachment" OnClick="btn_PDFEmail_Click" />  
The UI view looks like the following: 
So our front end is all set and we need to apply the cs logic to perform operation.
Let's start building HTML string. 
  1. StringBuilder sb = new StringBuilder();  
  2.                    sb.Append("<header class='clearfix'>");  
  3.                    sb.Append("<h1>INVOICE</h1>");  
  4.                    sb.Append("<div id='company' class='clearfix'>");  
  5.                    sb.Append("<div>Company Name</div>");  
  6.                    sb.Append("<div>455 John Tower,<br /> AZ 85004, US</div>");  
  7.                    sb.Append("<div>(602) 519-0450</div>");  
  8.                    sb.Append("<div><a href='mailto:[email protected]'>[email protected]</a></div>");  
  9.                    sb.Append("</div>");  
  10.                    sb.Append("<div id='project'>");  
  11.                    sb.Append("<div><span>PROJECT</span> Website development</div>");  
  12.                    sb.Append("<div><span>CLIENT</span> John Doe</div>");  
  13.                    sb.Append("<div><span>ADDRESS</span> 796 Silver Harbour, TX 79273, US</div>");  
  14.                    sb.Append("<div><span>EMAIL</span> <a href='mailto:[email protected]'>[email protected]</a></div>");  
  15.                    sb.Append("<div><span>DATE</span> April 13, 2016</div>");  
  16.                    sb.Append("<div><span>DUE DATE</span> May 13, 2016</div>");  
  17.                    sb.Append("</div>");  
  18.                    sb.Append("</header>");  
  19.                    sb.Append("<main>");  
  20.                    sb.Append("<table>");  
  21.                    sb.Append("<thead>");  
  22.                    sb.Append("<tr>");  
  23.                    sb.Append("<th class='service'>SERVICE</th>");  
  24.                    sb.Append("<th class='desc'>DESCRIPTION</th>");  
  25.                    sb.Append("<th>PRICE</th>");  
  26.                    sb.Append("<th>QTY</th>");  
  27.                    sb.Append("<th>TOTAL</th>");  
  28.                    sb.Append("</tr>");  
  29.                    sb.Append("</thead>");  
  30.                    sb.Append("<tbody>");  
  31.                    sb.Append("<tr>");  
  32.                    sb.Append("<td class='service'>Design</td>");  
  33.                    sb.Append("<td class='desc'>Creating a recognizable design solution based on the company's existing visual identity</td>");  
  34.                    sb.Append("<td class='unit'>$400.00</td>");  
  35.                    sb.Append("<td class='qty'>2</td>");  
  36.                    sb.Append("<td class='total'>$800.00</td>");  
  37.                    sb.Append("</tr>");  
  38.                    sb.Append("<tr>");  
  39.                    sb.Append("<td colspan='4'>SUBTOTAL</td>");  
  40.                    sb.Append("<td class='total'>$800.00</td>");  
  41.                    sb.Append("</tr>");  
  42.                    sb.Append("<tr>");  
  43.                    sb.Append("<td colspan='4'>TAX 25%</td>");  
  44.                    sb.Append("<td class='total'>$200.00</td>");  
  45.                    sb.Append("</tr>");  
  46.                    sb.Append("<tr>");  
  47.                    sb.Append("<td colspan='4' class='grand total'>GRAND TOTAL</td>");  
  48.                    sb.Append("<td class='grand total'>$1,000.00</td>");  
  49.                    sb.Append("</tr>");  
  50.                    sb.Append("</tbody>");  
  51.                    sb.Append("</table>");  
  52.                    sb.Append("<div id='notices'>");  
  53.                    sb.Append("<div>NOTICE:</div>");  
  54.                    sb.Append("<div class='notice'>A finance charge of 1.5% will be made on unpaid balances after 30 days.</div>");  
  55.                    sb.Append("</div>");  
  56.                    sb.Append("</main>");  
  57.                    sb.Append("<footer>");  
  58.                    sb.Append("Invoice was created on a computer and is valid without the signature and seal.");  
  59.                    sb.Append("</footer>"); 
I am using StringBuilder class for generating HTML string and pass to the parser for generating PDF. Before proceeding further add the following references. 
  1. using iTextSharp.text;  
  2. using iTextSharp.text.html.simpleparser;  
  3. using iTextSharp.text.pdf;  
  4. using System.Configuration;  
  5. using System.IO;  
  6. using System.Linq;  
  7. using System.Net;  
  8. using System.Net.Mail;  
  9. using System.Text;  
  10. using System.Web;  
Now let's write the code for generating in-memory PDF from HTML string. 
  1. StringReader sr = new StringReader(sb.ToString());  
  3.                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);  
  4.                    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);  
  5.                    using (MemoryStream memoryStream = new MemoryStream())  
  6.                    {  
  7.                        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);  
  8.                        pdfDoc.Open();  
  10.                        htmlparser.Parse(sr);  
  11.                        pdfDoc.Close();  
  13.                        byte[] bytes = memoryStream.ToArray();  
  14.                        memoryStream.Close();  
  15.                    } 
Now let's understand the Line of code. After building the string we can read from the string as we have passed the generated string. 
  1. StringReader sr = new StringReader(sb.ToString());   
We are building the PDF document with default page size of A4 Page size.
  1. Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);   
Parse the HTML string using HTMLWorker of Itextsharp library,
  1. HTMLWorker htmlparser = new HTMLWorker(pdfDoc);   
Use the memory stream to reside the file in-memory. 
  1. using (MemoryStream memoryStream = new MemoryStream())  
  2.                     {  

Now we get the PDF and memory stream to create the instance and write the document. Then first open the document, parse by the html worker and then after completing the work close the document (dispose off the resources) managing the resource properly.
  1. PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);    
  2.                        pdfDoc.Open();    
  4.                        htmlparser.Parse(sr);    
  5.                        pdfDoc.Close();   
Now we add the created document to the memory stream and use the bytes of it as a in-memory reference to later attach to the email.
  1. byte[] bytes = memoryStream.ToArray();  
  2.                memoryStream.Close(); 
This is all about first step which will generate the PDF file and we will later use this as an attachment.
First Output
Now let's proceed to the second step:
Step 2: 

Email the Generated PDF File as an attachment. We will now use the Mail Message class to send email with in-memory generated PDF File. 
  1. // From web.config
  2. string fromEmail = ConfigurationManager.AppSettings["fromEmail"].ToString();             
  3.                         MailMessage mm = new MailMessage();  
  4.                         mm.To.Add("recipientaddress");  
  5.                         mm.From = new MailAddress(fromEmail);  
  6.                         mm.Subject = "Online Request";  
  7.                         mm.Body = "Thanks for your time, Please find the attached invoice";  
  8.                         mm.Attachments.Add(new Attachment(new MemoryStream(bytes), "Invoice.pdf"));  
  9.                         mm.IsBodyHtml = true;  
  10.                         SmtpClient smtp = new SmtpClient();  
  11.                         smtp.Host = ConfigurationManager.AppSettings["SmtpServer"].ToString();  
  12.                         smtp.EnableSsl = false;  
  13.                         NetworkCredential NetworkCred = new NetworkCredential();  
  14.                         NetworkCred.UserName = "[email protected]";  
  15.                         NetworkCred.Password = "email_password";  
  16.                         smtp.UseDefaultCredentials = true;  
  17.                         smtp.Credentials = NetworkCred;  
  18.                         smtp.Port = 25;  
  19.                         smtp.Send(mm); 
You can use any email you receive from id by just authorizing the account i.e providing the network credentials. I have also use some application settings from web.config file and use here to get from there. 
  1. <configuration>  
  2.   <appSettings>  
  3.       <add key="fromEmail" value="[email protected]"/>  
  4.     <add key="SmtpServer" value=""/>  
  5.   </appSettings>  
  6. </configuration> 
Final Output

Read more articles on C#:

Up Next
    Ebook Download
    View all
    View all