In this blog we will see how to convert HTML string to PDF using iTextSharp library in asp.net c#. iTextSharp is very popular third party library to convert HTML to pdf.

As iTextSharp is a third party library. Download this itextsharp.dll library from internet and add it to our project. All the steps available below. But before starting implementing iTextSharp, please read note given below.

Note: iTextSharp is a third party library and is not free to use commercially under AGPL license. So, if you want to use it commercially and want to deploy please read its license terms properly. This blog is only showing implementation of iTextSharp and not promoting free use of it.

Download and Add itextsharp.dll to project

Step 1. You can download itextsharp.dll from internet. As download completes add its reference to our project. Right click to project and select Add Reference… option.

Step 2. As you click on Add Reference, it will open a new window. Click Browse button and select you itextsharp.dll from proper path. Click on Add button and then OK button. itextsharp.dll will be add to your project in Bin folder.

Create HTML page

Step 1. Create Sample.html page in your project and design it according to your requirements. Or you can download any sample html template from internet and put it to proper folder in project.

Sample.html

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

    <title></title>

</head>

<body>

    <header>

        <h1>My Invoice Sample</h1>

        <div>

            <div><img src="http://localhost:51238/images/logo.jpg" style="width: 200px; height: 70px;" /></div>

            <div>Company Address</div>

            <div>Phone number</div>

            <div><a>company email address</a></div>

        </div>

        <div>

            <div><span>PROJECT : </span>[ProjectTitle]</div>

            <div><span>CLIENT : </span>[ClientName]</div>

            <div><span>ADDRESS : </span>[ClientAddress]</div>

            <div><span>EMAIL : </span> <a>[ClientEmailAddress]</a></div>

            <div><span>DATE : </span>[Date]</div>

        </div>

    </header>

    <div class="content">

        <table>

            <thead>

                <tr>

                    <th>SERVICE</th>

                    <th>DESCRIPTION</th>

                    <th>PRICE</th>

                    <th>QTY</th>

                    <th>TOTAL</th>

                </tr>

            </thead>

            <tbody>

                <tr>

                    <td>Data collection</td>

                    <td>Collected data</td>

                    <td>Rs.500.00</td>

                    <td>1</td>

                    <td>Rs. 500.00</td>

                </tr>

                <tr>

                    <td colspan='4'>SUBTOTAL</td>

                    <td>----</td>

                </tr>

                <tr>

                    <td colspan='4'>GST 18%</td>

                    <td>----</td>

                </tr>

                <tr>

                    <td colspan='4'>GRAND TOTAL</td>

                    <td>Rs. 500.00</td>

                </tr>

            </tbody>

        </table>

    </div>

    <footer>

        Invoice generated automatic through computer. Do not required seal and signature.  

    </footer>

</body>

</html>

In this sample html page I have used some text with square brackets, which will be replace with dynamic values entered by user.

Generate pdf and Save to folder

Step 1. Create a folder with name pdfs in your project where generated pdf from code will be save.

Step to create new folder: Right click on project-> Add-> New Folder.

Step 2. Now create ConvertHTMLtoPDF.aspx page to write code using iTextSharp library. Please read my comments to understand code properly.

Step to create new page: Right click on project-> Add-> Add New Item-> Select Web Form-> Add.

ConvertHTMLtoPDF.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ConvertHTMLtoPDF.aspx.cs" Inherits="ConvertHTMLtoPDF" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">

<head runat="server">

    <title>Convert HTML to PDF</title>

    <style type="text/css">

        h2, table {

            display: table;

            margin: 40px auto;

        }

    </style>

</head>

<body>

    <form id="form1" runat="server">

        <div>

            <h2>Generate HTML to PDF</h2>

            <table>

                <tr>

                    <td>Project Title

                    </td>

                    <td>

                        <asp:TextBox ID="txtProjectTitle" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Cilent Name

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientName" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Cilent Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientAddress" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Client Email Address

                    </td>

                    <td>

                        <asp:TextBox ID="txtClientEmailAddress" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td>Date

                    </td>

                    <td>

                        <asp:TextBox ID="txtDate" runat="server" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Button Text="Generate PDF" ID="btnGeneratePDF" runat="server" OnClick="btnGeneratePDF_Click" />

                    </td>

                </tr>

                <tr>

                    <td colspan="2" align="center">

                        <asp:Label Text="" ID="lblMsg" runat="server" />

                    </td>

                </tr>

            </table>

        </div>

    </form>

</body>

</html>

ConvertHTMLtoPDF.aspx.cs

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO; /* Add this Namespace */

