Why does PDFSharp fail to convert a string containing <div style='display:flex

Summary

This incident occurred because PDFSharp does not support modern HTML or CSS, including flexbox, styled <div> elements, or anything beyond extremely limited, legacy HTML. When the input contained a <div style='display:flex'>, the rendering engine silently failed and produced a blank PDF.

Root Cause

The root cause is that PDFSharp’s HTML renderer is not a browser engine. It only understands a tiny subset of HTML and almost no CSS.

Key points:

  • PdfGenerator.GeneratePdf() uses HtmlRenderer, which supports only basic tags (<p>, <b>, <i>, <ul>, etc.).
  • CSS layout features like display:flex, justify-content, or modern block-level styling are not implemented.
  • When encountering unsupported markup, the renderer often fails without throwing an exception, resulting in an empty PDF.

Why This Happens in Real Systems

Real-world PDF libraries often:

  • Implement partial HTML support to avoid embedding a full browser engine.
  • Fail silently when encountering unknown CSS properties.
  • Assume developers will sanitize or preprocess HTML before rendering.

PDFSharp is designed for PDF creation, not HTML rendering, so its HTML support is intentionally minimal.

Real-World Impact

Unsupported HTML can cause:

  • Blank PDFs
  • Missing sections of content
  • Layout corruption
  • Silent failures that mislead developers into thinking the input is valid

This is especially common when developers assume PDFSharp behaves like a browser.

Example or Code (if necessary and relevant)

A minimal example that fails:

var html = "
Hello
"; PdfGenerator.GeneratePdf(html, PageSize.A4);

A minimal example that works:

var html = "

Hello

"; PdfGenerator.GeneratePdf(html, PageSize.A4);

How Senior Engineers Fix It

Experienced engineers typically:

  • Strip unsupported CSS before rendering.
  • Replace complex HTML with simple, PDFSharp‑friendly markup.
  • Switch to a library with full HTML/CSS support, such as:
    • PuppeteerSharp (Chromium-based)
    • DinkToPdf / wkhtmltopdf
    • QuestPDF (layout engine, not HTML)
  • Pre-render HTML using a real browser engine, then convert to PDF.

Key takeaway: If you need real HTML/CSS rendering, PDFSharp is the wrong tool.

Why Juniors Miss It

Common reasons:

  • They assume all HTML-to-PDF libraries behave like a web browser.
  • They expect CSS to be interpreted, not ignored.
  • They don’t realize PDFSharp’s HTML support is intentionally minimal.
  • They trust the absence of exceptions as proof that the input is valid.

The misunderstanding is natural—PDF rendering is not the same as HTML rendering, and PDFSharp does not try to be a browser.

Leave a Comment