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

Introduction

In this article, we will see how we can convert a string of data to PDF and then send an email with an attached copy of the 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 an email and send it to the recipient by using the built-in C# Mail messages Class.

So, let's start to build our first step.

Step 1. Convert HTML String to PDF

In this step, we will first create a button that will do the rest of the work on the Click event.

Let's create the button to perform the required operation.

<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.

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

So our front end is all set, and we need to apply the CS logic to perform the operation.

Let's start building an HTML string.

StringBuilder sb = new StringBuilder();sb.Append("<header class='clearfix'>");sb.Append("<h1>INVOICE</h1>");sb.Append("<div id='company' class='clearfix'>");sb.Append("<div>Company Name</div>");sb.Append("<div>455 John Tower,<br /> AZ 85004, US</div>");sb.Append("<div>(602) 519-0450</div>");sb.Append("<div><a href='mailto:[emailprotected]'>[emailprotected]</a></div>");sb.Append("</div>");sb.Append("<div id='project'>");sb.Append("<div><span>PROJECT</span> Website development</div>");sb.Append("<div><span>CLIENT</span> John Doe</div>");sb.Append("<div><span>ADDRESS</span> 796 Silver Harbour, TX 79273, US</div>");sb.Append("<div><span>EMAIL</span> <a href='mailto:[emailprotected]'>[emailprotected]</a></div>");sb.Append("<div><span>DATE</span> April 13, 2016</div>");sb.Append("<div><span>DUE DATE</span> May 13, 2016</div>");sb.Append("</div>");sb.Append("</header>");sb.Append("<main>");sb.Append("<table>");sb.Append("<thead>");sb.Append("<tr>");sb.Append("<th class='service'>SERVICE</th>");sb.Append("<th class='desc'>DESCRIPTION</th>");sb.Append("<th>PRICE</th>");sb.Append("<th>QTY</th>");sb.Append("<th>TOTAL</th>");sb.Append("</tr>");sb.Append("</thead>");sb.Append("<tbody>");sb.Append("<tr>");sb.Append("<td class='service'>Design</td>");sb.Append("<td class='desc'>Creating a recognizable design solution based on the company's existing visual identity</td>");sb.Append("<td class='unit'>$400.00</td>");sb.Append("<td class='qty'>2</td>");sb.Append("<td class='total'>$800.00</td>");sb.Append("</tr>");sb.Append("<tr>");sb.Append("<td colspan='4'>SUBTOTAL</td>");sb.Append("<td class='total'>$800.00</td>");sb.Append("</tr>");sb.Append("<tr>");sb.Append("<td colspan='4'>TAX 25%</td>");sb.Append("<td class='total'>$200.00</td>");sb.Append("</tr>");sb.Append("<tr>");sb.Append("<td colspan='4' class='grand total'>GRAND TOTAL</td>");sb.Append("<td class='grand total'>$1,000.00</td>");sb.Append("</tr>");sb.Append("</tbody>");sb.Append("</table>");sb.Append("<div id='notices'>");sb.Append("<div>NOTICE:</div>");sb.Append("<div class='notice'>A finance charge of 1.5% will be made on unpaid balances after 30 days.</div>");sb.Append("</div>");sb.Append("</main>");sb.Append("<footer>");sb.Append("Invoice was created on a computer and is valid without the signature and seal.");sb.Append("</footer>");

I am using the StringBuilder class for generating HTML string and passing it to the parser for generating PDF. Before proceeding further, add the following references.

using iTextSharp.text;using iTextSharp.text.html.simpleparser;using iTextSharp.text.pdf;using System.Configuration;using System.IO;using System.Linq;using System.Net;using System.Net.Mail;using System.Text;using System.Web;// Your code here...

Now let's write the code for generating in-memory PDF from HTML string.

StringReader sr = new StringReader(sb.ToString());Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);HTMLWorker htmlparser = new HTMLWorker(pdfDoc);using (MemoryStream memoryStream = new MemoryStream()){ PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close();}

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.

StringReader sr = new StringReader(sb.ToString());

We are building the PDF document with a default page size of A4 Page size.

Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);

Parse the HTML string using the HTMLWorker of Itextsharp library.

HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

Use the memory stream to keep the file in memory.

using (MemoryStream memoryStream = new MemoryStream()){ // Your code inside this block...}

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 of the resources), managing the resource properly.

