Do you know how to generate PDFs for download?

Last updated by Alex Rothwell [SSW] about 1 year ago.See history

Some projects call for being able to export data as a PDF. In these instances, it's great to be able to fully generate the file in the back-end and then provide it for download.

As with most software problems, there's many ways to achieve the same end result, each with their pros and cons.

There are many paid .NET libraries available which can generate PDFs for you like:

If the project has budget for a paid PDF solution, these are great and will get you generating PDFs quickly.

Pros:

✅ Mostly works out-of-the-box
✅ Potential for commercial support from the library developer

Cons:

❌ Project might not have the budget for such an option
❌ Is often closed source (see more)

Free libraries

Unfortunately, the vast majority of libraries which can generate PDFs directly are paid. To get around this, the PDF generation function of a browser testing library can be used instead. Using this method, the desired content is rendered in a headless browser and that browser is then used to generate a PDF.

Pros:

✅ Free!
Open source
✅ Can easily reuse existing web layouts

Cons:

❌ Support is often limited
❌ May require more configuration to get working

Example

One library which makes this really easy (and is free!) is Playwright.

Generating a PDF here takes just a few lines, see the demo and docs for more info.

public async Task<byte[]> ExportView(string url, CancellationToken cancellationToken)
{
    var playwright = await Playwright.CreateAsync();
    var browser = await playwright.Chromium.LaunchAsync();
    var page = await browser.NewPageAsync();
    await page.GotoAsync(url);
    if (cancellationToken.IsCancellationRequested) { return Array.Empty<byte>(); }

    return await page.PdfAsync(new PagePdfOptions { Format = "A4" });
}

Figure: A simple method to return a PDF using Playwright

We open source. Powered by GitHub