LLION/ PDF, print & document engineering

Generating PDFs with C# and .NET

LLION Editorial · Updated

.NET has one of the healthier PDF ecosystems: a modern layout engine, a long-lived drawing library, the .NET port of iText, a capable reader, and two headless-Chromium drivers. The decision is mostly about licensing and about where the code will run, because the libraries that look identical on a Windows laptop behave very differently in a Linux container with no fonts installed.

## The options
LibraryApproachLicencePackageBest forAvoid when
QuestPDFLayout engine with a fluent C# APICommunity License (free if annual gross revenue is under USD 1,000,000, or for charities, academic institutions, OSI-licensed open source and individuals; public-sector bodies and publicly traded companies excluded); Professional and Enterprise paidQuestPDFInvoices, reports, anything paginated from dataYou must read or edit existing PDFs; your organisation is above the revenue threshold and will not buy a licence
PDFsharp 6.2.xDrawing API (points on a page); MigraDoc adds a document modelMIT (last MIT release 6.2.4, January 2026)PDFsharp, PDFsharp-MigraDocFixed layouts, stamping, merging, forms; teams that need a permissive licenceYou need the newest features; 6.5.0 changed licence
PDFsharp 6.5.0 and 7.0 previewsSame APIAGPL-3.0-only or commercial; the application must call PdfSharpLicense.SetAgplLicense() or load a purchased keysameProjects that can comply with AGPL or hold a commercial keyClosed-source products without a commercial licence
iText 9 (iText Core)Drawing API plus a layout moduleAGPL-3.0 or commercial; iTextSharp 5 is end-of-lifeitext and itext.bouncy-castle-adapterSignatures, forms, PDF/A, tagged PDF, the widest feature setYou cannot release your source under AGPL and will not buy a licence
PdfPigReader and text extractor; basic builderApache-2.0PdfPigReading text and layout from existing filesGenerating complex documents
PuppeteerSharpHeadless Chromium (HTML renderer)MITPuppeteerSharpDocuments that exist as HTML templatesEnvironments where running a browser is not allowed
Microsoft.PlaywrightHeadless Chromium (HTML renderer)MIT (the .NET package); browsers installed separatelyMicrosoft.PlaywrightSame as above, with a multi-browser test storySame
Syncfusion, IronPDF, AsposeCommercial suites (drawing, HTML, conversion)Commercialvendor packagesEnterprise support contractsOpen-source or budget-constrained projects

Two licence facts matter more than any feature. First, PDFsharp changed licence in 6.5.0 (October 2026): the 6.2 line is MIT, and from 6.5.0 the package is dual AGPL-3.0 or commercial and refuses to run until your code selects a licence. Pin to 6.2.4 if MIT is a requirement. Second, QuestPDF's free tier is a revenue test, not an open-source test: a company above USD 1,000,000 in annual gross revenue needs a paid licence even for internal tools, with a 60-day evaluation window.

For the general choice between drawing, layout and HTML rendering, the developers hub has the decision table; this page assumes you have made it.

QuestPDF: an invoice with a table and page numbers#

QuestPDF describes a document as nested containers. Page size, margins and default text style are set once; the header, content and footer are slots; a table is declared with its columns and filled cell by cell. Page numbers come from the text API and are resolved after layout.

Program.cs (QuestPDF 2025.x, written against the docs, not executed here)C#
using QuestPDF.Drawing;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;

// Required at startup. Use Professional or Enterprise if you hold a paid key.
QuestPDF.Settings.License = LicenseType.Community;

// Ship your own font; do not rely on fonts installed on the server.
FontManager.RegisterFontFromFile("fonts/Inter-Regular.ttf");

var lines = new[]
{
    ("Design review", 4m, 120m),
    ("Implementation", 16m, 120m),
    ("Deployment support", 2m, 150m),
};

