pdforge logo

Product

Resources

Integrations

pdforge logo

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

Redirected from pdforge.com? You’re in the right place. we’re now pdf noodle!

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

Written by

Written by

Marcelo Abreu, founder of pdforge

Marcelo | Founder of pdf noodle

Marcelo | Founder of pdf noodle

Last Updated

Last Updated

Aug 6, 2025

Aug 6, 2025

Tags

Tags

PDF Libraries

PDF Libraries

C#

C#

pdforge logo
pattern behind Call to action

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
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: Convert HTML to PDF Using pdf noodle

Homepage of pdf noodle

Managing HTML-to-PDF conversion at scale can quickly become a nightmare!

Especially in serverless environments where cold starts, memory limits, and headless browser quirks love to break at the worst possible time (we even wrote a full article about it). Add constant template iterations, version control headaches, and the need to support non-technical contributors, and suddenly your “simple PDF library” turns into an ongoing engineering project.

pdf noodle eliminates all of that.

Instead of maintaining brittle infrastructure or wrestling with outdated pdf libraries, pdf noodle gives you a battle-tested PDF generation API that just works!

Fast, scalable, and designed for both developers and non-developers. You send raw HTML or use our AI-powered template builder, and pdf noodle handles the rendering, scaling, optimization, and delivery so your team doesn’t have to.

Here's an example of a simple API request to generate your pixel-perfect PDF with just a few lines of code:

using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;

namespace PdfApiIntegration
{
    class Program
    {
        static async Task Main(string[] args)
        {
            var client = new HttpClient();
            client.DefaultRequestHeaders.Add("Authorization", "Bearer your-api-key");
            var requestBody = new
            {
                html = "<html>your-html...",
            };
            var content = new StringContent(
                Newtonsoft.Json.JsonConvert.SerializeObject(requestBody),
                Encoding.UTF8,
                "application/json"
            );
            var response = await client.PostAsync("https://api.pdfnoodle.com/v1/html-to-pdf/sync", content);
            if (response.IsSuccessStatusCode)
            {
                var pdfBytes = await response.Content.ReadAsByteArrayAsync();
                File.WriteAllBytes("invoice.pdf", pdfBytes);
                Console.WriteLine("PDF generated using PDFForge API.");
            }
            else
            {
                Console.WriteLine("Error generating PDF: " + response.ReasonPhrase

pdf noodle also includes a powerful AI Agent that can generate PDF templates instantly, along with a modern editor for refining the design, also using AI, to match your brand. You don't need developing or design experience to quickly update layouts, adjust styling, and manage template versions.

Here’s a quick demo showing how it works:

You can create your account and design your first template without any upfront payment.

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.

If you don't want to waste time maintaining pdfs layouts and their infrastructure or if you don't want to keep track of best practices to generate PDFs at scale, third-party PDF APIs like pdf noodle will save you hours of work and deliver a high quality pdf layout.

Generating pdfs can be annoying!

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

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

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

pdforge logo
pattern behind Call to action

Generating pdfs can be annoying!

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

pdforge logo
pattern behind Call to action

Table of contents

Automate PDF Generation in minutes

No code or design experience needed

AI creates your template in seconds

Fine tune the design in our friendly builder

Generate PDFs with our API or integrations