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

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. 
  1. // Clears all content output from the buffer stream                 
  2.                   Response.Clear(); 
  3.  // Gets or sets the HTTP MIME type of the output stream.
  4.                   Response.ContentType = "application/pdf";  
  5. // Adds an HTTP header to the output stream
  6.                   Response.AddHeader("Content-Disposition""attachment; filename=Invoice.pdf");  
  8. //Gets or sets a value indicating whether to buffer output and send it after
    // the complete response is finished processing.
  9.                   Response.Buffer = true;  
  10.      // Sets the Cache-Control header to one of the values of System.Web.HttpCacheability.
  11.                   Response.Cache.SetCacheability(HttpCacheability.NoCache); 
  12.  // Writes a string of binary characters to the HTTP output stream. it write the generated bytes .
  13.                   Response.BinaryWrite(bytes); 
  14. // Sends all currently buffered output to the client, stops execution of the
    // page, and raises the System.Web.HttpApplication.EndRequest event.
  15.                   Response.End(); 
  16.  // Closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
  17.                   Response.Close();  
 Final Output:

Read more articles on C#:

Up Next
    Ebook Download
    View all
    View all