Pages

Friday, September 9, 2011

How to Convert Html to PDF in ASP.NET , C# Using iTextsharp

There are many solutions can convert html to PDF.

However they have different effects. As far as I know, the simplest solution that I ever seen is using iTextsharp and the code as below:

 Sample Code:

         string FilePath = Server.MapPath("") + "/OrderconfirmationMail.htm";
         System.IO.StreamReader myFile =new System.IO.StreamReader(FilePath);
         string myString = myFile.ReadToEnd();
         myFile.Close();
         string ImagePath = Server.MapPath("") + "\\Images\\";
        myString = myString.Replace("src=\"Images/", ImagePath);
         StringReader sr = new StringReader(myString);
         iTextSharp.text.Document pdfDoc = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 2f, 2f, 2f, 2f);
         HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
         string filename = Server.MapPath("") + "\\WordDoc\\parsetest3.pdf";
       

         if (File.Exists(filename))
         {
             File.Delete(filename);
         }
         PdfWriter.GetInstance(pdfDoc, new FileStream(filename, FileMode.Create));
         pdfDoc.Open();
         htmlparser.Parse(sr);
         pdfDoc.Close();
         Response.Write(pdfDoc);


I found some links where you can find details:

  • http://stackoverflow.com/questions/2822843/itextsharp-html-to-pdf
  • http://hamang.net/2008/08/14/html-to-pdf-in-net/
  • http://forums.asp.net/t/1596224.aspx/1
  • http://aspdotnetcodebook.blogspot.com/2008/07/how-to-export-content-of-gridview-to.html
  • http://channel9.msdn.com/Forums/TechOff/117199-ASPNET-and-iTextSharp-free-PDF-Generator-for-NET

ShareThis

Welcome

Welcome to Rajesh Prajapati, asp.net blog.
Here you can find some useful code and information about asp.net., c#, VB.net, SQL Server, Web Service, Web Designing etc