jgilmore
jgilmore

Reputation: 91

HTMLRenderer and PDFSharp not rendering tables well even with embedded styles

I'm trying to use HTMLRenderer and PDFSharp to output a PDF file. But I'm noticing that even very simple tables don't render correctly. I embed the style right in the web page. I even tried style tags right on the elements and it ignores them.

Am I missing something here?

using PdfSharp.Pdf;
using System.IO;
using TheArtOfDev.HtmlRenderer.PdfSharp;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            string html = File.ReadAllText(@"1.htm");
            PdfDocument pdf = PdfGenerator.GeneratePdf(html, PageSize.Letter);
            pdf.Save(@"1.pdf");
        }
    }
}

<!DOCTYPE html>

<html lang="en" xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta charset="utf-8" />
    <title></title>
    <style>
        .hdr { background-color:gray;}
        .cell {background-color:burlywood;}
        tr { color:blue;}
    </style>
</head>
<body>
    <table>
        <tr class="hdr"><td>Colum1</td><td>Column2</td></tr>
        <tr style="background-color: lightblue"><td>Chevy</td><td>Malibu</td></tr>
        <tr><td class="cell">Honda</td><td style="background-color:gold">Accord</td></tr>
    </table>
</body>
</html>

Output of browser on top and PDF on bottom:

Rendered table using browser and pdf

Upvotes: 1

Views: 6259

Answers (1)

jgilmore
jgilmore

Reputation: 91

I wasn't able to find a solution to my question, therefore, I found an alternative solution. I switched to Select HtmlToPdf. This is in NUGET.

The implementation is straightforward

static void Main(string[] args)
{
    SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
    SelectPdf.PdfDocument doc = converter.ConvertHtmlString(File.ReadAllText("3.htm"), @"file:///dev/pdf4/ConsoleApp1/");
    doc.Save("3.pdf");
    doc.Close();
}

They offer a free version that limits you to 5 pages and has a few other limitations, but it did the job I was looking for without me having to modify my Html.

I also like how they implemented image rendering. By specifying a base url, it renders images the way you expect without having to do any tricks. The table borders are a little messy, but not too bad.

Upvotes: 4

Related Questions