Document.Create(container =>
{
    container.Page(page =>
    {
        page.Size(PageSizes.A4);
        page.Margin(2, Unit.Centimetre);
        page.DefaultTextStyle(x => x.FontFamily("Inter").FontSize(10));

        page.Header()
            .Text("Invoice 2026-0142")
            .SemiBold().FontSize(20);

        page.Content()
            .PaddingVertical(1, Unit.Centimetre)
            .Table(table =>
            {
                table.ColumnsDefinition(columns =>
                {
                    columns.RelativeColumn(3);
                    columns.ConstantColumn(70);
                    columns.ConstantColumn(80);
                    columns.ConstantColumn(90);
                });

                table.Header(header =>
                {
                    header.Cell().BorderBottom(1).Padding(6).Text("Item");
                    header.Cell().BorderBottom(1).Padding(6).AlignRight().Text("Hours");
                    header.Cell().BorderBottom(1).Padding(6).AlignRight().Text("Rate");
                    header.Cell().BorderBottom(1).Padding(6).AlignRight().Text("Amount");
                });

                foreach (var (item, hours, rate) in lines)
                {
                    table.Cell().Padding(6).Text(item);
                    table.Cell().Padding(6).AlignRight().Text($"{hours:0.##}");
                    table.Cell().Padding(6).AlignRight().Text($"{rate:0.00}");
                    table.Cell().Padding(6).AlignRight().Text($"{hours * rate:0.00}");
                }
            });

        page.Footer()
            .AlignCenter()
            .Text(x =>
            {
                x.Span("Page ");
                x.CurrentPageNumber();
                x.Span(" of ");
                x.TotalPages();
            });
    });
})
.GeneratePdf("invoice.pdf");

The header block of a table repeats on every page the table spans, which is the behaviour you want for long line-item lists. Column widths mix relative and constant units; ConstantColumn(70) is 70 points. Install with dotnet add package QuestPDF.

QuestPDF ships Lato as its default font and, by default, throws when a glyph is missing rather than printing a placeholder (QuestPDF.Settings.ThrowOnMissingTextGlyphs, enabled by default). That is the right default: a missing glyph discovered in a test is cheaper than one discovered by a customer. System fonts are not used unless QuestPDF.Settings.UseSystemFonts = true is set, and the documentation recommends deploying font files with the application instead.

PDFsharp: drawing text with your own font resolver#

PDFsharp works at the level of a page and a graphics context, much like System.Drawing. It is the natural tool for stamping text onto existing pages, merging, splitting and form filling, and for fixed layouts where you know the coordinates.

The part that catches people is fonts. The Core build of PDFsharp has no platform font lookup on Linux or macOS and throws when an XFont is created unless a font resolver is installed. On Windows, GlobalFontSettings.UseWindowsFontsUnderWindows = true reads a handful of families from C:\Windows\Fonts, which the documentation describes as suitable for development only. For production you implement IFontResolver, which maps a family name to a face name and returns the font bytes.

Program.cs (PDFsharp 6.2.4, MIT; written against the docs, not executed here)C#
using PdfSharp.Drawing;
using PdfSharp.Fonts;
using PdfSharp.Pdf;

// Resolve every request to the fonts shipped with the application.
public sealed class AppFontResolver : IFontResolver
{
    public FontResolverInfo? ResolveTypeface(string familyName, bool bold, bool italic)
    {
        // Face names are identifiers you choose; PDFsharp caches the result.
        var face = bold ? "Inter#Bold" : "Inter#Regular";
        return new FontResolverInfo(face, false, italic);
    }

    public byte[]? GetFont(string faceName) => faceName switch
    {
        "Inter#Bold" => File.ReadAllBytes("fonts/Inter-Bold.ttf"),
        _ => File.ReadAllBytes("fonts/Inter-Regular.ttf"),
    };
}

static class Program
{
    static void Main()
    {
        // Must be set once, before the first XFont is created.
        GlobalFontSettings.FontResolver = new AppFontResolver();

        var document = new PdfDocument();
        document.Info.Title = "Certificate";

        var page = document.AddPage();
        page.Size = PdfSharp.PageSize.A4;

        var gfx = XGraphics.FromPdfPage(page);
        var title = new XFont("Inter", 24, XFontStyleEx.Bold);
        var body = new XFont("Inter", 12);

        // Coordinates are in points from the top-left corner of the page.
        gfx.DrawString("Certificate of completion", title, XBrushes.Black, new XPoint(72, 120));
        gfx.DrawString("Issued 29 October 2026", body, XBrushes.Black, new XPoint(72, 160));
        gfx.DrawLine(XPens.Black, 72, 180, 523, 180);

        document.Save("certificate.pdf");
    }
}

