QuestPDF is a really neat library. But in my situation, I need the ability to insert HTML snippets into PDFs, which is not supported functionality. See QuestPDF issue 134. To be fair, converting HTML to PDF is wildly complicated if you want to support every CSS feature. There are paid libraries from Syncfusion, for example, that do this. But these libraries tend to have large dependency footprints and do way more than I need.
Fortunately, my requirements are pretty modest. This project represents my attempt at PDF conversion from HTML, supporting a very small feature set. There are two main things I needed to do:
- get an XML document (in the form of
XDocument
orXElement
) from a string, with some forgiveness built-in for certain malformed tags. In my use case, the HTML is not perfectly XHTML-compliant. But I needed a valid XML document before attempting any conversion. This is theXmlHelper.ToDocument
method below. - provide an extension method that works with QuestPDF's
IContainer
that does the actual conversion.
See this in use in my test method. Note that I couldn't seem to get a real unit test working with a binary comparison of expected and actual PDF outputs. It appears that there are always minor differences between outputs of the same PDF. I've seen this symptom in other PDF libraries, so I figure this is just how it is with PDFs. In any case, I was pretty happy to get this much working.
QuestPdfUtil.QuestPdfHelper QuestPdfHelper.cs
- void Html (this IContainer container, XDocument document, [ Action spanAction ])
- void Html (this IContainer container, string html, [ Dictionary<string, string> replacements ], [ Action spanAction ])
- void Html (this IContainer container, XElement element, [ Action spanAction ])
QuestPdfUtil.XmlHelper XmlHelper.cs
- XDocument ToDocument (string input, [ string defaultEnclosingTag ], [ Dictionary<string, string>? replacements ])