Skip to content
GUIDE · PDF

Playwright PDF Generation: page.pdf() in Python, Node.js and C#

Turn a URL or an HTML string into a PDF with Playwright. Runnable code for all three languages, every page.pdf() option, headers and page numbers, print CSS, and how to run it inside a web service and a Docker image without it falling over.

Last updated

Short answer

Playwright makes PDFs with page.pdf(), which uses Chromium's print-to-PDF engine, so it only works with Chromium (not Firefox or WebKit). Load a URL with page.goto() or an HTML string with page.set_content(), then call page.pdf(path='out.pdf', format='A4', print_background=True). Set both options explicitly: the defaults are US Letter and no backgrounds.

page.pdf() is the same feature as Chrome's "Save as PDF" print dialog, driven from code. That brings real advantages. JavaScript runs, web fonts load, CSS grid and flexbox lay out exactly as they do in Chrome, and charts drawn on a canvas show up. It also has the quirks of printing. The page renders with print media, colors are adjusted for print unless you opt out, and headers and footers come from a small, separate template system. This guide covers the API in Python, Node.js and C#, then the parts that cause most production bugs: waiting for content, page numbers, print CSS, concurrency, and Docker. Everything was checked against the Playwright 1.65 docs in November 2026.

Playwright PDF generation in Python, Node.js and C#

