pdforge logo

pdforge

Product

Resources

Integrations

PDF Libraries

PDF Libraries

C#

C#

How to Generate PDF from HTML with Playwright using C# (Updated 2025)

Marcelo Abreu, founder of pdforge

Marcelo | Founder

Marcelo | Founder

Aug 6, 2025

Aug 6, 2025

What is Playwright and How Can It Convert HTML to PDF?

Playwright is a sophisticated open-source automation framework designed for comprehensive browser tasks, including automated testing, web scraping, and generating PDFs from HTML content. Compatible with Chromium, Firefox, and WebKit, Playwright delivers consistent rendering across different environments. Developers prefer Playwright for its high performance, extensive browser coverage, and impressive handling of dynamic content.

For HTML-to-PDF conversion tasks, Playwright distinctly excels by accurately capturing what browsers display—ranging from intricate CSS styles to fully JavaScript-rendered interactive elements. This precision ensures impeccable quality ideal for generating professional documents, like SaaS reports, invoices, and dynamic web-based documents.

Playwright also boasts extensive, clear documentation, enabling developers to resolve any implementation hiccups quickly and efficiently.


Explore our other guides for various programming languages:

Alternative PDF Libraries for .NET: Why Choose Playwright?

.NET offers several notable libraries for HTML-to-PDF generation:

Download comparison between pdf libraries using nuget trends
  • iTextSharp: Primarily PDF manipulation with limited native HTML rendering capabilities.

  • QuestPDF: Effective for structured PDF documents but struggles with complex HTML/CSS and dynamic content.

  • PdfSharp: Ideal for creating PDFs from scratch but lacks direct HTML to PDF conversion capabilities.

  • PuppeteerSharp: A port of Puppeteer for C#, allowing control over Chrome or Chromium browsers. It handles HTML to PDF conversion but can be resource-intensive and may have compatibility issues.

In contrast, Playwright’s open-source model, coupled with comprehensive browser support, superior JavaScript rendering, and precise HTML-to-PDF output, makes it the most versatile and scalable solution in the .NET ecosystem.

If you want to dig deeper on a comparison between PuppeteerSharp and other C# pdf libraries, we also have a detailed article with a full comparison between the best PDF libraries for C# in 2025.

Guide to generate pdf from html using C# Playwright
Guide to generate pdf from html using C# Playwright

Step 01: Setting Up Playwright for PDF Generation in C# (.NET)

Ensure .NET is installed from dotnet.microsoft.com before proceeding.

Install Playwright via NuGet using the command:

Next, install required browser engines using the Playwright CLI:



Step 02: Generating Your First “Hello World” PDF in C#

Creating PDFs with Playwright in C# involves a straightforward .NET script.

Alternative 01: Generate PDF from URL

Here’s how to generate a PDF from a webpage URL:

using Microsoft.Playwright;

var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();

await page.GotoAsync("https://example.com");
await page.PdfAsync(new PagePdfOptions { Path = "example.pdf", Format = "A4"

This script performs:

  • Launching a headless Chromium browser

  • Navigating to the specified webpage

  • Saving the rendered page as a PDF

Alternative 02: Generate PDF from HTML String

Generate PDFs directly from raw HTML content:

using Microsoft.Playwright;

var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();

string htmlContent = "<html><body><h1>Hello, PDF!</h1></body></html>";
await page.SetContentAsync(htmlContent);
await page.PdfAsync(new PagePdfOptions { Path = "sample.pdf", Format = "Letter"

Customizing PDF Output (Headers, Footers, Margins)

Playwright provides extensive customization for PDF outputs, including adding headers, footers, and adjusting margins:

await page.PdfAsync(new PagePdfOptions
{
    Path = "custom.pdf",
    Format = "A4",
    Margin = new Margin { Top = "20mm", Bottom = "20mm" },
    DisplayHeaderFooter = true,
    HeaderTemplate = "<span style='font-size:10px'>Header Content</span>",
    FooterTemplate = "<span style='font-size:10px'>Page <span class='pageNumber'></span> of <span class='totalPages'></span></span>"

Review more options in the Playwright documentation for .NET.

Using HTML Template Engines with .NET

Template engines like Razor can simplify creating dynamic HTML:

// Example using RazorLight
using RazorLight;

var engine = new RazorLightEngineBuilder()
    .UseEmbeddedResourcesProject(typeof(Program))
    .UseMemoryCachingProvider()
    .Build();

string template = "<h1>Invoice for @Model.ClientName</h1>";
string html = await engine.CompileRenderStringAsync("templateKey", template, new { ClientName = "Contoso Ltd." });

await page.SetContentAsync(html);
await page.PdfAsync(new PagePdfOptions { Path = "invoice.pdf"

Step 03: Scaling PDF Generation with Serverless Architectures

Generating complex PDFs with Playwright demands substantial computational resources. Serverless architectures like AWS Lambda, Google Cloud Function and Azure Functions offer cost-effective, scalable, and efficient environments.

Note that you must install the browser engine (e.g., Chromium) on the Lambda layer or any other serverless service you're using. While various installation guides exist online, what worked best for me was using a dockerized container to install the browser engine effectively.

I’ve prepared a detailed step-by-step guide to help you set this up, available here.

Alternative: Scale PDF Generation with Third-Party APIs

homepage of pdforge

For larger SaaS platforms requiring automated PDF generation at scale, if you're developing using no-code platforms like Bubble or creating automation workflows using platforms like n8n, make or zapier, integrating a PDF Generation API like pdforge can offload the heavy lifting.

With pdforge, you can create beautiful PDF documents in minutes using our AI-first PDF Generation. You can fine-tune de design with an easy-to-use opinionated no-code builder and start generating PDFs using our API or native integration with no-code tools. Let the AI do the heavy lifting by generating your templates, creating custom components or even filling all the variables for you.

You can handle high-volume PDF generation from a single backend call.

Here’s an example of how to generate pdf with pdforge via an API call:

using System.Net.Http;

HttpClient client = new HttpClient();
var payload = new
{
    templateId = "invoice-template",
    data = new { client = "Contoso Ltd." }
};

var response = await client.PostAsJsonAsync("https://api.pdforge.com/v1/pdf", payload);
var pdfBytes = await response.Content.ReadAsByteArrayAsync();

await File.WriteAllBytesAsync("invoice.pdf", pdfBytes

You can create your account, experience our no-code builder and create your first layout template without any upfront payment clicking here.

If you prefer a managed service, third-party APIs like pdforge offer scalable HTML-to-PDF generation without infrastructure setup or design changes management from you. These solutions manage everything from HTML template rendering to PDF delivery.

Conclusion

Playwright in C# (.NET) is a powerful and reliable solution for converting HTML content into high-quality, pixel-perfect PDFs. Its growing popularity, extensive browser compatibility, and precision make it an exceptional choice for developers handling sophisticated SaaS document generation.

For developers who prefer minimal infrastructure management and effortless scalability, leveraging dedicated PDF APIs like pdforge can significantly streamline processes, enabling rapid, reliable, and efficient PDF delivery.

Generating pdfs at scale can be annoying!

Generating pdfs at scale can be annoying!

Let us help you make it easier while you focus on what truly matters for your company.

Let us help you make it easier while you focus on what truly matters for your company.

7-day free trial

7-day free trial

Table of contents

Automate PDF Generation with pdforge

No code or design experience needed

AI creates your template in seconds

Fine tune the design in our no-code builder

Generate PDFs with our API or integrations