0

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

jgilmore
  • 29
  • 4

1 Answers1

1

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.

jgilmore
  • 29
  • 4
  • Another solution you may want to check out is [GemBox.Document](https://www.gemboxsoftware.com/document) (also found on [NuGet](https://www.nuget.org/packages/GemBox.Document/)). It also has a free version with size limitation and the code is rather simple, a one-liner: "DocumentModel.Load("3.htm").Save("3.pdf");" – Mario Z Jan 20 '20 at 02:28