Showing posts with label HtmlToPDF. Show all posts
Showing posts with label HtmlToPDF. Show all posts

Thursday, 12 January 2017

C# HTML to PDF Converter, iTextSharp

Hi All, we 've made lot of research to make this super useful function in c# to convert HTML to PDF,
with help of fantastic free library iTextSharp:

https://sourceforge.net/projects/itextsharp/
With only 6 rows it's done!
Warning!: HTML code must be very clear, simple and clean(CSS was not fully supported, is better use attributes to element if exists)
Example:

<!--lwebcode:inside yout html code-->
<div style='font-size:15px;text-align:left;'>Title Of Page<br/></div> ==> Works
<td align='center' style='width:15%' >cell content</td> ==> DOESN'T Works
<td align='center' width='15%' >cell content</td> ==> Works

//lwebcode:inside *.cs file
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.text.html;
using iTextSharp.text.html.simpleparser;
using iTextSharp.tool.xml;

//
lwebcode:inside your class lwebcode
private void ConvertHtmlToPdf(string sHTML)
    {
        Document document = new Document();
        PdfWriter.GetInstance(document, new FileStream(Server.MapPath("~/OutPath/TargetName.pdf"), FileMode.Create));
        document.Open();
        iTextSharp.text.html.simpleparser.HTMLWorker hw = new iTextSharp.text.html.simpleparser.HTMLWorker(document);
        hw.Parse(new StringReader(sHTML));
        document.Close();
    }