Playwright PDF Too Slow? Move PDF Generation to a Managed API
Playwright is a great browser automation tool — but using it for PDF generation in production means managing Chromium lifecycle, browser pools, memory limits, and version compatibility. None of that is your core problem.
This guide covers how to migrate from Playwright to the FUNBREW PDF API, with concrete before/after code in Node.js and Python, a mapping of page.pdf() options to the API, and a step-by-step migration checklist.
The Playwright PDF Operations Tax
Used for PDF generation, Playwright carries the same kind of operational overhead as Puppeteer.
Memory Per Browser Context
Every PDF Playwright generates uses a Chromium browser process and a browser context. Memory grows with the number of concurrent PDF jobs, and when this runs on the same server as your application, OOM kills become a real risk on memory-constrained machines. Usage varies widely by template and environment, so measure it in yours before deciding to migrate.
Context Lifecycle Management
Playwright requires you to manage both the browser instance and browser contexts. Leaking a context is easy to do under error conditions. Left unclosed, contexts accumulate and slowly exhaust memory.
// Common mistake: context not closed on error
const context = await browser.newContext();
const page = await context.newPage();
await page.setContent(html); // if this throws, context stays open
const pdf = await page.pdf();
await context.close(); // never reached on error
Chromium Version Pinning
The Playwright docs state: "Each version of Playwright needs specific versions of browser binaries to operate." Every Playwright upgrade swaps the Chromium build with it, so you need to re-check your rendered output on each update. Where a corporate proxy blocks access to public resources, the browser download needs proxy configuration (the official docs describe how).
Cold Starts in Serverless
In serverless environments, Chromium launch time is added directly to request latency. After moving to an API, your function no longer launches Chromium (the API call itself still takes time). See the serverless PDF API guide for serverless usage.
Mapping page.pdf() Options to the API
The FUNBREW PDF API generation endpoint (POST /api/pdf/generate-from-html) accepts only page-size, orientation, margin-top/right/bottom/left, and engine under options. Unknown keys are silently ignored rather than rejected, so do not send Playwright option names as-is.
Playwright page.pdf() |
FUNBREW PDF API | Notes |
|---|---|---|
format: 'A4' |
options["page-size"]: "A4" |
A3, A4, A5, Letter, Legal only |
landscape: true |
options.orientation: "Landscape" |
Portrait / Landscape |
margin: { top: '20mm', ... } |
options["margin-top"]: 20, etc. |
Numbers in mm, 0 to 50. Defaults to 10mm |
width / height (custom size) |
Not supported | Pick one of the five sizes above |
printBackground: true |
Not supported | See Step 4 below |
displayHeaderFooter / headerTemplate / footerTemplate |
Not supported | Put headers in the HTML body. Add page numbers afterwards with /api/pdf/page-numbers |
scale / preferCSSPageSize / pageRanges |
Not supported | Set the paper size with page-size |
setContent(html, { waitUntil: 'networkidle' }) |
Not supported | There is no wait option. Send HTML that is complete at load time |
| (engine choice) | options.engine: "quality" |
Only quality renders with Chromium (Pro plan and above). fast is wkhtmltopdf |
The other big difference is the response. page.pdf() returns the PDF bytes, while the API returns JSON (data.download_url and more). You fetch the PDF itself with a GET to download_url using the same API key.
Before / After: Node.js Code Comparison
Before: Playwright (Self-managed)
const { chromium } = require('playwright');
// You must manage browser sharing across requests
let browser;
async function getBrowser() {
if (!browser || !browser.isConnected()) {
browser = await chromium.launch({
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
}
return browser;
}
async function generatePdfWithPlaywright(html) {
const browser = await getBrowser();
const context = await browser.newContext();
const page = await context.newPage();
try {
await page.setContent(html, { waitUntil: 'networkidle' });
const pdf = await page.pdf({
format: 'A4',
margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
printBackground: true,
});
return pdf;
} finally {
await context.close(); // always close in finally to prevent leaks
}
}
// Also required:
// - Browser health checks and restart logic
// - Concurrency limiting (semaphore or queue)
// - Per-page timeout handling
// - npx playwright install chromium (browser download per environment)
// - Regression checks on every Playwright update
After: Managed API
const BASE_URL = 'https://pdf.funbrew.cloud';
const headers = { Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };
async function generatePdf(html) {
// 1. Send the HTML and generate the PDF (the response is JSON)
const response = await fetch(`${BASE_URL}/api/pdf/generate-from-html`, {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({
html,
options: {
'page-size': 'A4',
'margin-top': 20,
'margin-bottom': 20,
'margin-left': 15,
'margin-right': 15,
engine: 'quality', // render with Chromium (Pro plan and above)
},
}),
});
if (!response.ok) throw new Error(`PDF API error: ${response.status}`);
const { data } = await response.json();
// 2. Fetch the PDF itself from download_url
const pdfResponse = await fetch(data.download_url, { headers });
if (!pdfResponse.ok) throw new Error(`Download error: ${pdfResponse.status}`);
return Buffer.from(await pdfResponse.arrayBuffer());
}
// No browser management, contexts, pools, or Chromium installs.
Browser launch, sharing and shutdown — plus the health checks and concurrency control around them — are replaced by two HTTP calls.
Before / After: Python Code Comparison
Before: Playwright (Python async)
import asyncio
from playwright.async_api import async_playwright
async def generate_pdf_playwright(html: str) -> bytes:
async with async_playwright() as p:
# Chromium is launched on every call
browser = await p.chromium.launch()
context = await browser.new_context()
page = await context.new_page()
try:
await page.set_content(html, wait_until="networkidle")
pdf = await page.pdf(
format="A4",
margin={"top": "20mm", "bottom": "20mm",
"left": "15mm", "right": "15mm"},
print_background=True,
)
finally:
await browser.close()
return pdf
# Requirements:
# pip install playwright
# playwright install chromium # browser download per environment
After: Managed API (Python)
import os
import requests
BASE_URL = "https://pdf.funbrew.cloud"
HEADERS = {"Authorization": f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"}
def generate_pdf(html: str) -> bytes:
resp = requests.post(
f"{BASE_URL}/api/pdf/generate-from-html",
headers=HEADERS,
json={
"html": html,
"options": {
"page-size": "A4",
"margin-top": 20, "margin-bottom": 20,
"margin-left": 15, "margin-right": 15,
"engine": "quality",
},
},
timeout=60,
)
resp.raise_for_status()
download_url = resp.json()["data"]["download_url"]
pdf = requests.get(download_url, headers=HEADERS, timeout=60)
pdf.raise_for_status()
return pdf.content
For async Python apps (FastAPI, Starlette, Django Channels), use httpx:
import os
import httpx
BASE_URL = "https://pdf.funbrew.cloud"
HEADERS = {"Authorization": f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"}
async def generate_pdf_async(html: str) -> bytes:
async with httpx.AsyncClient(timeout=60.0, headers=HEADERS) as client:
response = await client.post(
f"{BASE_URL}/api/pdf/generate-from-html",
json={
"html": html,
"options": {
"page-size": "A4",
"margin-top": 20, "margin-bottom": 20,
"margin-left": 15, "margin-right": 15,
"engine": "quality",
},
},
)
response.raise_for_status()
download_url = response.json()["data"]["download_url"]
pdf = await client.get(download_url)
pdf.raise_for_status()
return pdf.content
Performance and Resource Comparison
Response time and memory usage vary widely by template, environment and plan, so this article does not publish numbers. Measure before and after the migration with the same templates. What to look at:
- Response time: Playwright pays for browser launch (on cold start) plus rendering; the API pays for the network round trip, rendering, and fetching the PDF (a second GET).
- Memory: With the API, Chromium no longer runs on your server, so you no longer need memory for it.
- Concurrency: With the API you can send requests in parallel up to your plan's per-minute limit (Free 10 / Pro 120 / Business 300). Above that you get a 429.
Docker Image Size
The Playwright docs say of the browsers: "These browsers will take a few hundred megabytes of disk space when installed." The API version no longer needs them.
# Before: Node.js + Playwright + Chromium
FROM node:22
RUN npx playwright install chromium # browser download
# After: API client only
FROM node:22-alpine
# No Chromium needed
Node.js 20 is listed as EOL on the official releases page, so the example uses Node.js 22. Compare the actual image sizes before and after with docker images. See the Docker/Kubernetes PDF guide for container-specific configuration.
Cost Analysis: Self-Hosted vs Managed API
Self-Hosted Costs
Self-hosting costs are not just the server bill; they are driven by the engineering time below. All of it varies widely by environment, so estimate from your own team's history.
- Initial implementation of the browser pool, retries and timeouts
- Checking rendered output on every Playwright and Chromium upgrade
- Incident response for OOM kills and zombie contexts
- Downloading and caching browsers in CI
FUNBREW PDF API Costs
Free plan: 30 PDFs/month, no cost
Paid plans: fixed monthly price, each with a monthly PDF limit
(Pro 1,000 / Business 10,000)
Maintenance: HTTP client code only
See the pricing table for prices. Once you reach the monthly limit you cannot generate more that month (the API returns 429, and waiting does not clear it).
Decision Guide
| Situation | Better fit |
|---|---|
| Low monthly volume and no time for Chromium operations | API (try it on the free plan) |
| You want to run on serverless | API (no browser launch inside your function) |
You must have fine-grained page.pdf() control: custom paper sizes, header/footer templates, render waits |
Playwright (the API has no equivalent options) |
| Monthly volume far above the plan limits | Compare the pricing table against your volume |
The missing variable in most cost analyses is engineer opportunity cost. Every hour spent on Chromium management is an hour not spent on features that generate revenue.
Migration Steps
Step 1: Validate Output Quality
Paste your existing HTML template into the Playground and compare the PDF output side-by-side with your current Playwright output. The Playground needs no signup, renders with the quality engine (Chromium), adds a "TEST" watermark, and only lets you choose the paper size. If your API key uses the fast engine (the default on the Free plan), the output can differ from the Playground, so compare again on your real plan after Step 3.
Step 2: Install the API Key
# Add to .env
FUNBREW_PDF_API_KEY=your_key_here
Sign up for the free plan (30 PDFs/month) to obtain a key and test before committing. The Chromium-based quality engine needs the Pro plan or above; requesting engine: "quality" on the Free plan returns 403.
Step 3: Replace the PDF Generation Function
Create a wrapper function with the same signature as your current implementation:
// utils/pdf.js — replacement for a Playwright-based generatePdf()
const BASE_URL = 'https://pdf.funbrew.cloud';
export async function generatePdf(html, options = {}) {
const headers = { Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };
const response = await fetch(`${BASE_URL}/api/pdf/generate-from-html`, {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({
html,
options: {
'page-size': 'A4',
'margin-top': 20,
'margin-bottom': 20,
'margin-left': 15,
'margin-right': 15,
engine: 'quality',
...options, // pass API key names (page-size, orientation, margin-*, engine)
},
}),
});
if (!response.ok) {
const body = await response.text();
throw new Error(`PDF API error ${response.status}: ${body}`);
}
const { data } = await response.json();
const pdfResponse = await fetch(data.download_url, { headers });
if (!pdfResponse.ok) throw new Error(`Download error: ${pdfResponse.status}`);
return Buffer.from(await pdfResponse.arrayBuffer());
}
Call sites without options (const pdf = await generatePdf(html)) need no change. Call sites that passed Playwright options (format, a margin object, printBackground, and so on) must switch to the key names in the mapping table above; passed as-is, they are silently ignored.
Step 4: Review CSS (Media Type and Backgrounds)
The Playwright docs state: "page.pdf() generates a pdf of the page with print css media." Your @media print styles therefore carry over unchanged. If you switched to screen media with page.emulateMedia({ media: 'screen' }), the API has no media type option, so move your @media screen styles to unconditional styles:
/* Before: screen-only (applied only because emulateMedia switched to screen) */
@media screen {
.invoice { padding: 40px; background: #fff; }
}
/* After: apply unconditionally */
.invoice { padding: 40px; background: #fff; }
Backgrounds differ too. The docs for Gotenberg, which runs the quality engine, describe printBackground (default false) as "Prints the page's own background, set on html and body." and add that "Chromium prints the backgrounds of elements, such as table fills and colored boxes, whatever this field says." The FUNBREW PDF API does not send this field, so move any background colour on html or body to a wrapper element (for example <div class="page">). The fast engine can behave differently, so check the output.
Step 5: Convert SSR-dependent Patterns
If you used page.waitForSelector() or page.evaluate() to inject data before export, move that logic server-side. The API has no option to wait for an element and no way to run a script before rendering.
// Before: Playwright DOM injection
await page.evaluate((data) => {
document.querySelector('#total').textContent = data.total;
document.querySelector('#customer').textContent = data.customerName;
}, invoiceData);
const playwrightPdf = await page.pdf();
// After: Server-side HTML generation (SSR)
const html = renderInvoiceTemplate(invoiceData); // build complete HTML first
const pdf = await generatePdf(html); // then call the API
Step 6: Remove Playwright Dependencies
npm uninstall playwright @playwright/test
# Remove from Dockerfile:
# RUN npx playwright install chromium
# Remove from CI/CD:
# - Playwright Chromium cache steps
# - PLAYWRIGHT_BROWSERS_PATH env var
If you also use Playwright for E2E tests, keep @playwright/test. See the full PDF API production checklist for post-migration hardening.
Common Migration Issues and Fixes
Issue 1: External images not rendering
Cause: Rendering happens on FUNBREW's servers, which cannot reach localhost or private network URLs.
Fix: Embed images as Base64 data URIs.
import fs from 'fs';
import path from 'path';
const MIME_TYPES = { png: 'image/png', jpg: 'image/jpeg', jpeg: 'image/jpeg', svg: 'image/svg+xml', webp: 'image/webp' };
function embedImage(imagePath) {
const ext = path.extname(imagePath).slice(1).toLowerCase();
const data = fs.readFileSync(imagePath).toString('base64');
return `data:${MIME_TYPES[ext]};base64,${data}`;
}
const html = `<img src="${embedImage('./logo.png')}" alt="Logo">`;
Issue 2: Google Fonts not loading
Cause: The API has no option to wait before rendering, so a font that has not arrived in time can be replaced by a fallback font.
Fix: Embedding the font as Base64 removes the external fetch. For Japanese text, the quality engine is expected to render with a Japanese font such as Noto Sans CJK JP, but check the generated PDF.
<style>
/* Option A: Google Fonts URL (when the renderer can reach the internet) */
@import url('https://fonts.googleapis.com/css2?family=Inter&display=swap');
/* Option B: embed a Base64 font (no external fetch) */
@font-face {
font-family: 'Inter';
src: url('data:font/woff2;base64,d09GMgAB...') format('woff2');
}
body { font-family: 'Inter', sans-serif; }
</style>
Issue 3: Chart.js renders blank or half-drawn
Cause: The Gotenberg docs for the quality engine say "Chromium prints the page as soon as it loads, though.", so the PDF can be captured mid-animation. The fast engine (wkhtmltopdf) can render differently from quality.
Fix: Set engine: "quality", load Chart.js synchronously in the <head>, and set animation: false (Chart.js docs: "chart.options.animation = false; // disables all animations").
new Chart(ctx, {
type: 'bar',
data: {
labels: ['Jan', 'Feb', 'Mar'],
datasets: [{ label: 'Revenue', data: [120, 150, 180] }],
},
options: {
animation: false, // Required for PDF generation
responsive: true,
},
});
See the report generation guide for a complete Chart.js + PDF pattern.
Issue 4: Timeouts and 429 errors
Fix: A 429 from the per-minute limit carries a Retry-After header; wait that many seconds and retry. A 429 from the monthly limit (no Retry-After) will not clear by waiting, so fail instead of retrying.
const BASE_URL = 'https://pdf.funbrew.cloud';
async function generatePdfWithRetry(html, options = {}, maxRetries = 3) {
const headers = { Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };
for (let attempt = 1; attempt <= maxRetries; attempt++) {
const response = await fetch(`${BASE_URL}/api/pdf/generate-from-html`, {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({ html, options }),
signal: AbortSignal.timeout(60_000), // 60 seconds
});
if (response.status === 429) {
const retryAfter = response.headers.get('Retry-After');
if (!retryAfter || attempt === maxRetries) {
throw new Error(`Rate or monthly limit reached: ${await response.text()}`);
}
await new Promise(r => setTimeout(r, Number(retryAfter) * 1000));
continue;
}
if (response.status >= 500 && attempt < maxRetries) {
await new Promise(r => setTimeout(r, 2 ** attempt * 1000)); // exponential backoff
continue;
}
if (!response.ok) throw new Error(`API error ${response.status}: ${await response.text()}`);
const { data } = await response.json();
const pdfResponse = await fetch(data.download_url, { headers });
if (!pdfResponse.ok) throw new Error(`Download error: ${pdfResponse.status}`);
return Buffer.from(await pdfResponse.arrayBuffer());
}
}
See the PDF API error handling guide for the complete retry and alerting pattern.
Migration Checklist
Pre-migration
[ ] Paste HTML into the Playground — compare output with Playwright
[ ] Sign up for free plan, obtain FUNBREW_PDF_API_KEY
[ ] Choose the engine (Chromium-based quality needs Pro plan or above)
[ ] Create wrapper function generatePdf(html, options) (generate, then fetch download_url)
[ ] Visual diff the PDF output in staging
CSS review
[ ] If you used emulateMedia screen, move @media screen rules to unconditional styles
[ ] Verify page-break-before / break-before: page behaviour
[ ] Convert external fonts to @font-face Base64 if needed
[ ] Move html / body background colours to a wrapper element
Code review
[ ] Convert page.pdf() options to API key names (page-size, orientation, margin-*, engine)
[ ] Replace headerTemplate / footerTemplate with HTML body content or /api/pdf/page-numbers
[ ] Convert page.waitForSelector() calls to SSR
[ ] Convert page.evaluate() DOM injections to template rendering
[ ] Verify local image paths are converted to Base64
Production cutover
[ ] Add error handling (retry 429 with Retry-After; alert on monthly-limit 429 and 5xx)
[ ] Set a client timeout
[ ] Run: npm uninstall playwright (keep @playwright/test if you use it for E2E)
[ ] Remove npx playwright install from Dockerfile
[ ] Remove Playwright cache from CI/CD
[ ] Right-size server memory (Chromium no longer required)
What Improves After Migration
| Aspect | Playwright (Self-managed) | FUNBREW PDF API |
|---|---|---|
| Memory usage | Browser processes and contexts | HTTP client only |
| Cold start | Chromium launch time | No browser launch on your side |
| Concurrency | Manual context pooling | Parallel requests up to the plan's per-minute limit |
| Chromium version management | Required on every update | Not needed |
| Serverless (Lambda/Cloud Run) | Workarounds to bundle a browser | Works with plain HTTP calls |
| Docker image | A few hundred MB larger for the browser | No browser needed |
| Fine-grained control | Every page.pdf() option |
5 paper sizes, orientation, margins and engine only |
Try It Before Committing
Paste your Playwright HTML template into the Playground and see the PDF output instantly — no signup required. When you are ready to test with code, the free plan (30 PDFs/month) gives you API access to validate against your staging environment.
For the full API reference, see the documentation.
Related
- Puppeteer to PDF API Migration — Same migration path, Puppeteer-specific context
- PDF Report Generation Guide — Chart.js, cron scheduling, email delivery
- PDF API Quickstart by Language — Node.js, Python, PHP code examples
- HTML to PDF CSS Tips — CSS compatibility and print media type tips
- PDF API Serverless Guide — Lambda and Cloud Run deployment
- PDF API Error Handling Guide — Retry logic and alerting patterns
- PDF API Production Checklist — Post-migration hardening
- PDF API Docker/Kubernetes Guide — Container-based deployment
- API Documentation — Full endpoint reference