IC Improve Code Recipes

Recipe 11.5 · C#

PDF Generation with QuestPDF

Problem

Invoices, statements, certificates and letters need to be PDFs. Legacy options are a reporting tool with a designer, an HTML-to-PDF converter that drives a headless browser, or an old version of a PDF library under a license that no longer fits. Each has its own deployment headaches.

The way it's often written

Anti-pattern: shown so you can recognize it. Don't copy this one.

C#
var doc = new Document();
PdfWriter.GetInstance(doc, new FileStream(path, FileMode.Create));
doc.Open();
doc.Add(new Paragraph("Invoice " + invoice.Number));
var table = new PdfPTable(4);
foreach (var line in invoice.Lines)
{
    table.AddCell(line.Description);
    table.AddCell(line.Qty.ToString());
    // ...
}
doc.Add(table);
doc.Close();

Code like this was written against an old open-source release of a library that later moved to the AGPL or a commercial license. Positioning is manual, page breaks in tables need hand-tuning, and the stream is never disposed.

The improved recipe

QuestPDF describes documents with a fluent C# layout API. Headers and footers repeat on every page, tables break across pages and repeat their header row, and page numbers are built in.

License note. QuestPDF is not free for everyone. Its Community license is free for individuals, small businesses under a revenue threshold (annual gross revenue under USD 1 million at the time of writing), qualifying charities, academic institutions and open-source projects. Larger organizations need a paid Professional or Enterprise license. The terms have changed before, so read the current license on the QuestPDF web site before you ship. The code declares the license you hold with one line at startup.

NuGet package: QuestPDF.

C#
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using QuestPDF.Fluent;
using QuestPDF.Helpers;
using QuestPDF.Infrastructure;

namespace ImproveCode.Export;

public sealed record InvoiceLine(
    string Description, int Quantity, decimal UnitPrice)
{
    public decimal Total => Quantity * UnitPrice;
}

public sealed record InvoiceModel(
    string Number,
    DateOnly IssuedOn,
    string SellerName,
    string CustomerName,
    IReadOnlyList<InvoiceLine> Lines);

public sealed class InvoiceDocument : IDocument
{
    private static readonly CultureInfo Money =
        CultureInfo.GetCultureInfo("en-US");
    private readonly InvoiceModel _model;

    public InvoiceDocument(InvoiceModel model)
    {
        ArgumentNullException.ThrowIfNull(model);
        _model = model;
    }

    public DocumentMetadata GetMetadata() => new()
    {
        Title = $"Invoice {_model.Number}",
        Author = _model.SellerName
    };

    public void Compose(IDocumentContainer container)
    {
        container.Page(page =>
        {
            page.Size(PageSizes.Letter);
            page.Margin(40);
            page.DefaultTextStyle(x => x.FontSize(10));

            page.Header().Row(row =>
            {
                row.RelativeItem().Column(col =>
                {
                    col.Item().Text($"Invoice {_model.Number}")
                        .FontSize(20).SemiBold();
                    col.Item().Text(
                        $"Issued {_model.IssuedOn:d MMM yyyy}");
                    col.Item().Text($"Bill to: {_model.CustomerName}");
                });
                row.ConstantItem(180).AlignRight()
                    .Text(_model.SellerName).SemiBold();
            });

            page.Content().PaddingVertical(15).Column(col =>
            {
                col.Item().Element(ComposeTable);
                decimal total = _model.Lines.Sum(l => l.Total);
                col.Item().AlignRight().PaddingTop(10)
                    .Text($"Total: {Format(total)}")
                    .FontSize(12).SemiBold();
            });

            page.Footer().AlignCenter().Text(text =>
            {
                text.Span("Page ");
                text.CurrentPageNumber();
                text.Span(" of ");
                text.TotalPages();
            });
        });
    }

    private void ComposeTable(IContainer container)
    {
        container.Table(table =>
        {
            table.ColumnsDefinition(columns =>
            {
                columns.RelativeColumn(5);
                columns.RelativeColumn(1);
                columns.RelativeColumn(2);
                columns.RelativeColumn(2);
            });

            table.Header(header =>
            {
                header.Cell().Element(HeaderCell).Text("Description");
                header.Cell().Element(HeaderCell).AlignRight().Text("Qty");
                header.Cell().Element(HeaderCell).AlignRight()
                    .Text("Unit price");
                header.Cell().Element(HeaderCell).AlignRight()
                    .Text("Amount");
            });

            foreach (var line in _model.Lines)
            {
                table.Cell().Element(BodyCell).Text(line.Description);
                table.Cell().Element(BodyCell).AlignRight()
                    .Text(line.Quantity.ToString(Money));
                table.Cell().Element(BodyCell).AlignRight()
                    .Text(Format(line.UnitPrice));
                table.Cell().Element(BodyCell).AlignRight()
                    .Text(Format(line.Total));
            }
        });
    }

    private static IContainer HeaderCell(IContainer c) =>
        c.BorderBottom(1).BorderColor(Colors.Grey.Darken1)
         .PaddingVertical(4).DefaultTextStyle(x => x.SemiBold());

    private static IContainer BodyCell(IContainer c) =>
        c.BorderBottom(0.5f).BorderColor(Colors.Grey.Lighten2)
         .PaddingVertical(3);

    private static string Format(decimal amount) =>
        amount.ToString("C", Money);
}

public static class InvoicePdf
{
    public static byte[] Create(InvoiceModel model)
    {
        // Declare the license you hold. See the license note above.
        QuestPDF.Settings.License = LicenseType.Community;
        return new InvoiceDocument(model).GeneratePdf();
    }
}

How it works

A QuestPDF document is a class implementing IDocument. Compose describes the page: size, margins and default text style, then three slots. The header and footer repeat on every page. The content flows across as many pages as it needs, and the table moves to the next page between rows, repeating its header there.

Layout is containers inside containers. Row places items side by side, with RelativeItem sharing the remaining width and ConstantItem taking a fixed width in points. Column stacks items vertically. Element(HeaderCell) applies a small styling function, which is how you keep table styles consistent without repeating border and padding calls on every cell.

CurrentPageNumber and TotalPages are resolved at render time, so "Page 2 of 5" is always right. GetMetadata sets the title and author that PDF viewers show.

Money is formatted with an explicit culture, not the server's current culture. An invoice should not change currency symbol because it was generated on a server in a different region. Pick the culture from the customer's account, not from the thread.

GeneratePdf() returns a byte array. There are overloads for a Stream and a file path, and in a web endpoint you can return the bytes with Results.File(bytes, "application/pdf", "invoice.pdf"). In development, the QuestPDF Companion app shows a live preview as you edit the layout code.

Variations and pitfalls

  • Set the license once. Put the QuestPDF.Settings.License line in Program.cs. It is in the helper here only so the listing is self-contained. QuestPDF throws at generation time if no license is set.
  • Fonts. QuestPDF embeds the fonts it uses. On Linux containers, install the fonts your design names, or register a font file with FontManager.RegisterFont. Otherwise text falls back to a default font.
  • Separate data from layout. Build the InvoiceModel in your application service and keep the document class free of database calls. That makes PDF tests simple: build a model, generate, check the byte count or compare against a stored reference.
  • HTML to PDF. If your designers already maintain HTML templates, a headless browser such as Playwright's page.PdfAsync() renders them faithfully. It is a heavier dependency to deploy.