Convert HTML String To PDF Via iTextSharp Library And Download

In this article, we will see how we can convert a string of data to PDF and then send email with attached copy of generated PDF in C#.

Firstly, we can convert the string of data to PDF by using Popular Library for rendering PDF in ItextSharp. Secondly, we can download/save the converted PDF by using HTTP Response Class which provides response to client and contains information about response in the form of headers and other piece of necessary information.

So, lets start to  build our first step,

Step 1: Convert  HTML String to PDF,

In this step we will first create a button which will do the rest of the work on 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: 

 

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

Let's start building 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:[email protected]'>[email protected]</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:[email protected]'>[email protected]</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 StringBuilder class for generating HTML string and pass 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;

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 default page size of A4 Page size.

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

Parse the HTML string using HTMLWorker of Itextsharp library,

HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

Use the memory stream to reside the file in-memory. 

using (MemoryStream memoryStream = new MemoryStream())  
{  
}

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.

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 a in-memory reference to later attach to the email.

byte[] bytes = memoryStream.ToArray();  
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

In the next step we will see how we can download the in memory generated PDF File.

As we are using the stream so that we use response method to send the information to the client. 

// Clears all content output from the buffer stream                 
Response.Clear(); 
// Gets or sets the HTTP MIME type of the output stream.
Response.ContentType = "application/pdf";  
// Adds an HTTP header to the output stream
Response.AddHeader("Content-Disposition", "attachment; filename=Invoice.pdf");  

//Gets or sets a value indicating whether to buffer output and send it after
// the complete response is finished processing.
Response.Buffer = true;  
// Sets the Cache-Control header to one of the values of System.Web.HttpCacheability.
Response.Cache.SetCacheability(HttpCacheability.NoCache); 
// Writes a string of binary characters to the HTTP output stream. it write the generated bytes .
Response.BinaryWrite(bytes); 

// Sends all currently buffered output to the client, stops execution of the
// page, and raises the System.Web.HttpApplication.EndRequest event.
Response.End(); 
// Closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
Response.Close();

Final Output

 

Now I will compare the ironPDF Library with itextsharp for Converting HTML to PDF, so that we can get better idea which one library convert it in better way without losing formatting. 

C# HTML to PDF rendering is undertaken by a fully functional version of the Google Chromium engine, embedded within IronPDF DLL. 

Lets Start, the Configuration of IronPDF in our project. 

Step 1

Open Visual Studio and Create New Dot Net Web App Project By Pressing Ctrl + Shift + N Combination of Keys or File --> New --> Project. 

Lets Name the project as per your business need as its demo so I have mentioned this name. 

After creating new project, Lets Start adding Nuget package of IronPDF, 

Open nuget packager and type IronPDF and select to install or go to the above link and use command interface to install.

 or using Package Manager Console of nuget Manager using this command

Install-Package IronPdf

Now we All set to configure IronPDF in our project. 

Step 2

Once you have IronPDF installed and referenced in you project you can start using it right away by typing a couple of code lines: regarding how to convert HTML to PDF in C#.

But Firstly, Lets Create Button for Export into PDF 

Then, Create instance of ChromerPdfRenderer.

var ChromePdfRenderer = new ChromePdfRenderer(); 

Secondly, Add couple of lines to convert html to pdf. 

// render html to pdf 
var PDF = Renderer.RenderHtmlAsPdf(InvoiceHtml()); 
// output to pdf 
var OutputPath = Server.MapPath("HtmlToPDF.pdf"); 
PDF.SaveAs(OutputPath); 
// after pdf saved it will open it in the default browser 
System.Diagnostics.Process.Start(OutputPath); 

And the perfect (without losing formatting) exported pdf preview is shown below: 

Lets now compare the difference between itextsharp and IronPDF rendering below:

iText is a lower level library which focuses on a drawing API where we add objects, shapes, and text to pages.

While IronPDF uses a full embedded web browser renderer to convert HTML to PDF.

At the end a key difference with HTML to PDF between C# iTextSharp and IronPDF is that IronPDF has more advanced and accurate HTML-To-PDF rendering by using an embedded Chrome based web browser.

Read more articles on C#:


Similar Articles