How to convert HTML to PDF in ASP.NET?


In this article I have explained in detail about how to convert html content to PDF content. In this article I convert PDF in two ways. 1) direct html text into PDF and also Read HTML file content and convert into PDF. I am using itextsharp dll for this requirement.

Client side:


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

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title>Convert HTML to PDF</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<table cellpadding="0" cellspacing="0" align="center" width="500">
<tr>
<td height="80" align="center">

</td>
</tr>
<tr>
<td height="40">
<b>Convert HTML to PDF in ASP.NET</b>
</td>
</tr>
<tr>
<td height="80" align="center">
<asp:Button ID="btnExportPDF" runat="server" Text="Click here to convert HTML string to PDF"
OnClick="btnExportPDF_Click" Width="320" />
</td>
</tr>
<tr>
<td height="80" align="center">
<asp:Button ID="Button1" runat="server"
Text="Click here to convert HTML File to PDF File" Width="320"
onclick="Button1_Click" />
</td>
</tr>
</table>
</div>
</form>
</body>
</html>

Server side


using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html.simpleparser;
using System.IO;
using System.Collections;

public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{

}

// Below code is used to convert your string HTML value to PDF
protected void btnExportPDF_Click(object sender, EventArgs e)
{

//Set page size as A4
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);

try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);

//Open PDF Document to write data
pdfDoc.Open();

//Assign Html content in a string to write in PDF
string contents = "<h5>EXPORT HTML CONTENT TO PDF</h5><br/><br/><b><u>This content is convert from html string to PDF</u></b><br/><br/><br/><font color='red'>Samples from Ravi!!!</font>";

//Read string contents using stream reader and convert html to parsed conent
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);

//Get each array values from parsed elements and add to the PDF document
foreach (var htmlElement in parsedHtmlElements)
pdfDoc.Add(htmlElement as IElement);

//Close your PDF
pdfDoc.Close();

Response.ContentType = "application/pdf";

//Set default file Name as current datetime
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);

Response.Flush();
Response.End();
}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}

// Below code is read content from HTML file and convert to PDF

protected void Button1_Click(object sender, EventArgs e)
{
//Set page size as A4
Document pdfDoc = new Document(PageSize.A4, 10, 10, 10, 10);

try
{
PdfWriter.GetInstance(pdfDoc, System.Web.HttpContext.Current.Response.OutputStream);

//Open PDF Document to write data
pdfDoc.Open();

//Assign Html content in a string to write in PDF
string contents = "";

StreamReader sr;
try
{
//Read file from server path
sr = File.OpenText(Server.MapPath("sample.html"));
//store content in the variable
contents = sr.ReadToEnd();
sr.Close();
}
catch (Exception ex)
{

}

//Read string contents using stream reader and convert html to parsed conent
var parsedHtmlElements = HTMLWorker.ParseToList(new StringReader(contents), null);

//Get each array values from parsed elements and add to the PDF document
foreach (var htmlElement in parsedHtmlElements)
pdfDoc.Add(htmlElement as IElement);

//Close your PDF
pdfDoc.Close();

Response.ContentType = "application/pdf";

//Set default file Name as current datetime
Response.AddHeader("content-disposition", "attachment; filename=" + DateTime.Now.ToString("yyyyMMdd") + ".pdf");
System.Web.HttpContext.Current.Response.Write(pdfDoc);

Response.Flush();
Response.End();

}
catch (Exception ex)
{
Response.Write(ex.ToString());
}
}
}


Output
Client side Design
Output

Convert HTML content to PDF screen shot
Output

Convert HTML file content to PDF screen shot
Output

Source Code Detail:
Here with I have attached source code of Convert HTML content to PDF example download and try to learn this concept.
Front End : ASP.NET

Conclusion:
I hope this article help to know AJAX Convert HTML content to PDF


Attachments

  • Source Code (43589-191827-ConvertHtmlToPDF.rar)
  • Comments

    Guest Author: Jalilur Rahman23 Mar 2012

    It's wonderful and interesting. Thanks,

    Author: Ravindran26 Mar 2012 Member Level: Gold   Points : 0

    Thanks Jalilur!

    Guest Author: abdhesh05 Jul 2012

    %PDF-1.4 %???? System.FormatException: Input string was not in a correct format.

    Author: Ravindran19 Jul 2012 Member Level: Gold   Points : 0

    abdhesh, Make sure your input string was correct format like if you assign string value in integer variable got this kind of error...

    Author: rajesh kumar parbat20 Jul 2012 Member Level: Gold   Points : 0

    Nice and very relevent .

    Guest Author: ALberT15 Feb 2013

    Is very nice, but how can I convert the source codo to string?

    Guest Author: ALberT15 Feb 2013

    Nice, but how can I convert the source code to string?

    Guest Author: Albert15 Feb 2013

    Nice, but how can I convert the sourse code to string???

    Guest Author: kumar23 Apr 2013

    "Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack."

    Author: Hania17 Jan 2014 Member Level: Bronze   Points : 0

    Try Aspose.PDF for .NET for converting HTML to PDF and vice versa:

    http://www.aspose.com/.net/pdf-component.aspx



  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name:
    Email: