
Generate PDFs with Playwright in Node.js and Python
Table of Contents
- Install Playwright and Chromium for PDF output
- Generate a PDF with Playwright in Node.js
- Playwright page.pdf() options
- Puppeteer and Playwright pdf() option names
- Generate a PDF with Playwright in Python (sync API)
- Serve the PDF from a FastAPI endpoint (async API)
- Test the PDF output in Node.js and Python
- Fix empty headers, missing backgrounds and other PDF errors
- What a production PDF service needs
- Install Playwright and Chromium for PDF output
- Generate a PDF with Playwright in Node.js
- Playwright page.pdf() options
- Puppeteer and Playwright pdf() option names
- Generate a PDF with Playwright in Python (sync API)
- Serve the PDF from a FastAPI endpoint (async API)
- Test the PDF output in Node.js and Python
- Fix empty headers, missing backgrounds and other PDF errors
- What a production PDF service needs
A team that uses Playwright for end-to-end tests or scraping already has a browser that can print. When a feature needs PDF files, such as a monthly report or an invoice, page.pdf() makes them without a second tool. This guide makes a Playwright PDF from one HTML file in Node.js and in Python. Then it puts the Python version behind a short FastAPI endpoint.
The finished Node.js script turns a sample report into a three-page A4 PDF. The PDF has a header, page numbers, bookmarks and a page break that the CSS sets:
node make-pdf.js report.html out/report.pdf
Wrote out/report.pdf (139 KB, print media)

