How to convert HTML content to PDF? Once, this question was very intricate. But after getting the solution I found it like a piece of cake. Here, I have provided solution with C# code so that you don’t have to waste your time by looking here and there for the solutions.

I have used iTextSharp.dll (version 4.0.6.0)in my solution which is very useful indeed. You can get it from here.

Review the below code, where I have converted content of the GridView to HTML and then I have converted that HTML content into a PDF file.

I have put comments with the code for more specification.//Include following name space to use iTextSharp library
using iTextSharp.text;
using iTextSharp.text.pdf;
//Document is inbuilt class, available in iTextSharp
Document document = new Document(PageSize.A4, 80, 50, 30, 65);
StringBuilder strData = new StringBuilder(string.Empty);
//I have provided Path for the HTML which will be generated from GridView content
string strHTMLpath = Server.MapPath("MyHTML.html");
//I have provided Path for the PDF file which will be generated from HTML content
string strPDFpath = Server.MapPath("MyPDF.pdf");
try
{
StringWriter sw = new StringWriter();
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
sw.WriteLine(Environment.NewLine);
HtmlTextWriter htw = new HtmlTextWriter(sw);
//gvSearchResult is a GridView, I have converted its content to HTML and will acquire final PDF file
/*Here i have set AllowPaging and AllowSorting property of GridView as false, As my aim is to get whole content of the GridView in a single table, by setting these properties and binding the GridView again will remove paging and sorting property from it. */
gvSerchResult.AllowPaging = false;
gvSerchResult.AllowSorting = false;
BindGridView();
//Rendering the HtmlTextWriter
gvSerchResult.RenderControl(htw);
/*Here i have set AllowPaging and AllowSorting property of GridView as true, As my aim is to get whole content of the GridView is now finished and I have acquire its content in HtmlTextWriter. Then by setting properties again I will get the original form of my GridView again*/
gvSerchResult.AllowPaging = true;
gvSerchResult.AllowSorting = true;
BindGridView();
StreamWriter strWriter = new StreamWriter(strHTMLpath, false, Encoding.UTF8);
strWriter.Write("<html><head><link href=Style.css rel=stylesheet type=text/css /></head><body>" + htw.InnerWriter.ToString() + "</body></html>");
strWriter.Close();
strWriter.Dispose();
iTextSharp.text.html.simpleparser.
StyleSheet styles = new iTextSharp.text.html.simpleparser.StyleSheet();
styles.LoadTagStyle("ol", "leading", "16,0");
PdfWriter.GetInstance(document, new FileStream(strPDFpath, FileMode.Create));
document.Add(new Header(iTextSharp.text.html.Markup.HTML_ATTR_STYLESHEET, "Style.css"));
document.Open();
ArrayList objects;
styles.LoadTagStyle("li", "face", "garamond");
styles.LoadTagStyle("span", "size", "8px");
styles.LoadTagStyle("body", "font-family", "times new roman");
styles.LoadTagStyle("body", "font-size", "10px");
document.NewPage();
objects = iTextSharp.text.html.simpleparser.
HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);
for (int k = 0; k < objects.Count; k++)
{
document.Add((IElement)objects[k]);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
document.Close();
Response.Write(Server.MapPath("~/" + strPDFpath));
Response.ClearContent();
Response.ClearHeaders();
Response.AddHeader("Content-Disposition", "attachment; filename=" + strPDFpath);
Response.ContentType = "application/octet-stream";
Response.WriteFile(Server.MapPath("~/" + strPDFpath));
Response.Flush();
Response.Close();
if (File.Exists(Server.MapPath("~/" + strPDFpath)))
{
File.Delete(Server.MapPath("~/" + strPDFpath));
}
}Whether you found this article useful or not? please provide your valuable comments.

Hi!
I used ur Code, didn’t change even 1 leter. Build succsess, but when i browse it i got a mistake:
“~/C:\Inetpub\wwwroot\FinfoBase\Admin\FINFOBASE_Form\MyPDF.pdf’ is not a valid virtual path” – C:\Inetpub\wwwroot\FinfoBase is where i placed my project.

Thanks hspinfo for the response, but now i get another error, name “Could not find file ‘C:\Inetpub\wwwroot\FinfoBase\Admin\FINFOBASE_Form\MyPDF.pdf'”.
I guess that i failed to generate the “MyPDF.pdf” file or “MyHTML.html” file from the begining but i dont know how to fix it.
Could you mind send me the example you ‘ve done so that better for me and dont waste your time.
Thanks again .

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using iTextSharp.text;
using iTextSharp.text.pdf;
using System.Text;
using System.IO;
using FinfoBase.Engine;

