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(

    );

  5.                    sb.Append(
    Company Name

    “);

  6.                    sb.Append(
    455 John Tower,
     AZ 85004, US

    “);

  7.                    sb.Append(
    (602) 519-0450

    “);

  8.                    sb.Append(

    “);

  9.                    sb.Append(“</div>”);
  10.                    sb.Append(

    );

  11.                    sb.Append(
    PROJECT Website development

    “);

  12.                    sb.Append(
    CLIENT John Doe

    “);

  13.                    sb.Append(
    ADDRESS 796 Silver Harbour, TX 79273, US

    “);

  14.                    sb.Append(

    “);

  15.                    sb.Append(
    DATE April 13, 2016

    “);

  16.                    sb.Append(
    DUE DATE May 13, 2016

    “);

  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(

    );

  53.                    sb.Append(
    NOTICE:

    “);

  54.                    sb.Append(
    A finance charge of 1.5% will be made on unpaid balances after 30 days.

    “);

  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());
  2.                    Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
  3.                    HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
  4.                    using (MemoryStream memoryStream = new MemoryStream())
  5.                    {
  6.                        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, memoryStream);
  7.                        pdfDoc.Open();
  8.                        htmlparser.Parse(sr);
  9.                        pdfDoc.Close();
  10.                        byte[] bytes = memoryStream.ToArray();
  11.                        memoryStream.Close();
  12.                    }

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.                     {
  3. }
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();
  3.                        htmlparser.Parse(sr);
  4.                        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”);
  7. //Gets or sets a value indicating whether to buffer output and send it after
    // the complete response is finished processing.
  8.                   Response.Buffer = true;
  9.      // Sets the Cache-Control header to one of the values of System.Web.HttpCacheability.
  10.                   Response.Cache.SetCacheability(HttpCacheability.NoCache);
  11.  // Writes a string of binary characters to the HTTP output stream. it write the generated bytes .
  12.                   Response.BinaryWrite(bytes);
  13. // Sends all currently buffered output to the client, stops execution of the
    // page, and raises the System.Web.HttpApplication.EndRequest event.
  14.                   Response.End();
  15.  // Closes the socket connection to a client. it is a necessary step as you must close the response after doing work.its best approach.
  16.                   Response.Close();

Final Output:

Advertisements