Converting HTML to PDF in a Legacy iTextSharp Project

Editorial illustration.

Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.

The HTML invoice looks crisp in Chrome, so you wire up the PDF export endpoint, click Download, and get no exceptions. Then you open the PDF. The margins are off, the custom font fell back to Helvetica, a table header is stranded at the bottom of page one, and your clean Flexbox layout collapsed into a single vertical stack.

In legacy .NET Framework and ASP.NET MVC applications, this usually happens because the project is using iTextSharp 5 together with itextsharp.xmlworker. Getting a reliable PDF out of that stack means working with what XML Worker actually supports rather than treating it like a headless browser.

Know What XML Worker Can and Cannot Render

iTextSharp 5 and XML Worker belong to a legacy generation of the iText library—iText’s legacy product page outlines its status and points newer projects toward iText 7 / pdfHTML. XML Worker parses a subset of XHTML and CSS 2.1. It does not execute JavaScript, and it does not understand modern CSS like Flexbox, CSS Grid, calc(), or CSS custom properties (var(--color)).

If you are maintaining an existing system and cannot replace the PDF engine right away, design your HTML template specifically for XML Worker:

  • Use classic HTML <table> structures for multi-column layouts (like invoice headers and totals).
  • Keep your HTML strictly well-formed XHTML—self-closing tags like <br /> and <img ... /> matter because XML Worker will throw parsing exceptions on unclosed tags that browsers silently forgive.
  • Inline critical CSS or pass a dedicated print stylesheet directly into XMLWorkerHelper rather than relying on external Bootstrap or Tailwind files.

Also check your NuGet dependencies and licence terms before upgrading anything. Jumping from iTextSharp 5 to iText 7 or another library is a full rewrite of the rendering code, not a namespace swap.

MemoryStream, Fonts, and Resource Paths

Two bugs show up constantly in iTextSharp HTML-to-PDF handlers. The first is the Stream closed exception when returning the PDF bytes from an ASP.NET controller. By default, closing iTextSharp.text.Document also closes the underlying MemoryStream. Set writer.CloseStream = false before closing the document, or call ms.ToArray() carefully after document.Close():

using var ms = new MemoryStream();
using var document = new Document(PageSize.A4, 36f, 36f, 36f, 36f);
var writer = PdfWriter.GetInstance(document, ms);
writer.CloseStream = false;

document.Open();
using var sr = new StringReader(safeHtml);
XMLWorkerHelper.GetInstance().ParseXHtml(writer, document, sr);
document.Close();

ms.Position = 0;
return ms.ToArray();

The second headache is fonts. If your document contains Malay, Arabic, Chinese, or even certain currency symbols, default PDF fonts will quietly drop them and render blank spaces. You need to register a Unicode TrueType font (such as Noto Sans or Arial Unicode) using a custom FontFactoryImp or XMLWorkerFontProvider and point it to a local .ttf file on disk with BaseFont.IDENTITY_H.

Lock Down Untrusted HTML and External Requests

Never pass raw user-submitted HTML straight into ParseXHtml. Even if the template looks harmless, user-controlled <img src="..."> or <link> tags can trigger Server-Side Request Forgery (SSRF) if the PDF renderer tries to fetch internal network URLs or local file paths during generation.

Treat the HTML template as a controlled server-side asset:

  • Encode all dynamic fields (WebUtility.HtmlEncode) before interpolating them into the template.
  • Resolve images and stylesheets through an explicit IImageProvider or local base path rather than letting the parser hit arbitrary external URLs.
  • Enforce record-level authorization on the export endpoint, plus sensible limits on input size and execution time so a malformed template cannot tie up IIS worker threads.

Inspect the Rendered Pages, Not Just the Exit Code

Automated tests that only assert pdfBytes.Length > 0 or check for %PDF- at the start of the stream will miss almost every layout bug. Whenever you touch a legacy PDF template, test it with awkward real-world data: long customer names that wrap onto three lines, 40-row tables that cross page boundaries, empty optional sections, and missing logo files.

Open the generated file in an actual PDF viewer (not just a quick browser preview) and check page breaks, margins, and text selection. Before changing any package versions or shared CSS, save a small folder of “known good” reference PDFs so you can visually compare the output after each change. If a legacy project eventually outgrows those constraints—especially when clients demand modern CSS layouts—that is the point to evaluate modern alternatives like Playwright, PuppeteerSharp, or code-first libraries such as QuestPDF.