Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Absolute position when converting HTML to PDF with iTextSharp

I am using iTextSharp to convert HTML to PDF and it doesn't seem to work with absolutely positioned elements. For example I have this HTML file:

<html>
<body>
    <p style="position: absolute; left: 10px; top: 100px; width: 50px;">Hello World</p>
</body>
</html>

The text is not correctly positioned in the resulting PDF file. Do you know if it is possible to have absolutely positioned elements when converting HTML to PDF? Any free solution (iTextSharp or other) that allows this would be greatly appreciated.

Here's the code I am using to perform the conversion with iTextSharp:

class Program
{
    static void Main(string[] args)
    {
        Document document = new Document(PageSize.A4);
        using (Stream output = new FileStream("out.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
        using (Stream htmlStream = new FileStream("input.htm", FileMode.Open, FileAccess.Read, FileShare.Read))
        using (XmlTextReader reader = new XmlTextReader(htmlStream))
        {
            PdfWriter.GetInstance(document, output);
            HtmlParser.Parse(document, reader);
        }
        Process.Start(@"C:\Program Files\Adobe\Reader 9.0\Reader\AcroRd32.exe", "out.pdf");
    }
}        

EDIT:

After further investigation it seems that iTextSharp's HTML to PDF conversion capability is limited to some very simple HTML documents. There's a nice Java project called Flying Saucer which handles complex HTML documents. So I tried using it with IKVM and it worked very well. The only problem is that it feels somehow a dirty solution. Adding 31MB of assembly code for HTML to PDF conversion seems quite much. Are there any better and "free" alternatives to handle this scenario.

like image 624
Darin Dimitrov Avatar asked Nov 05 '22 21:11

Darin Dimitrov


1 Answers

I finally decided to use xhtmlrenderer. It perfectly fits my needs, it has many features and it was able to correctly render any of my HTML files.

As currently it has only a JAVA version I had to convert the jars into a .NET assembly with IKVM.

like image 105
Darin Dimitrov Avatar answered Nov 15 '22 07:11

Darin Dimitrov