using iTextSharp.text; /* Add this Namespace */

using iTextSharp.text.html.simpleparser; /* Add this Namespace */

using iTextSharp.text.pdf; /* Add this Namespace */

  

public partial class ConvertHTMLtoPDF : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

  

    /* Generate button click event */

    protected void btnGeneratePDF_Click(object sender, EventArgs e)

    {

        string htmlstring = "", Filename = DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".pdf", Filepath = "";

        htmlstring = File.ReadAllText(HttpContext.Current.Server.MapPath("~/template/Sample.html")); /* Read Sample.html from folder in our project */

  

        /* Replace square braket text with dynamic value insert by user. ie. [ProjectTitle] -> value */

        htmlstring = htmlstring.Replace("[ProjectTitle]", txtProjectTitle.Text);

        htmlstring = htmlstring.Replace("[ClientName]", txtClientName.Text);

        htmlstring = htmlstring.Replace("[ClientAddress]", txtClientAddress.Text);

        htmlstring = htmlstring.Replace("[ClientEmailAddress]", txtClientEmailAddress.Text);

        htmlstring = htmlstring.Replace("[Date]", txtDate.Text);

  

        Filepath = "~/pdfs/" + Filename; /* Path to save generated pdf */

        fnGeneratePDF(htmlstring, Filepath);

    }

  

    /* Function to generate pdf using iTextSharp */

    public void fnGeneratePDF(string html, string FilePath)

    {

        try

        {

            StringReader sr = new StringReader(html);

            Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10F, 10F, 100F, 0F);

            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, new FileStream(HttpContext.Current.Server.MapPath(FilePath), FileMode.Create));

            pdfDoc.Open();

            htmlparser.Parse(sr);

            pdfDoc.Close();

  

            lblMsg.Text = "PDF generated successfully..!!";

        }

        catch (Exception ex)

        {

        }

    }

}

PDF would be save to folder in your project. Here I have used "pdfs" folder.

Generate PDF and Download

You can create a new page to write code for downloading generated pdf. Your design page will remain same. Only the code of button click event will change. Code for generate pdf and download is given below.

ConvertAndDownload.aspx.cs

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.UI;

using System.Web.UI.WebControls;

using System.IO; /* Add this Namespace */

using iTextSharp.text; /* Add this Namespace */

using iTextSharp.text.html.simpleparser; /* Add this Namespace */

using iTextSharp.text.pdf; /* Add this Namespace */

  

public partial class ConvertAndDownload : System.Web.UI.Page

{

    protected void Page_Load(object sender, EventArgs e)

    {

  

    }

  

    /* Generate button click event */

    protected void btnGeneratePDF_Click(object sender, EventArgs e)

    {

        string htmlstring = "", Filename = DateTime.Now.ToString("ddMMMyyyyHHmmss") + ".pdf";

        htmlstring = File.ReadAllText(HttpContext.Current.Server.MapPath("~/template/Sample.html")); /* Read Sample.html from folder in our project */

  

        /* Replace square braket text with dynamic value insert by user. ie. [ProjectTitle] -> value */

        htmlstring = htmlstring.Replace("[ProjectTitle]", txtProjectTitle.Text);

        htmlstring = htmlstring.Replace("[ClientName]", txtClientName.Text);

        htmlstring = htmlstring.Replace("[ClientAddress]", txtClientAddress.Text);

        htmlstring = htmlstring.Replace("[ClientEmailAddress]", txtClientEmailAddress.Text);

        htmlstring = htmlstring.Replace("[Date]", txtDate.Text);

  

        fnGeneratePDF(htmlstring, Filename);

    }

  

    /* Function to generate pdf using iTextSharp */

    public void fnGeneratePDF(string html, string Filename)

    {

        try

        {

            StringReader sr = new StringReader(html);

            Document pdfDoc = new iTextSharp.text.Document(PageSize.A4, 10F, 10F, 100F, 0F);

            HTMLWorker htmlparser = new HTMLWorker(pdfDoc);

            PdfWriter.GetInstance(pdfDoc, Response.OutputStream);

            pdfDoc.Open();

            htmlparser.Parse(sr);

            pdfDoc.Close();

    

            /* Code to download pdf */

            Response.ContentType = "application/pdf";

            Response.AddHeader("content-disposition", "attachment;filename=" + Filename);

            Response.Cache.SetCacheability(HttpCacheability.NoCache);

            Response.Write(pdfDoc);

            Response.End();

        }

        catch (Exception ex)

        {

        }

    }

}

Hope this blog will help you. If I missed something or you have doubts comment below. Thank you..!!