
Editorial illustration.
Originally published 23 June 2023; rewritten and reviewed on 15 October 2026.
Getting a “Hello, World” PDF out of C# takes ten lines of code. Getting a reliable, multi-page invoice or statement out of a live ASP.NET application without corrupting the file, leaking memory, or mangling characters is a different story. Every time I revisit an older iTextSharp integration—usually in a legacy .NET Framework portal that still generates RM receipts or SST tax invoices—the bugs almost never come from the layout. They come from stream ownership and lifecycle order.
Know which iText generation you are maintaining
Document and PdfWriter belong to iTextSharp (the 5.x port of iText to .NET, now end-of-life). If you are maintaining an existing codebase that already references iTextSharp.LGPLv2.Core or the classic iTextSharp NuGet package, keeping it working makes sense. If you are starting a greenfield .NET 8 project, though, you should check the licensing first: iText 7/8 is AGPLv3 unless you buy a commercial licence, whereas alternatives like QuestPDF (Community licence for smaller teams/revenue) or PuppeteerSharp/Playwright for HTML-to-PDF might fit your budget better.
Whatever wrapper you use, iTextSharp expects a strict lifecycle. If you skip a step or dispose things out of order, you end up with a 0-byte file or a PDF that Adobe Acrobat refuses to open because the cross-reference table at the end was never flushed.
Stream ownership and the CloseStream trap
The most common mistake in web endpoints is writing to a MemoryStream and then trying to read it after document.Close(). By default, PdfWriter closes the underlying stream when document.Close() runs. If you pass ms.ToArray(), it still works because ToArray() copies the internal buffer even on a closed MemoryStream, but if you try to rewind ms.Position = 0 and pass the stream itself to File(ms, "application/pdf"), ASP.NET throws ObjectDisposedException: Cannot access a closed Stream.
Setting writer.CloseStream = false makes ownership explicit:
using System;
using System.IO;
using iTextSharp.text;
using iTextSharp.text.pdf;
public byte[] BuildInvoicePdf(string invoiceNo, string customerName, decimal totalRm)
{
using var ms = new MemoryStream();
using (var document = new Document(PageSize.A4, 36f, 36f, 48f, 48f))
{
var writer = PdfWriter.GetInstance(document, ms);
writer.CloseStream = false;
document.Open();
// Embed a Unicode-capable font so symbols and non-ASCII names render properly
var fontPath = Path.Combine(AppContext.BaseDirectory, "Fonts", "Inter-Regular.ttf");
var baseFont = BaseFont.CreateFont(fontPath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
var bodyFont = new Font(baseFont, 10f, Font.NORMAL);
var headerFont = new Font(baseFont, 14f, Font.BOLD);
document.Add(new Paragraph($"Tax Invoice #{invoiceNo}", headerFont));
document.Add(new Paragraph($"Billed to: {customerName}", bodyFont));
document.Add(new Paragraph($"Total Payable: RM {totalRm:N2}", bodyFont));
document.Close();
}
return ms.ToArray();
}
Notice the order: document.Close() runs before ms.ToArray(), because Close() is what actually writes the PDF trailer and flushes buffered page content into the stream. And writer.CloseStream = false guarantees the outer using var ms remains the single owner of the MemoryStream.
Fonts, character sets, and real data
iTextSharp’s built-in Helvetica and Times-Roman constants use WinAnsi encoding. They work fine for basic ASCII English, but the moment a customer’s address includes a Chinese company name, Tamil characters, or a less common Unicode symbol, WinAnsi silently drops those characters and leaves blank spaces on the invoice.
Embedding a .ttf font with BaseFont.IDENTITY_H and BaseFont.EMBEDDED solves that, at the cost of a slightly larger PDF. Always test your template against real production edge cases:
- Long item descriptions that wrap across two pages inside a
PdfPTable(make suretable.HeaderRows = 1is set so the column headers repeat on page two). - Customer names with diacritics or CJK characters.
- User-supplied filenames—never build a disk path like
Path.Combine(tempDir, request.FileName)without sanitising it, or better yet, stream straight from memory and assign a generated GUID if you must cache to disk.
Do not serve an HTML error page as a .pdf
Nothing confuses end users more than clicking “Download Receipt”, getting a receipt-1042.pdf file, and seeing “Failed to load PDF document” in Chrome because the server actually returned an IIS yellow screen of death or an HTML 500 error page with a .pdf filename attached.
Keep the PDF generation in a dedicated service method that completes before you set response headers:
try
{
byte[] pdfBytes = _invoiceService.BuildInvoicePdf(id);
return File(pdfBytes, "application/pdf", $"invoice-{id}.pdf");
}
catch (Exception ex)
{
_logger.LogError(ex, "Failed to generate PDF for invoice {InvoiceId}", id);
return Problem("Unable to generate the invoice PDF right now.", statusCode: 500);
}
If generation fails before File(...) is returned, the client receives a proper HTTP 500 JSON/problem response instead of a broken download. And before shipping any template change, open the generated .pdf in both Chrome’s viewer and Adobe Acrobat—subtle font or table border issues often show up in one and not the other.