The API is identical across languages; only the naming convention changes (print_background in Python, printBackground in Node.js, PrintBackground in C#). In every language, install the library first, then download Chromium. If Chromium was never installed, you'll hit the most common first-run error: Executable doesn't exist.

Python

install
pip install playwright
playwright install --with-deps chromium
pdf.py
from playwright.sync_api import sync_playwright

with sync_playwright() as p:
    browser = p.chromium.launch()      # page.pdf() works in Chromium only
    page = browser.new_page()
    page.goto("https://example.com/invoice/1024")

    page.pdf(
        path="invoice.pdf",
        format="A4",                   # default is Letter
        print_background=True,         # default is False
        margin={"top": "20mm", "right": "15mm", "bottom": "20mm", "left": "15mm"},
    )
    browser.close()

Playwright for Python ships a sync API (above) and an async API (from playwright.async_api import async_playwright, with await on every call). Use the async one inside FastAPI, aiohttp, Jupyter or any code that already runs an event loop. The sync API raises an error there. With no path, page.pdf() returns the PDF as bytes, which is what you want in a web handler.

Node.js

install
npm install playwright
npx playwright install --with-deps chromium
pdf.mjs
// pdf.mjs
import { chromium } from "playwright";

const browser = await chromium.launch();
const page = await browser.newPage();
await page.goto("https://example.com/invoice/1024");

// Resolves to a Buffer; the path option also writes it to disk
const pdf = await page.pdf({
  path: "invoice.pdf",
  format: "A4",
  printBackground: true,
  margin: { top: "20mm", right: "15mm", bottom: "20mm", left: "15mm" },
});
console.log(pdf.length, "bytes");

await browser.close();

Use the playwright package for scripts and servers. @playwright/test is the test runner, and you don't need it to generate documents. TypeScript works unchanged: the options object is typed, so a typo like printBackgrounds fails at compile time.

C# (.NET)

install
dotnet new console -n PdfDemo
cd PdfDemo
dotnet add package Microsoft.Playwright
dotnet build
# use your build output folder: net8.0, net10.0, ...
pwsh bin/Debug/net10.0/playwright.ps1 install --with-deps chromium
Program.cs
// Program.cs
using Microsoft.Playwright;

using var playwright = await Playwright.CreateAsync();
await using var browser = await playwright.Chromium.LaunchAsync();
var page = await browser.NewPageAsync();
await page.GotoAsync("https://example.com/invoice/1024");

byte[] pdf = await page.PdfAsync(new()
{
    Path = "invoice.pdf",
    Format = "A4",
    PrintBackground = true,
    Margin = new Margin { Top = "20mm", Right = "15mm", Bottom = "20mm", Left = "15mm" },
});
Console.WriteLine($"{pdf.Length} bytes");

In .NET the method is PdfAsync, options come in a PagePdfOptions object, and the result is a byte[]. The playwright.ps1 script needs PowerShell. If pwsh throws TypeNotFound, the Playwright docs suggest updating it with dotnet tool update --global PowerShell.

page.pdf() options

From the page.pdf() reference for Playwright 1.65 (Python, Node.js and .NET docs).
PythonNode.js / C#DefaultWhat it does
pathpath / PathnoneAlso write the file to disk. Without it you only get the bytes back.
formatformat / FormatLetterPaper size: Letter, Legal, Tabloid, Ledger, A0 to A6. Takes priority over width and height.
width, heightwidth, heightnoneCustom size with units px, in, cm or mm. A number without a unit means pixels.
marginmargin / Margin0 on every sidetop, right, bottom, left, each with units.
print_backgroundprintBackgroundFalsePrint background colors and images. Off by default, which is why colored rows vanish.
landscapelandscapeFalsePaper orientation.
scalescale1Zoom the rendering, from 0.1 to 2.
page_rangespageRangesall pagesFor example '1-5, 8, 11-13'.
prefer_css_page_sizepreferCSSPageSizeFalseLet a CSS @page { size } win over format, width and height.
display_header_footerdisplayHeaderFooterFalseTurn the header and footer templates on.
header_template, footer_templateheaderTemplate, footerTemplateChromium's defaultHTML templates; see the page-numbers section below.
outlineoutlineFalseEmbed a document outline (PDF bookmarks). Added in v1.42.
taggedtaggedFalseGenerate a tagged, more accessible PDF. Added in v1.42.

Two of those defaults surprise almost everyone. format is Letter, which is 8.5 × 11 inches, not A4. print_background is off, so your table stripes and colored header bars disappear. Both stem from browser print-dialog defaults rather than PDF-generation needs, which is why every example on this page sets them. Also note that the PDF uses print media: rules inside @media print apply, and your screen-only styles don't. If you want the PDF to look like the screen, call page.emulate_media(media='screen') before page.pdf().

Playwright HTML to PDF in Python: set_content vs goto

There are two ways to get HTML into the page, and they behave differently around relative URLs. That difference is where most "my images and CSS are missing" bug reports come from.

`page.goto(url)``page.set_content(html)`
SourceA URL: your running app, a local server, or a file:// pathAn HTML string in memory
Relative URLs (CSS, images, fonts)Resolve against the page's URLThe page stays on about:blank, so they don't resolve. Use absolute URLs, inline the assets, or add <base href>
How it loadsA normal navigation with redirects and cookiesPlaywright writes the markup in with document.write()
Default waitload eventload event
Best forPages that already exist, such as a report route in your appTemplated documents: invoices, tickets, statements
html_to_pdf.py
from pathlib import Path
from playwright.sync_api import sync_playwright

html = """<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <!-- set_content() runs on about:blank, so give relative URLs a base -->
  <base href="https://cdn.example.com/invoice-assets/">
  <link rel="stylesheet" href="invoice.css">
</head>
<body>
  <img src="logo.png" alt="Acme" width="120">
  <h1>Invoice INV-1024</h1>
  <table>
    <tr><td>Pro plan, November</td><td>$29.00</td></tr>
  </table>
</body>
</html>"""

with sync_playwright() as p:
    browser = p.chromium.launch()
    page = browser.new_page()

    # 1. An HTML string (from Jinja2, Django templates, an f-string ...)
    page.set_content(html, wait_until="load")
    pdf_bytes = page.pdf(format="A4", print_background=True)   # bytes, nothing on disk

    # 2. An HTML file on disk: relative links resolve next to the file
    page.goto(Path("report.html").resolve().as_uri())
    page.pdf(path="report.pdf", format="A4", print_background=True)

    browser.close()

For templated documents, render the template to a string with whatever you already use (Jinja2, Django's render_to_string, Handlebars in Node), then pass it to set_content. If your templates reference assets with root-relative paths like /static/app.css, you have two choices. You can serve them and use goto against that server, or add a <base href> that points at where they're hosted. For a file on disk, Path(...).resolve().as_uri() builds the correct file:/// URL on Windows, macOS and Linux.

Waiting for JavaScript, fonts and charts before printing

page.pdf() prints whatever is on the page at that moment. If data comes from an API or a chart animates in, a PDF taken right after load contains spinners and empty boxes. Wait on something specific:

waits.py
# Pick the signal that matches how your page loads
page.goto(url, wait_until="networkidle")          # no requests for 500 ms (Playwright discourages it for tests)
page.wait_for_selector("#revenue-chart svg")      # a specific element is on the page
page.wait_for_function("() => window.reportReady === true")    # your own code says it's done
page.evaluate("() => document.fonts.ready.then(() => true)")   # web fonts finished loading

page.pdf(path="dashboard.pdf", format="A4", print_background=True)
  • A selector is the most reliable general signal: wait for the element that appears last, such as the chart's svg or the totals row.
  • A ready flag is best when you own the page. Set window.reportReady = true after your data renders, and wait for it with wait_for_function. Also turn chart animations off for print (in Chart.js, animation: false), or the PDF may capture a half-drawn bar.
  • Network idle: networkidle waits until there have been no network requests for 500 ms. It's convenient, but Playwright's docs mark it as discouraged. Pages with analytics beacons, long polling or websockets may never go idle and will time out instead.
  • Fonts: with set_content and an @font-face that loads over the network, awaiting document.fonts.ready prevents the fallback-font PDF.
  • In Node.js and C# the same calls are waitForSelector / WaitForSelectorAsync, waitForFunction / WaitForFunctionAsync, and the waitUntil / WaitUntil option on goto and setContent.

Headers, footers and page numbers

Turn on display_header_footer and pass HTML templates. Chromium fills any element with one of five classes: date, title, url, pageNumber and totalPages. Here's a two-sided header and a centered "Page X of Y" footer in Node.js:

header-footer.mjs
await page.pdf({
  path: "report.pdf",
  format: "A4",
  printBackground: true,
  displayHeaderFooter: true,
  headerTemplate:
    '<div style="font-size:9px; width:100%; padding:0 15mm; display:flex; justify-content:space-between;">' +
    '<span class="title"></span><span class="date"></span></div>',
  footerTemplate:
    '<div style="font-size:9px; width:100%; text-align:center;">' +
    'Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>',
  // The header and footer are drawn inside these margins, so leave room
  margin: { top: "25mm", right: "15mm", bottom: "20mm", left: "15mm" },
});

The Python version, with an empty header so only the footer prints:

footer.py
page.pdf(
    path="report.pdf",
    format="A4",
    print_background=True,
    display_header_footer=True,
    header_template="<span></span>",   # empty: suppresses Chromium's default header
    footer_template=(
        '<div style="font-size:9px; width:100%; text-align:center;">'
        'Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>'
    ),
    margin={"top": "15mm", "right": "15mm", "bottom": "20mm", "left": "15mm"},
)
  • Templates are isolated from the page. Per the Playwright docs, page styles are not visible inside templates and <script> tags in them are not evaluated. Use inline style attributes.
  • Always set a font size. Without an explicit font-size, template text comes out tiny.
  • Leave room in the margins. The header and footer are drawn inside margin.top and margin.bottom. With the default margins of 0 they have no space and won't appear.
  • Suppress the side you don't want. If you set only a footer, Chromium prints its default header. Pass <span></span> as the header template to keep it blank.
  • Logos: templates don't reliably fetch external resources, so embed small images as base64 data: URIs.
  • The same template runs on every page. There's no built-in "different first page" option, so if the cover page needs to differ, generate it separately or design around it.

CSS print rules that matter

Most layout problems in Playwright PDFs are print-CSS problems, not Playwright problems. These rules fix the usual ones:

print.css
@page {
  size: A4;                   /* honored when prefer_css_page_size / preferCSSPageSize is on */
}

@media print {
  nav, .no-print { display: none; }
}

body {
  -webkit-print-color-adjust: exact;   /* keep backgrounds and colors as designed */
  print-color-adjust: exact;
}

h2, h3 { break-after: avoid; }             /* no heading stranded at the bottom of a page */
tr, figure, .card { break-inside: avoid; } /* don't split rows or cards across pages */
.chapter { break-before: page; }           /* start each chapter on a new page */
  • Colors changing or disappearing: Playwright's docs note that by default the PDF has colors modified for printing. print-color-adjust: exact (plus the -webkit- prefix) together with print_background=True keeps them.
  • Page size from CSS: a @page { size: A5 } rule is ignored unless you pass prefer_css_page_size=True. Otherwise format wins and the content is scaled to fit.
  • Margins: choose one place for them, either the margin option or @page { margin }, so you're not guessing which one applied.
  • Awkward page breaks: break-inside: avoid on rows, cards and figures; break-before: page to force a new page; break-after: avoid on headings.
  • An extra blank page at the end usually means something is slightly taller than the page, often an element with height: 100vh or a fixed height. Shrink it, or cut the output with page_ranges.

Running Playwright PDF generation in a web service

A script that launches Chromium, prints one PDF and exits is easy. A web endpoint that does it under load is where teams get burned: memory climbs, requests pile up, and one crashed browser takes every later request down with it. These patterns prevent that:

  • Launch the browser once and reuse it. Starting Chromium is the slowest step, so do it at startup, not per request.
  • One browser context per request. Playwright's docs describe contexts as fast and cheap to create and completely isolated, so one request's cookies, storage or cache can't leak into another's PDF. Close the context in a finally block.
  • Cap concurrency. Each open page uses real CPU and memory. A semaphore (or a job queue) keeps a traffic spike from turning into an out-of-memory kill.
  • Set timeouts on goto and set_content so a slow page can't hold a slot forever.
  • Recover from crashes. Listen for the browser's disconnected event (or check is_connected()) and relaunch.
  • Treat user-supplied HTML as untrusted. It runs in a real browser that can fetch URLs from inside your network, including cloud metadata endpoints. Block requests you don't expect with context.route() and route.abort(), and never print arbitrary user-supplied URLs without an allowlist.
  • For heavy or bursty traffic, move generation to a worker behind a queue (Celery, RQ or Dramatiq in Python; BullMQ in Node.js) and return the file when it's ready.
main.py
# main.py: FastAPI + async Playwright. One browser, one context per request.
import asyncio
from contextlib import asynccontextmanager

from fastapi import FastAPI, Response
from playwright.async_api import async_playwright
from pydantic import BaseModel

slots = asyncio.Semaphore(4)  # max concurrent renders; tune to your CPU and RAM


class PdfRequest(BaseModel):
    html: str


@asynccontextmanager
async def lifespan(app: FastAPI):
    async with async_playwright() as p:
        app.state.browser = await p.chromium.launch()
        yield
        await app.state.browser.close()


app = FastAPI(lifespan=lifespan)


@app.post("/pdf")
async def make_pdf(body: PdfRequest):
    async with slots:
        context = await app.state.browser.new_context()  # fresh cookies and storage
        try:
            page = await context.new_page()
            await page.set_content(body.html, wait_until="load", timeout=15_000)
            pdf = await page.pdf(format="A4", print_background=True)
        finally:
            await context.close()
    return Response(content=pdf, media_type="application/pdf")

The same design in Node.js, with crash recovery added. If Chromium dies, the disconnected handler clears the cached browser and the next request launches a fresh one:

server.mjs
// server.mjs: Express + Playwright, with crash recovery and a concurrency cap
import express from "express";
import { chromium } from "playwright";

const MAX_PAGES = 4;
let browserPromise = null;
let active = 0;
const waiting = [];

// One Chromium for the whole process, relaunched if it crashes
function getBrowser() {
  if (!browserPromise) {
    browserPromise = chromium.launch().then((browser) => {
      browser.on("disconnected", () => { browserPromise = null; });
      return browser;
    });
  }
  return browserPromise;
}

async function acquire() {
  if (active < MAX_PAGES) { active++; return; }
  await new Promise((resolve) => waiting.push(resolve));
}

function release() {
  const next = waiting.shift();
  if (next) next(); else active--;
}

const app = express();
app.use(express.json({ limit: "2mb" }));

app.post("/pdf", async (req, res) => {
  await acquire();
  let context;
  try {
    const browser = await getBrowser();
    context = await browser.newContext();
    const page = await context.newPage();
    await page.setContent(req.body.html, { waitUntil: "load", timeout: 15_000 });
    const pdf = await page.pdf({ format: "A4", printBackground: true });
    res.type("application/pdf").send(pdf);
  } catch (err) {
    res.status(500).json({ error: err.message });
  } finally {
    await context?.close().catch(() => {});
    release();
  }
});

app.listen(3000);

Playwright PDF in Docker

Microsoft publishes Playwright images with the browsers and their system libraries already installed: mcr.microsoft.com/playwright/python, mcr.microsoft.com/playwright (Node.js) and mcr.microsoft.com/playwright/dotnet. They come in Ubuntu 24.04 (-noble) and 22.04 (-jammy) variants, and Alpine isn't supported. The Python image doesn't include the playwright package itself, so pin it to the image's version:

Dockerfile
# Pin the image to the SAME version as the playwright package you install
FROM mcr.microsoft.com/playwright/python:v1.65.2-noble

WORKDIR /app
COPY requirements.txt .
# requirements.txt contains: playwright==1.65.2, fastapi, uvicorn
RUN pip install --no-cache-dir -r requirements.txt
COPY . .

# Don't run the web app as root; the image ships a pwuser account
USER pwuser
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8000"]
build and run
docker build -t pdf-service .
docker run --init --ipc=host -p 8000:8000 pdf-service
  • Match versions exactly. Each Playwright release expects a specific browser build, so the image tag and the package version must agree. In November 2026 that meant v1.65.2 for Python, and mcr.microsoft.com/playwright:v1.65.1-noble with [email protected] for Node.js.
  • Run flags: the Playwright docs recommend --ipc=host for Chromium, because without it Chromium can run out of shared memory and crash. --init stops zombie Chromium processes from piling up when PID 1 doesn't reap them.
  • Fonts: if CJK characters or emoji print as empty boxes, the glyphs aren't in the image. Install them, for example apt-get install -y fonts-noto-cjk fonts-noto-color-emoji, in a RUN step before USER pwuser.
  • Image size: every Playwright image bundles Chromium, Firefox and WebKit. If size matters, build from a slim base and run playwright install --with-deps chromium instead. Our headless Chrome in Docker guide covers that route.

Common Playwright PDF problems

SymptomCauseFix
Executable doesn't exist at ...Browsers weren't downloaded in this environmentRun playwright install --with-deps chromium (or the npm / pwsh equivalent)
Error when calling pdf() in Firefox or WebKitPDF printing is implemented only in ChromiumLaunch chromium for PDF jobs, even if your tests use other browsers
Playwright Sync API inside the asyncio loopThe sync API is being called in FastAPI, Jupyter or other async codeSwitch to playwright.async_api and await the calls
Backgrounds and colors missingprint_background defaults to False; colors are adjusted for printprint_background=True plus print-color-adjust: exact
PDF is US Letter, not A4format defaults to LetterPass format='A4'
Images or CSS missing with set_contentRelative URLs have no base on about:blankUse absolute URLs, inline assets, add <base href>, or use goto
Spinners or empty chartsPrinted before the data or animation finishedwait_for_selector, a ready flag, and chart animations off
Header or footer doesn't appearNo room: margins are 0 by defaultIncrease margin.top / margin.bottom
Layout looks different from the browserPDF uses print mediaFix the @media print rules, or emulate_media(media='screen')
Chromium crashes in DockerToo little shared memoryRun with --ipc=host

Self-hosted Playwright vs a PDF API

Playwright is free and gives you complete control, and for a handful of documents a day it's hard to beat. The cost shows up in operations: a Chromium in every web worker, version-pinned Docker images, concurrency limits, crash handling and font packages. Here's how it compares with sending the same HTML to a hosted endpoint:

Playwright in your serviceRenderKit /v1/pdf
PriceFree (you pay for servers and memory)Free trial with 500 credits for 14 days; from $9/month for 5,000 credits (a PDF costs 2)
SetupLibrary + Chromium + system packages; pinned Docker imageAn API key and one HTTPS request
RenderingChromium, fully under your controlChromium; the same header/footer template classes
Concurrency and crashesYour semaphore, queue and restart logicHandled server-side; failed renders are refunded
DataHTML never leaves your infrastructureHTML or URL is sent to RenderKit; output is hosted on a public CDN URL
ExtrasAnything Chromium can do, such as outline, tagged and screen mediaRender cache (repeat renders cost 0 credits), async jobs and webhooks on paid plans

The same PDF with RenderKit's /v1/pdf API

If you'd rather not run Chromium at all, RenderKit takes the same inputs as page.pdf() as JSON and returns a hosted PDF URL. Most options map one to one:

PlaywrightRenderKit parameterNotes
page.goto(url)urlMust be http(s). Send exactly one of url or html.
page.set_content(html)htmlUp to 2 MB. Use absolute URLs for assets, same as with set_content.
formatpage_formatA4 (default), A3, A5, Letter, Legal, Tabloid.
width, heightpage_width, page_heightCSS lengths such as "80mm"; they override page_format.
margin={...}margin or margin_top / margin_right / margin_bottom / margin_leftOne CSS length string, e.g. "16mm" (default 10mm).
print_background (default False)print_background (default true)Backgrounds print unless you turn them off.
landscape, scale, page_ranges, prefer_css_page_sizelandscape, scale, page_range, prefer_css_page_sizeSame meaning; scale 0.1–2.
header_template, footer_templateheader_html, footer_htmlSame Chromium templates with pageNumber / totalPages spans.
wait_until, wait_for_selectorwait_until (default networkidle), wait_for_selector, delaydelay adds up to 10,000 ms.
emulate_media('screen'), outline, taggedNot availableKeep using Playwright if you depend on these.
renderkit_pdf.py
import os
from renderkit import RenderKit   # pip install renderkit-sdk

rk = RenderKit(os.environ["RENDERKIT_API_KEY"])

pdf = rk.pdf(
    html=html,                     # or url="https://example.com/invoice/1024"
    page_format="A4",
    margin="16mm",
    wait_for_selector="#total",    # optional, like page.wait_for_selector()
    footer_html=(
        '<div style="font-size:9px; width:100%; text-align:center;">'
        'Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>'
    ),
)
print(pdf["url"], pdf["credits_used"])   # hosted PDF on cdn.renderkit.tech, 2 credits
renderkit-pdf.mjs
import { RenderKit } from "renderkit-sdk"; // npm install renderkit-sdk

const rk = new RenderKit(process.env.RENDERKIT_API_KEY);

const pdf = await rk.pdf({
  url: "https://example.com/invoice/1024", // or html: "<!doctype html>..."
  page_format: "A4",
  margin: "16mm",
  landscape: false,
});
console.log(pdf.url);
RenderKitPdf.cs
// No SDK needed: one HTTPS request with HttpClient
using System.Net.Http.Json;
using System.Text.Json;

using var http = new HttpClient();
http.DefaultRequestHeaders.UserAgent.ParseAdd("my-app/1.0");

using var req = new HttpRequestMessage(HttpMethod.Post, "https://api.renderkit.tech/v1/pdf")
{
    Content = JsonContent.Create(new { url = "https://example.com/invoice/1024", page_format = "A4", margin = "16mm" }),
};
req.Headers.Add("x-api-key", Environment.GetEnvironmentVariable("RENDERKIT_API_KEY"));

using var res = await http.SendAsync(req);
res.EnsureSuccessStatusCode();
using var json = JsonDocument.Parse(await res.Content.ReadAsStreamAsync());
string pdfUrl = json.RootElement.GetProperty("data").GetProperty("url").GetString()!;

await File.WriteAllBytesAsync("invoice.pdf", await http.GetByteArrayAsync(pdfUrl));
  • Cost: a PDF is 2 credits, identical repeat requests served from the render cache cost 0, and failed renders are refunded. The free trial has 500 credits for 14 days, at 10 requests per minute, 1 concurrent render and a 15-second render timeout. Hobby is $9/month for 5,000 credits, or 2,500 PDFs. See pricing.
  • Where the file lives: the response carries a public, content-addressed URL on cdn.renderkit.tech (unguessable, but not access-controlled). Download it into your own storage if the documents are sensitive.
  • Trade-offs, honestly: your HTML goes to a third party, every render is a network round trip, PDFs render from servers in France, and there's no uptime SLA. If any of that rules it out, the Playwright setup above is the right call.
  • Errors come back as JSON: 422 with RENDER_FAILED, TIMEOUT or SELECTOR_NOT_FOUND, and 429 when you hit your rate limit or quota. Full parameter list in the PDF API reference.

Common questions

No. page.pdf() is built on Chromium's print-to-PDF support, and Playwright's own test suite skips PDF tests on other browsers with the message that printing to PDF is only supported in Chromium. Launch chromium for PDF jobs even if your tests run in Firefox or WebKit.

Launch Chromium, open a page, load your HTML with page.set_content(html, wait_until='load'), then call page.pdf(path='out.pdf', format='A4', print_background=True). Because set_content runs on about:blank, use absolute URLs for images and stylesheets, inline them, or add a <base href> tag. For an HTML file on disk, page.goto(Path('file.html').resolve().as_uri()) keeps relative links working.

print_background defaults to False, and Chromium adjusts colors for print by default. Pass print_background=True (printBackground: true in Node.js) and add print-color-adjust: exact and -webkit-print-color-adjust: exact to the elements whose colors must not change.

Set display_header_footer=True and put <span class='pageNumber'></span> and <span class='totalPages'></span> in footer_template. Use inline styles with an explicit font-size, because page styles aren't visible inside templates, and set a bottom margin tall enough to hold the footer.

page.pdf() renders with print media, so @media print rules apply and screen-only styles don't. Either fix your print stylesheet or call page.emulate_media(media='screen') before page.pdf() to print the screen styles. Also check that format matches what you expect: the default is Letter, not A4.

Add the Microsoft.Playwright NuGet package, build, install Chromium with the generated playwright.ps1 script, then call await page.PdfAsync(new() { Path = "out.pdf", Format = "A4", PrintBackground = true }). PdfAsync returns the PDF as a byte array, and Margin, HeaderTemplate and FooterTemplate work as in the other languages.

There's no fixed number; it depends on page complexity, CPU and memory. Reuse one browser, open one context per request, close it in a finally block, and cap concurrency with a semaphore or queue. Raise the cap gradually while watching memory. Launching a browser per request is the most common mistake.

Playwright itself is a library, not a hosted service, so page.pdf() runs wherever your code runs. You can wrap it in your own endpoint (see the FastAPI and Express examples above) or use a hosted HTML-to-PDF API such as RenderKit's /v1/pdf, which accepts a URL or HTML plus the same page-size, margin and header/footer options.

Ship your first render in 60 seconds.

500 free credits to start. No card. Cancel by ignoring it.

Get your free key$npm i renderkit-sdk