Pls assign path to the variable strPDFPath, and strHTMLPath while declaring, and use the same variable for all process it as below, and do not provide any static path during the process:
string strHTMLpath = Server.MapPath(”~/Admin/FINFOBASE_Form/MyHTML.htm”);
string strPDFpath = Server.MapPath(”~/Admin/FINFOBASE_Form/MyPDF.pdf”);

The reason the HTML file is still in use is because the HtmlTextWriter is never closed in the code. The easiest way to remedy this would be in the finally block add the line
htw.Close();
NOTE: you will also need to move the definition of htw out of the try block so that it is available inside the finaly block.
This should release any resources held by the HtmlTextWriter object and let you reuse the file.:-)

hi!
Thank you very much for your information about convert html to pdf but i can’t convert this especially another text for example can you help me how can ı convert in asp.net FCKEditor1.value convent to pdf with html tags like tables or msn smiles or normal text.
i need so much very urgently .
Thank for your interest
i am waiting for your return
Güncel Sarıman

oas’s code works well. I want to create a asp webform using vb.net, when click a button on the page, a table on the page will be saved to a pdf file, how can I change the code, like change strHTMLpath to table ID. Thanks.

Hello, i’m looking to find a list of the attributes that you can use with the StyleSheet.LoadTagStyle and their definition.
Is that available anywhere? Specifically, other than controlling font and font size i want to control vertical whitespace and indentation. the “leading” tag almost does this, but does not quite do what i hoped for.

Iam using the code given by you for converting my web page to pdf but iam having the problem of binding my gridview because iam using data list inside the datagrid for my data representation..and how to do this phenomenon…Please help me..My requirement is very urgent

Thanks a Lot !!!
Very Gud Site. But i’ am getting a problem. I’ am not able to add image in my string builder. Or i closed the htw in the finally block but still it give me an error message “HTML file is used It is used by another Process”.

Thanks Pradeep it’s working fine. But i’ am facing two more issues:
1. How we can Merge PDF Files
2. Can we add an image in our html string (Actually) it is not taking the path. It give me an exception “IT is not a virtual path”.

In my output pdf the font sizes and other html formatting are coming through in the pdf but not font styles..

Registering a certain font for a tag like ariel for span tag wouldn’t make sense in my case since the user can enter different font families for style tags, for instance they have may the word Hello in ariel followed by the name in Courier font. Any ideas?

Hi, I am getting an error….
“Could not find a part of the path ‘C:\Registration_files\image001.gif’.”

I am converting Registration.html file which has its Registration_files folder in the same folder as the file is in. But still the code checks for files in “C:\Registration_files\..” a fixed location. I have never given this as default location.

am am convert aspx page to PDf using your First code it generate html and pdf file successfully in Html format abd css is Ok but for Pdf formate are not Set alignment of table are not looking god 3 html page become 14 Pdf pages can you provide me any sugestion

hi,
I convert HTML page to PDF by using your code and it helped me a lot. It works fine in Internet Explorer but give an error in Mozilla.
Error is showing in this line “objects = iTextSharp.text.html.simpleparser.HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);”

hi,
Now it is working also in Mozilla but there is alignment problem. All contents are writing left align forcefully in IE and right align forcefully in Mozilla but actual alignment in HTML is center.
Can u help me It is very argent .

I used ur code,i am getting error like ” Cannot implicitly convert type ‘System.Collections.Generic.List’ to ‘System.Collections.ArrayList'” at HTMLWorker.ParseToList(new StreamReader(strHTMLpath, Encoding.Default), styles);
Can some one help me,i need very urgent

//gvSearchResult is a GridView, I have converted its content to HTML and will acquire final PDF file
/*Here i have set AllowPaging and AllowSorting property of GridView as false, As my aim is to get whole content of the GridView in a single table, by setting these properties and binding the GridView again will remove paging and sorting property from it. */

FormView1.AllowPaging = false;

fillFromView(Asso_code);

//Rendering the HtmlTextWriter

FormView1.RenderControl(htw);

/*Here i have set AllowPaging and AllowSorting property of GridView as true, As my aim is to get whole content of the GridView is now finished and I have acquire its content in HtmlTextWriter. Then by setting properties again I will get the original form of my GridView again*/

You should supply the source code. I find that copying and pasting does not do what you suggest it does. But I have my own working version. I was really just trying to figure out how to incorrperate css in the pdf. I tried to link the page to a css page, did’t work, tried inline tags, didn’t work. tried styles.LoadTagStyle(“span”, “size”, “8px”);, and still nothing. I see that you were doing it. and seen several good comments but I could not get your project to run. How ever my does just does not take the css.

I like the valuable info you provide in your articles.
I’ll bookmark your weblog and take a look at once more here frequently. I am quite certain I’ll be told a lot of new stuff proper here!
Good luck for the next!