On PDFsharp 6.5.0 and later, add PdfSharpLicense.SetAgplLicense(); before any other call, or PdfSharpLicense.LoadLicense(key) with a commercial key; the library refuses to work otherwise. The font-resolver contract is the same across 6.x and 7.0.

PDFsharp's coordinate origin is the top-left corner with y pointing down, the opposite of the PDF coordinate system described on the units page; the library converts for you.

MigraDoc for paginated documents#

MigraDoc sits on top of PDFsharp and gives you a document model: sections, paragraphs, tables and styles that flow across pages. It is the right layer once content needs to wrap and paginate.

Report.cs (PDFsharp-MigraDoc 6.2.4; written against the docs, not executed here)C#
using MigraDoc.DocumentObjectModel;
using MigraDoc.DocumentObjectModel.Tables;
using MigraDoc.Rendering;

var document = new Document();
document.Styles["Normal"].Font.Name = "Inter";   // resolved by the same IFontResolver
document.Styles["Normal"].Font.Size = 10;

var section = document.AddSection();
section.PageSetup.PageFormat = PageFormat.A4;
section.AddParagraph("Monthly report").Format.Font.Size = 18;

var table = section.AddTable();
table.Borders.Width = 0.5;
table.AddColumn(Unit.FromCentimeter(10));
table.AddColumn(Unit.FromCentimeter(3));

var header = table.AddRow();
header.HeadingFormat = true;              // repeated on every page
header.Cells[0].AddParagraph("Metric");
header.Cells[1].AddParagraph("Value");

foreach (var (metric, value) in new[] { ("Documents", "12,480"), ("Pages", "91,002") })
{
    var row = table.AddRow();
    row.Cells[0].AddParagraph(metric);
    row.Cells[1].AddParagraph(value);
}

var renderer = new PdfDocumentRenderer { Document = document };
renderer.RenderDocument();
renderer.PdfDocument.Save("report.pdf");

iText 9: layout module with a table#

iText is the .NET port of the Java library and the most complete of the open-source options: digital signatures, AcroForm and XFA handling, PDF/A and PDF/UA creation, redaction and comparison tools in paid add-ons. The price is the licence. iText Core is AGPL-3.0, which obliges you to release the source of any application that uses it, including over a network, unless you buy a commercial licence. The .NET package also needs the Bouncy Castle adapter package since 8.0.2.

Program.cs (iText 9.8.0; written against the docs, not executed here)C#
using iText.IO.Font;
using iText.Kernel.Font;
using iText.Kernel.Pdf;
using iText.Layout;
using iText.Layout.Element;
using iText.Layout.Properties;

using var pdf = new PdfDocument(new PdfWriter("report.pdf"));
using var document = new Document(pdf);

// Embed a TrueType font with Identity-H so any Unicode text works.
var font = PdfFontFactory.CreateFont("fonts/Inter-Regular.ttf", PdfEncodings.IDENTITY_H);
document.SetFont(font).SetFontSize(10);

document.Add(new Paragraph("Quarterly summary").SetFontSize(18));

var table = new Table(UnitValue.CreatePercentArray(new float[] { 3, 1, 1 }))
    .UseAllAvailableWidth();
table.AddHeaderCell("Region");
table.AddHeaderCell("Units");
table.AddHeaderCell("Revenue");

foreach (var (region, units, revenue) in new[] { ("North", "1,204", "48,160.00"), ("South", "980", "39,200.00") })
{
    table.AddCell(region);
    table.AddCell(units);
    table.AddCell(revenue);
}

document.Add(table);

Header cells are repeated at the top of each page the table spans. Install with dotnet add package itext and dotnet add package itext.bouncy-castle-adapter; without the adapter, anything touching encryption or signatures fails at runtime.

Headless Chromium with PuppeteerSharp#

