Sunday, 28 July 2013

Html to Pdf document conversion in .Net

Hi, in this post I am going to share very simple and easy way to convert HTML document to Pdf file on the fly on just one click , you can use it from desktop as well as web application to convert a html page either from local storage or online web page.Lets start this , we are going to use PDFizer ( for this task , a very easy and simple open source library to use for .net apps.Download that form above url and use the following code for creating a PDF document from html source.

  1. Include pdfizer.dll into reference of your project
  2. Specify the path where to store created pdf file                                                                              
           static  string sPathToWritePdfTo = "Report.pdf";
  3. Create a simple method                                                                                                                      public static void HtmlToPdf(string htmlString,string sPathToWritePdf)

               Stream stream = new FileStream(sPathToWritePdf, FileMode.Create);
               HtmlToPdfConverter htmlToPdf = new HtmlToPdfConverter();

  4. Use above method to create Pdf file from html source like following                                             StringBuilder sbHtml = new StringBuilder();
                sbHtml.Append("This is my document text ");

And that all , your pdf is ready to use , you can convert html by reading html source from .html file , by downloading html from url by get request to url like :
public static String code(string Url)
            HttpWebRequest myRequest = (HttpWebRequest)WebRequest.Create(Url);
            myRequest.Method = "GET";
            WebResponse myResponse = myRequest.GetResponse();
            StreamReader sr = new StreamReader(myResponse.GetResponseStream(),
            string result = sr.ReadToEnd();
            return result;
This method will return you html source of the input url so you can create 
your pdf of online resources like that.

Recently during R&D I found another opensource pdf creation library for .net which seems to be more powerful (not sure), here is the link for library 
"PDFSharp" "" , will surely get into it when got some time :)
A very useful post from another forum is "".