Do you know how to generate PDFs for download?
Updated by Brady Stroud [SSW] 1 year ago. See history
Paid libraries
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
Categories
Need help?
SSW Consulting has over 30 years of experience developing awesome software solutions.