Tested with:
| Item | Version |
|---|---|
| Playwright for Node.js | 1.65.0 (Chromium 158.0.8127.18) |
| Playwright for Python | 1.64.1 (Chromium 156.0.8078.4), the latest Python release on the test date |
| Node.js | 22.22.3 on macOS, 22.23.4 in GitHub Actions |
| Python | 3.14.5 on macOS, 3.12.16 in GitHub Actions |
| FastAPI, pypdf, pdf-lib | 0.162.2, 7.0.0, 1.17.1 |
| Operating system | macOS 26.7 on Apple Silicon, Ubuntu 24.04 in GitHub Actions |
| Test date | 9 November 2026 |
All the code, with the tests, is in the html-to-pdf repository: the nodejs-playwright folder for Node.js and the python-playwright folder for Python. Each folder is a separate project with its own copy of report.html.
Install Playwright and Chromium for PDF output
Playwright makes PDF files only with Chromium. A test in the repository calls page.pdf() in Firefox and gets this error:
Error: page.pdf: PDF generation is only supported for Headless Chromium
The Playwright source code has no PDF function for WebKit either. If your tests run in three browsers, keep one Chromium instance for PDF work.
Create a nodejs-playwright folder and add package.json:
{
"name": "playwright-pdf-node",
"version": "1.0.0",
"private": true,
"type": "module",
"description": "Generate PDFs from HTML with Playwright in Node.js",
"scripts": {
"pdf": "node make-pdf.js report.html out/report.pdf",
"test": "node --test"
},
"engines": {
"node": ">=22"
},
"dependencies": {
"playwright": "1.65.0"
},
"devDependencies": {
"pdf-lib": "1.17.1"
}
}
Install the packages and Chromium:
cd nodejs-playwright
npm install
npx playwright install chromium
If you use Linux, add --with-deps to the last command. It installs the system libraries that Chromium needs.
Create report.html in the nodejs-playwright folder. It is a normal web page with print CSS:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Monthly usage report</title>
<style>
body { font: 12px/1.5 Arial, Helvetica, sans-serif; color: #1f2933; margin: 0; }
h1 { font-size: 26px; margin: 0 0 4px; }
h2 { font-size: 17px; margin: 18px 0 8px; }
.cover { background: #0b1016; color: #f2f6fa; padding: 24px; border-radius: 8px; }
.cards { display: grid; grid-template-columns: repeat(3, 1fr); gap: 10px; margin: 16px 0; }
.card { background: #e6fff2; border: 1px solid #99ffcc; border-radius: 6px; padding: 10px; }
.card b { display: block; font-size: 20px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 5px 8px; border-bottom: 1px solid #d9e2ec; text-align: left; }
th { background: #d9e2ec; }
tr { break-inside: avoid; } /* never split a row over two pages */
.new-page { break-before: page; } /* start this section on a new page */
.screen-only { background: #fff3c4; padding: 8px; margin-bottom: 12px; }
@media print { .screen-only { display: none; } }
</style>
</head>
<body>
<p class="screen-only">Screen version: print media hides this note.</p>
<section class="cover">
<h1>Monthly usage report</h1>
<p>Demo account, sample data generated by the script in this page.</p>
</section>
<div class="cards">
<div class="card">Requests <b id="total">0</b></div>
<div class="card">Errors <b id="errors">0</b></div>
<div class="card">Days <b>30</b></div>
</div>
<h2>Requests per day</h2>
<table>
<thead><tr><th>Day</th><th>Requests</th><th>Errors</th><th>Error rate</th></tr></thead>
<tbody id="rows"></tbody>
</table>
<section class="new-page">
<h2>Notes</h2>
<p>This section starts on a new page because of <code>break-before: page</code>.</p>
</section>
<script>
// JavaScript runs before page.pdf(), so the PDF shows the finished table.
let total = 0, errors = 0;
for (let day = 1; day <= 30; day++) {
const requests = 1000 + (day * 137) % 500;
const failed = (day * 7) % 13;
total += requests; errors += failed;
document.getElementById('rows').insertAdjacentHTML('beforeend',
`<tr><td>${day}</td><td>${requests}</td><td>${failed}</td><td>${(failed / requests * 100).toFixed(2)}%</td></tr>`);
}
document.getElementById('total').textContent = total;
document.getElementById('errors').textContent = errors;
</script>
</body>
</html>
Four parts of the page change the PDF:
tr { break-inside: avoid; }keeps each table row on one page..new-page { break-before: page; }starts the notes on a new page. This rule makes the third page.@media printhides the yellow note. Screen media shows it.- The script fills the table.
page.setContent()waits for theloadevent, so the table is complete before the PDF starts.
Chromium also repeats the <thead> row at the top of page 2. It does this for table headers by default.
Generate a PDF with Playwright in Node.js
Create pdf.js. It has one function, htmlToPdf(), that loads an HTML string, calls page.pdf() and returns the PDF buffer:
// Render an HTML string to a PDF buffer with Playwright and Chromium.
// The page CSS does not apply to the header and footer templates, so every
// style is inline. Without a font size, the text is almost invisible.
const textStyle = 'font: 9px Arial, sans-serif; width: 100%; margin: 0 14mm; color: #52606d;';
const headerTemplate = `<div style="${textStyle}"><span class="title"></span></div>`;
const footerTemplate = `<div style="${textStyle} text-align: right;">
Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>`;
export const defaultPdfOptions = {
format: 'A4',
// The top and bottom margins must leave room for the header and footer.
margin: { top: '20mm', right: '14mm', bottom: '18mm', left: '14mm' },
printBackground: true, // keep background colors and images
displayHeaderFooter: true,
headerTemplate,
footerTemplate,
outline: true, // bookmarks from the headings (Chromium needs tagged: true for this)
tagged: true, // accessible PDF with a structure tree
};
export async function htmlToPdf(browser, html, options = {}) {
const { media = 'print', loadTimeout = 15_000, pdfTimeout = 30_000, ...pdfOptions } = options;
// A new context per document: no cookies or storage leak between documents.
const context = await browser.newContext();
try {
const page = await context.newPage();
page.setDefaultTimeout(loadTimeout);
await page.emulateMedia({ media });
await page.setContent(html, { waitUntil: 'load' });
await page.evaluate(() => document.fonts.ready.then(() => true));
return await withTimeout(page.pdf({ ...defaultPdfOptions, ...pdfOptions }), pdfTimeout);
} finally {
// Closing the context also stops a render that ran out of time.
await context.close();
}
}
// page.pdf() in Playwright has no timeout option, so race it against a timer.
function withTimeout(promise, ms) {
let timer;
const timeout = new Promise((_, reject) => {
timer = setTimeout(() => reject(new Error(`page.pdf() took longer than ${ms} ms`)), ms);
});
return Promise.race([promise, timeout]).finally(() => clearTimeout(timer));
}
The steps in htmlToPdf():

The reasons for each part:
- A new browser context for each document. A context is a separate browser profile with its own cookies and storage. When the context closes, its pages close too.
emulateMedia()beforesetContent().page.pdf()uses print CSS unless you setscreen. The early call makes the scripts in the page see the same media type as the PDF.document.fonts.ready. Playwright does not wait for web fonts before it prints, and it has nowaitForFontsoption as Puppeteer has.- Margins. The header and footer go into the top and bottom margins. With a margin of 0, Chromium draws them on top of the page text.
- Inline styles in the templates. The page CSS does not apply to the header and footer. Without a
font-size, the text is too small to read. Chromium fills elements with the classestitle,pageNumber,totalPages,dateandurl. outlinetogether withtagged. In a test with Playwright 1.65,outline: truealone gave a PDF with no bookmarks. Withtagged: true, the PDF had one bookmark for each heading.- A timer around
page.pdf(). The method has notimeoutoption, and the Node.js API ignores an unknowntimeoutkey. If the timer ends first, thefinallyblock closes the context and stops the render.
If you set displayHeaderFooter: true without templates, Chromium prints its own header and footer. In the test, the header showed the date and the title, and the footer showed about:blank and 1/3.
Create make-pdf.js, the command-line script:
// Usage: node make-pdf.js <input.html> <output.pdf> [print|screen]
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import path from 'node:path';
import { chromium } from 'playwright';
import { htmlToPdf } from './pdf.js';
const [input = 'report.html', output = 'out/report.pdf', media = 'print'] = process.argv.slice(2);
const html = await readFile(input, 'utf8');
const browser = await chromium.launch();
try {
const pdf = await htmlToPdf(browser, html, { media });
await mkdir(path.dirname(output), { recursive: true });
await writeFile(output, pdf);
console.log(`Wrote ${output} (${Math.round(pdf.length / 1024)} KB, ${media} media)`);
} finally {
await browser.close();
}
Run it from the nodejs-playwright folder. The third argument selects the CSS media:
node make-pdf.js report.html out/report.pdf
node make-pdf.js report.html out/report-screen.pdf screen
The screen version shows the yellow note, and the print version hides it. Both versions have three pages.
Playwright page.pdf() options
The table that follows is from the Playwright page.pdf() documentation, with notes from tests with the sample report.
| Option (Node.js) | Python name | Default | What it does |
|---|---|---|---|
format |
format |
Letter |
Paper size: Letter, Legal, Tabloid, Ledger, A0 to A6. It wins over width and height. |
width, height |
width, height |
none | A number is pixels. A string can use px, in, cm or mm. |
margin |
margin |
0 on each side | An object with top, right, bottom and left. A CSS @page margin wins over it. |
printBackground |
print_background |
false |
Prints background colors and images. |
landscape |
landscape |
false |
Turns the paper. |
scale |
scale |
1 |
From 0.1 to 2. With 0.5, the sample report had two pages instead of three. |
pageRanges |
page_ranges |
all pages | For example '1-2, 5'. |
preferCSSPageSize |
prefer_css_page_size |
false |
A CSS @page size wins over format. |
displayHeaderFooter |
display_header_footer |
false |
Prints headerTemplate and footerTemplate. |
outline |
outline |
false |
Adds bookmarks from the headings. It needs tagged: true. |
tagged |
tagged |
false |
Adds a structure tree for screen readers. |
path |
path |
none | Also writes the PDF to this file. |
Two rules decide the page size. format wins over width and height. A CSS @page { size: ... } rule wins over both, but only with preferCSSPageSize: true. In a test, @page { size: A5; } with format: 'A4' gave an A4 sheet with the A5 page in the middle. With preferCSSPageSize: true, the PDF page was A5.
Which setting decides the page size:

Margins have a similar rule. A test page with @page { margin: 30mm; } and a margin option of 5 mm on each side got 30 mm margins.
By default, Chromium does not print background colors, and it changes some colors for print. In the image that follows, the left page has printBackground: false: the dark title box is gone, and its white text is light gray. The right page has printBackground: true.

To keep the background of one element only, add print-color-adjust: exact to its CSS. In a test, that element kept its dark background with printBackground: false.
Puppeteer and Playwright pdf() option names
Both libraries send the same command, Page.printToPDF, over the Chrome DevTools Protocol (CDP, the protocol that controls Chrome). So most option names are the same, but the defaults and the extra features are different. The Puppeteer column uses version 25.16.0 and the Puppeteer PDFOptions reference.
| Task | Playwright (Node.js) | Playwright (Python) | Puppeteer |
|---|---|---|---|
| Paper size | format, width, height |
format, width, height |
format, width, height |
| Background colors | printBackground |
print_background |
printBackground |
| CSS page size wins | preferCSSPageSize |
prefer_css_page_size |
preferCSSPageSize |
| Header and footer | displayHeaderFooter, headerTemplate, footerTemplate |
display_header_footer, header_template, footer_template |
displayHeaderFooter, headerTemplate, footerTemplate |
| Some pages only | pageRanges |
page_ranges |
pageRanges |
| Accessible PDF | tagged, default false |
tagged, default False |
tagged, default true |
| Bookmarks | outline |
outline |
outline |
| Time limit | none | none | timeout, default 30 seconds |
| Wait for web fonts | none | none | waitForFonts, default true |
| Transparent background | none | none | omitBackground |
| PDF as a stream | none | none | page.createPDFStream() |
| Screen CSS | page.emulateMedia({ media: 'screen' }) |
page.emulate_media(media="screen") |
page.emulateMediaType('screen') |
With Puppeteer 25.16.0, outline: true alone gave a PDF with bookmarks, because Puppeteer tags the PDF by default. In Playwright, the same call gave none.
Generate a PDF with Playwright in Python (sync API)
Playwright for Python makes the same PDF with the same methods. Only the names change to snake_case. On 9 November 2026, the latest Python release was 1.64.1 with Chromium 156, one minor version behind Node.js.
Create a python-playwright folder, copy report.html into it, and add requirements.txt:
playwright==1.64.1
fastapi==0.162.2
uvicorn==0.54.0
pydantic==2.14.3
pypdf==7.0.0
pytest==9.2.0
httpx2==2.16.0
Make a virtual environment, then install the packages and Chromium:
cd python-playwright
python3 -m venv .venv
.venv/bin/pip install -r requirements.txt
.venv/bin/python -m playwright install chromium
Create make_pdf.py. It generates the PDF with the Playwright sync API and the same options as pdf.js:
"""Render an HTML file to PDF with the Playwright sync API.
Usage: python make_pdf.py <input.html> <output.pdf> [print|screen]
"""
import sys
from pathlib import Path
from playwright.sync_api import Browser, sync_playwright
TEXT_STYLE = "font: 9px Arial, sans-serif; width: 100%; margin: 0 14mm; color: #52606d;"
PDF_OPTIONS = {
"format": "A4",
"margin": {"top": "20mm", "right": "14mm", "bottom": "18mm", "left": "14mm"},
"print_background": True,
"display_header_footer": True,
"header_template": f'<div style="{TEXT_STYLE}"><span class="title"></span></div>',
"footer_template": (
f'<div style="{TEXT_STYLE} text-align: right;">'
'Page <span class="pageNumber"></span> of <span class="totalPages"></span></div>'
),
"outline": True,
"tagged": True,
}
def html_to_pdf(browser: Browser, html: str, media: str = "print") -> bytes:
context = browser.new_context()
try:
page = context.new_page()
page.set_default_timeout(15_000)
page.emulate_media(media=media)
page.set_content(html, wait_until="load")
page.evaluate("document.fonts.ready.then(() => true)")
return page.pdf(**PDF_OPTIONS)
finally:
context.close()
def main() -> None:
args = sys.argv[1:]
source = Path(args[0] if len(args) > 0 else "report.html")
target = Path(args[1] if len(args) > 1 else "out/report.pdf")
media = args[2] if len(args) > 2 else "print"
with sync_playwright() as p:
browser = p.chromium.launch()
try:
pdf = html_to_pdf(browser, source.read_text(encoding="utf-8"), media)
finally:
browser.close()
target.parent.mkdir(parents=True, exist_ok=True)
target.write_bytes(pdf)
print(f"Wrote {target} ({len(pdf) // 1024} KB, {media} media)")
if __name__ == "__main__":
main()
Run it:
.venv/bin/python make_pdf.py report.html out/report.pdf
Wrote out/report.pdf (138 KB, print media)
The sync API fits scripts, Django views and job workers. It does not work inside a running asyncio event loop, for example in a FastAPI async def route. There, you get this error:
Error: It looks like you are using Playwright Sync API inside the asyncio loop.
Please use the Async API instead.
Serve the PDF from a FastAPI endpoint (async API)
The Puppeteer version of this service in Node.js has templates, URL input and a Dockerfile. This FastAPI endpoint is short: it takes HTML and returns a PDF from the Playwright async API.
Create app.py:
"""POST /pdf: HTML in, PDF out. Uses the Playwright async API."""
import asyncio
from contextlib import asynccontextmanager
from typing import Literal
from fastapi import FastAPI, HTTPException, Request
from fastapi.responses import JSONResponse, Response
from playwright.async_api import Browser, async_playwright
from pydantic import BaseModel, Field
from make_pdf import PDF_OPTIONS
MAX_BODY_BYTES = 2_000_000
RENDER_TIMEOUT_SECONDS = 30
render_slots = asyncio.Semaphore(4) # at most 4 renders at the same time
@asynccontextmanager
async def lifespan(app: FastAPI):
# One browser for the whole process, started once.
async with async_playwright() as p:
app.state.browser = await p.chromium.launch()
yield
await app.state.browser.close()
app = FastAPI(lifespan=lifespan)
class PdfRequest(BaseModel):
html: str = Field(min_length=1, max_length=MAX_BODY_BYTES)
media: Literal["print", "screen"] = "print"
format: Literal["A4", "Letter", "Legal"] = "A4"
landscape: bool = False
@app.middleware("http")
async def limit_body_size(request: Request, call_next):
# A reverse proxy limit is still necessary for requests without Content-Length.
length = request.headers.get("content-length", "0")
if not length.isdigit() or int(length) > MAX_BODY_BYTES:
return JSONResponse({"detail": "Request body is too large"}, status_code=413)
return await call_next(request)
async def render(browser: Browser, body: PdfRequest) -> bytes:
context = await browser.new_context()
try:
# Block every network request: the HTML cannot load remote files
# or reach hosts in your private network.
await context.route("**/*", lambda route: route.abort())
page = await context.new_page()
page.set_default_timeout(15_000)
await page.emulate_media(media=body.media)
await page.set_content(body.html, wait_until="load")
await page.evaluate("document.fonts.ready.then(() => true)")
options = {**PDF_OPTIONS, "format": body.format, "landscape": body.landscape}
return await page.pdf(**options)
finally:
await context.close()
@app.post("/pdf")
async def create_pdf(body: PdfRequest, request: Request) -> Response:
async with render_slots:
try:
pdf = await asyncio.wait_for(
render(request.app.state.browser, body), RENDER_TIMEOUT_SECONDS
)
except TimeoutError:
raise HTTPException(status_code=504, detail="Rendering took too long")
return Response(pdf, media_type="application/pdf")
The design decisions:
- One browser for the process. The
lifespanfunction starts Chromium once and closes it when the server stops. - A context for each request, closed in
finally. The screenshot API with Playwright uses the same pattern for the same reason: no cookies or storage go from one request to the next. context.route("**/*", ...)stops every network request from the page.set_content()does not make a network request, so the HTML still loads, anddata:URLs still work. Without the block, a test page made Chromium call a local test server.- The semaphore lets four renders run at the same time. Other requests wait for a free slot.
asyncio.wait_for()stops a render after 30 seconds, becausepage.pdf()has no timeout. The cancellation runs thefinallyblock, which closes the context.- Pydantic accepts only the values in each
Literal, so a bad value gets a 422 response before Chromium starts. - The middleware sends 413 for a
Content-Lengthof more than 2 MB. A request without that header gets past the middleware, so also set a body limit in your reverse proxy.
One request to POST /pdf:

Start the service:
.venv/bin/uvicorn app:app --port 8000
Send the sample report from a second terminal. jq puts the file into a JSON string:
jq -Rs '{html: .}' report.html | curl -s -H 'Content-Type: application/json' -d @- -o report.pdf http://127.0.0.1:8000/pdf
The response is the same three-page PDF. A bad value gets a 422 response with the reason:
curl -s -H 'Content-Type: application/json' -d '{"html": "<p>Hi</p>", "format": "A7"}' http://127.0.0.1:8000/pdf
{"detail":[{"type":"literal_error","loc":["body","format"],"msg":"Input should be 'A4', 'Letter' or 'Legal'","input":"A7","ctx":{"expected":"'A4', 'Letter' or 'Legal'"}}]}
Test the PDF output in Node.js and Python
The tests read the real PDF: pdf-lib in Node.js, pypdf in Python.
| Test file | What it checks |
|---|---|
nodejs-playwright/test/pdf.test.js |
The file starts with %PDF-. The report has 3 A4 pages (596 x 843 points). Landscape Letter is 792 x 612. preferCSSPageSize changes A4 to A5. A 1 ms pdfTimeout fails with the timer error. Firefox gives the Chromium-only error. |
python-playwright/tests/test_pdf.py |
The sync API makes 3 A4 pages with a “Monthly usage report” bookmark and a structure tree. outline without tagged gives no bookmarks. Without the route block, Chromium calls a local server. The endpoint returns application/pdf, 422 for bad input, 413 for a large body, and makes no request to the local server. |
Run them with npm test in nodejs-playwright/ and .venv/bin/python -m pytest -q in python-playwright/. In GitHub Actions, the test.sh file of each folder installs the browsers with their system libraries. Then it runs the tests and the script, and the Python folder also sends the curl call to the running service.
For PDF files without a Chromium process on your servers, the APISK HTML to PDF API converts a URL, HTML or Markdown to PDF. It is in early access.
Fix empty headers, missing backgrounds and other PDF errors
| What you see | Cause | Fix |
|---|---|---|
page.pdf: PDF generation is only supported for Headless Chromium |
The page is in Firefox or WebKit. | Launch chromium for PDF work. |
browserType.launch: Executable doesn't exist at ... |
The browser build for this Playwright version is not installed. | Run npx playwright install chromium or python -m playwright install chromium after each upgrade. |
page.pdf: Unknown paper format: A7 |
format accepts only Letter, Legal, Tabloid, Ledger and A0 to A6. |
Use width and height for other sizes. |
page.pdf: Protocol error (Page.printToPDF): scale is outside of [0.1 - 2] range |
The scale value is too small or too large. |
Use a value from 0.1 to 2. |
It looks like you are using Playwright Sync API inside the asyncio loop. |
The sync API runs inside async code. | Use playwright.async_api in async code. |
| The header or footer is empty | The template has no font-size, so the text is very small. |
Set the font size inline in the template. |
| The header covers the first lines | The top margin is too small for the header. | Make margin.top larger. |
| Background colors are missing | printBackground is false. |
Set printBackground: true, or print-color-adjust: exact on one element. |
| The PDF has no bookmarks | outline is on, but tagged is off. |
Set tagged: true too. |
The margin option has no effect |
The page CSS has an @page margin. |
Change the margin in the CSS. |
What a production PDF service needs
The scripts and the endpoint are a start. A service for real users also needs these parts:
- Fonts. The same report was 139 KB on macOS and 74 KB on Ubuntu. Install the fonts that your documents use on the server, and compare a server PDF with one from your computer.
- URL input. This endpoint takes only HTML and blocks the network. If you add a URL input, you must add protection against SSRF (server-side request forgery) for each URL and each redirect.
- Versions. Keep
playwrightpinned, and run the browser install command after each upgrade. The page count and page size tests show changes in the output. - Long jobs. The semaphore holds waiting requests in memory. For large reports or many users, put the jobs in a queue.
For a complete Node.js service with templates and Docker, read the HTML to PDF API with Puppeteer tutorial. For images instead of PDFs, the Playwright screenshot API uses the same context-per-request design. The code for this guide is in the nodejs-playwright and python-playwright folders of the html-to-pdf repository.
Frequently Asked Questions
Does Playwright page.pdf() work in Firefox or WebKit?
No. Playwright makes PDF files only with Chromium. In Firefox, page.pdf() fails with PDF generation is only supported for Headless Chromium, and WebKit has no PDF function. If your tests run in all three browsers, launch a separate Chromium browser for the PDF step.
Why does my Playwright PDF have no background colors?
Chromium leaves out backgrounds when it prints, unless you ask for them. Set printBackground: true in Node.js or print_background=True in Python. To keep the background of one element only, add print-color-adjust: exact to its CSS. Chromium also changes some text colors for print, so light text on a dark box can become gray.
How do I add page numbers to a Playwright PDF?
Set displayHeaderFooter: true and put <span class="pageNumber"></span> and <span class="totalPages"></span> in footerTemplate. Give the template an inline font-size, for example 9px, because the page CSS does not apply to it. Leave a bottom margin for the footer, for example 18 mm.
Can Playwright return the PDF as bytes without a file?
Yes. page.pdf() always returns the PDF: a Buffer in Node.js and bytes in Python. The path option is optional. With path, Playwright also writes the file and makes the missing folders.
How do I force a page break in a Playwright PDF?
Use CSS, because page.pdf() has no page break option. break-before: page starts an element on a new page, and break-inside: avoid keeps a table row or a card on one page. Chromium also accepts the older page-break-before: always.
Is Playwright or Puppeteer better for PDF generation?
Both send the same Page.printToPDF command to Chromium, so the layout rules are the same. Use the library that your project already has. Puppeteer has more PDF options: timeout, waitForFonts, omitBackground and a PDF stream. Playwright has an official Python package with the same methods.