If the document is already an HTML template, rendering it with Chromium gives you CSS layout, web fonts and the print stylesheet for free. PuppeteerSharp drives a downloaded Chromium build; Microsoft.Playwright does the same with its own browser bundle. The HTML-to-PDF guide covers print CSS, headers, footers and the security of rendering untrusted HTML; here is the .NET side.

Program.cs (PuppeteerSharp 20.x; written against the docs, not executed here)C#
using PuppeteerSharp;
using PuppeteerSharp.Media;

// Downloads a matching Chromium build on first run; cache it in your image.
await new BrowserFetcher().DownloadAsync();

await using var browser = await Puppeteer.LaunchAsync(new LaunchOptions { Headless = true });
await using var page = await browser.NewPageAsync();

await page.SetContentAsync(File.ReadAllText("invoice.html"));
await page.EvaluateExpressionAsync("document.fonts.ready");   // wait for web fonts

await page.PdfAsync("invoice.pdf", new PdfOptions
{
    Format = PaperFormat.A4,
    PrintBackground = true,
    PreferCSSPageSize = true,            // honour @page { size: ... } if the CSS sets it
    MarginOptions = new MarginOptions { Top = "20mm", Right = "15mm", Bottom = "20mm", Left = "15mm" },
});

With Playwright the equivalent is await page.PdfAsync(new() { Path = "invoice.pdf", Format = "A4", PrintBackground = true }) after Playwright.CreateAsync() and playwright.Chromium.LaunchAsync(); the browsers are installed once with the playwright.ps1 install script that ships in the build output.

Reading existing files with PdfPig#

None of the generators above is the right tool for extracting text from PDFs you did not create. PdfPig (Apache-2.0) opens a document, exposes pages, words and letters with positions, and has a content-order text extractor that handles columns better than raw stream order. Its builder can produce simple documents, but that is a secondary feature.

Extract.cs (PdfPig 0.1.x; written against the docs, not executed here)C#
using UglyToad.PdfPig;
using UglyToad.PdfPig.DocumentLayoutAnalysis.TextExtractor;

using var document = PdfDocument.Open("input.pdf");
foreach (var page in document.GetPages())
{
    var text = ContentOrderTextExtractor.GetText(page);
    Console.WriteLine($"--- page {page.Number} ({page.Width:0} x {page.Height:0} pt)");
    Console.WriteLine(text);
}

Traps specific to .NET#

Fonts in containers. A Linux image built from a minimal base has no fonts, and each library reacts differently: QuestPDF falls back to its bundled Lato and throws on missing glyphs; PDFsharp Core throws on the first XFont unless a resolver is installed; iText embeds whatever file you point it at and fails only if the path is wrong; Chromium silently substitutes, which looks fine until a glyph is missing. In every case the fix is the same: ship the font files with the application and register them explicitly. The fonts page explains what embedding and subsetting mean in the output.

Licence checks at startup. QuestPDF and PDFsharp 6.5.0 and later both require a licence selection in code. Put it in the application's startup path, not in a lazily constructed service, so a misconfiguration fails at boot rather than on the first customer request.

AGPL reach. AGPL-3.0 applies to iText Core and to PDFsharp 6.5.0 and later. "Internal tool" is not an exemption in AGPL terms if users interact with it over a network. If legal review is a problem, pin PDFsharp to 6.2.4 (MIT), use QuestPDF under its Community License if eligible, or use PdfPig for reading.

Unicode and encodings. With iText, create fonts with PdfEncodings.IDENTITY_H for anything beyond Latin-1; the default simple-font encoding cannot represent most scripts. QuestPDF and PDFsharp handle Unicode through the font you register, so the question becomes whether that font has the glyphs.

Coordinate systems. PDFsharp and MigraDoc use a top-left origin; iText's low-level canvas uses the PDF origin at the bottom-left; QuestPDF hides coordinates entirely. Mixing libraries in one project means keeping that straight.

Checking the output. Open the result in the PDF inspector to confirm the fonts are embedded and subset, the page size is what you asked for, and the metadata (title, producer) is what you intended. The metadata page shows what each library writes by default.

Sources