using (MemoryStream memoryStream = new MemoryStream()){ PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close();}

Now we add the created document to the memory stream and use the bytes of it as an in-memory reference to later attach to the email.

StringReader sr = new StringReader(sb.ToString());Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);HTMLWorker htmlparser = new HTMLWorker(pdfDoc);using (MemoryStream memoryStream = new MemoryStream()){ PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream); pdfDoc.Open(); htmlparser.Parse(sr); pdfDoc.Close(); byte[] bytes = memoryStream.ToArray(); memoryStream.Close(); // Now you have the PDF content in the 'bytes' array // You can save it to a file, send it as an email attachment, etc.}

This is all about the first step, which will generate the PDF file, and we will later use this as an attachment.

First Output

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

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 emails with in-memory generated PDF files.

using System;using System.Configuration;using System.IO;using System.Net;using System.Net.Mail;using System.Text;namespace YourNamespace{ public class YourClass { public void SendEmailWithAttachment(byte[] pdfBytes) { // From web.config string fromEmail = ConfigurationManager.AppSettings["fromEmail"].ToString(); string smtpServer = ConfigurationManager.AppSettings["SmtpServer"].ToString(); string smtpUsername = ConfigurationManager.AppSettings["SmtpUsername"].ToString(); string smtpPassword = ConfigurationManager.AppSettings["SmtpPassword"].ToString(); int smtpPort = Convert.ToInt32(ConfigurationManager.AppSettings["SmtpPort"]); using (MemoryStream memoryStream = new MemoryStream(pdfBytes)) { MailMessage mm = new MailMessage(); mm.To.Add("recipientaddress"); mm.From = new MailAddress(fromEmail); mm.Subject = "Online Request"; mm.Body = "Thanks for your time. Please find the attached invoice"; mm.Attachments.Add(new Attachment(memoryStream, "Invoice.pdf")); mm.IsBodyHtml = true; SmtpClient smtp = new SmtpClient(); smtp.Host = smtpServer; smtp.EnableSsl = false; smtp.UseDefaultCredentials = false; smtp.Credentials = new NetworkCredential(smtpUsername, smtpPassword); smtp.Port = smtpPort; try { smtp.Send(mm); } catch (Exception ex) { // Handle exception or log error } } } }}

You can use any email you receive from ID by just authorizing the account i.e, providing the network credentials. I have also used some application settings from the web. config file and use it here to get from there.

<configuration> <appSettings> <add key="fromEmail" value="[emailprotected]" /> <add key="SmtpServer" value="smtp.gmail.com" /> </appSettings></configuration>

Final Output

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

Read more articles on C#.

  • What Can C# Do For You
  • C# and ASP.Net Interview Question and Answers
Convert HTML String To PDF Via iTextSharp Library And Send As An Email Attachment (2024)

FAQs

How to convert HTML to PDF using iText? ›

HtmlConverter Class
  1. HtmlConverter class is the main class to convert HTML to PDF.
  2. HtmlConverter class has three main methods with different inputs and return types: convertToDocument(): returns Document instance. convertToElements(): returns a list of iText IElement instances.
Dec 5, 2019

How do I convert HTML string to PDF? ›

How to convert HTML to PDF quickly using the Acrobat extension for your web browser:
  1. Open the HTML web page in your Microsoft, Google, or Mozilla browser.
  2. Select Convert to PDF in the Adobe PDF toolbar.
  3. Name the file and save the new PDF file in your desired location.

How to convert HTML string to PDF in C# using iTextSharp? ›

Step 1. Convert HTML String to PDF
  1. <asp:Button ID="btn_PDFEmail" runat="server" Text="Convert HTML to PDF and Send Email with Attachment" OnClick="btn_PDFEmail_Click" /> ...
  2. using iTextSharp. ...
  3. StringReader sr = new StringReader(sb. ...
  4. Document pdfDoc = new Document(PageSize. ...
  5. HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
Aug 29, 2023

Can PdfSharp convert HTML to PDF? ›

PdfSharp is a C# library used to generate PDFs. This library enables the creation of PDF documents from HTML snippets using static rendering code.

How do I convert encoded text to PDF? ›

To convert the Base64 string into a PDF file, you'll need to do the following:
  1. Get the Base64 string from the Textarea.
  2. Create an Anchor element in the HTML element.
  3. Assign the Base64 string to the href attribute of the anchor element.
  4. Assign a filename to the download attribute.
Feb 27, 2023

How to convert HTML to PDF with JavaScript? ›

The html2pdf library converts HTML pages to PDFs in the browser. It uses html2canvas and jsPDF under the hood. html2canvas renders an HTML page into a canvas element and turns it into a static image. jsPDF then takes the image and converts it to a PDF file.

How do I convert HTML to PDF without losing formatting? ›

Simply and quickly change your file format online:
  1. Click on "Convert HTML to PDF" or select, drag and drop your file in "Convert HTML to PDF".
  2. Make any edit or changes your document may need.
  3. Click on "Convert" and select the desired format.
  4. Download the converted file or share it with anyone!

Can I convert HTML to PDF free? ›

WordToHTML.net is an online conversion tool that allows users to convert HTML documents to PDF with ease. This tool is free and requires no download or installation, making it a convenient option for those who need to convert HTML files on the go.

What is the shortcut to convert HTML to PDF? ›

Open the pages you want to save in Google Chrome. Next, open the menu using the three-dot button in the upper right corner of the screen. In the context menu, select the "Print" line or use the keyboard shortcut Ctrl + P. In the "Printer" section, set "Save as PDF".

How to convert HTML to PDF in C# .NET core? ›

How to Convert HTML to PDF in . NET Core
  1. Download the C# library to convert HTML to PDF.
  2. Use RenderUrlAsPdf to convert web URLs to PDF.
  3. Convert HTML markdown strings to PDF with RenderHtmlAsPdf.
  4. Convert MVC views to PDF by configuring the Model and Services class.

How to convert PDF to HTML string in C#? ›

How to convert PDF to HTML
  1. Download the C# library to convert PDF to HTML.
  2. Import an existing PDF document using the FromFile method.
  3. Configure the output HTML with the HtmlFormatOptions class.
  4. Convert the PDF to an HTML string with the ToHtmlString method.
  5. Export the HTML file from the PDF using the SaveAsHtml method.

How to generate HTML to PDF in Python? ›

How to Convert HTML to PDF in Python
  1. Install the Python library required for HTML to PDF conversion.
  2. Utilize the RenderHtmlAsPdf method to convert an HTML string into a PDF document.
  3. Generate PDF files directly from a website URL in Python.
  4. Convert HTML files to PDF files using the RenderHtmlFileAsPdf method.

How to convert HTML to PDF programmatically? ›

Steps to convert HTML to PDF programmatically:
  1. Convert("http://www.google.com/"); //Save the PDF document document.
  2. Save("HTMLToPDF. pdf"); //Close the document document.
  3. Close(true); //This will open the PDF file so, the result will be seen in default PDF viewer Process. Start("HTMLToPDF. pdf");

How to convert HTML to PDF programmatically in C#? ›

How to Convert HTML to PDF in C#
  1. Download and install the HTML to PDF C# library.
  2. Create a PDF with an HTML String.
  3. Use the RenderHtmlAsPdf method to convert an HTML String to a PDF.
  4. Export a PDF using existing URL.
  5. Generate a PDF from a HTML page.
  6. Add Custom Headers and Footers.

How to convert HTML to PDF batch? ›

Can I convert HTML to PDF in bulk? Yes, MConverter supports batch converting of multiple HTMLs to PDFs simultaneously. You can even drag and drop folders containing HTMLs to convert to PDF. Pasting HTML files and folders copied in the clipboard also works: use Ctrl+V.

How to convert HTML to PDF using itext7 in Java? ›

In iText for Java, HTMLConverter is the primary class used to convert HTML to PDF. There are three main methods in HTMLConverter : convertToDocument , which returns a Document object. convertToElements , which return a list of IElement objects.

How to convert HTML to PDF in PHP using Fpdf? ›

php require('fpdf. php'); $pdf=new FPDF(); $pdf->AddPage(); $pdf->SetFont('Arial','B',16); $pdf->Cell(40,10,'Hello World! '); $pdf->Output(); ?> To generate a pdf file, first, we need to include the library file fpdf.

Is iText 7 free for commercial use? ›

We have a dual licensing business model. You can use the SDK at no cost if you open source the application you are integrating the iText SDK into per the terms of the AGPL license, or you can license iText commercially if you don't want to open source your entire application.

Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 6342

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.