PDF generation in Cloudflare Workers
Workers cannot run a browser at all — no Chromium, no native binaries. An HTTP call is the only option, and the streaming Response makes it a clean one.
The code
export default {
async fetch(request: Request, env: { PDFCRAFT_API_KEY: string }): Promise<Response> {
const { html } = await request.json<{ html: string }>();
const upstream = await fetch('https://api.pdfcraft.dev/v1/render', {
method: 'POST',
headers: {
authorization: `Bearer ${env.PDFCRAFT_API_KEY}`,
'content-type': 'application/json',
},
body: JSON.stringify({ html, options: { printBackground: true } }),
});
if (!upstream.ok) return new Response(upstream.body, { status: upstream.status });
// Straight through — the Worker never holds the PDF.
return new Response(upstream.body, {
headers: {
'content-type': 'application/pdf',
'content-disposition': 'attachment; filename="document.pdf"',
},
});
},
};What to watch for
- Put the key in a Worker secret (`wrangler secret put PDFCRAFT_API_KEY`), not in `wrangler.toml` — `vars` in that file are committed to your repository.
- Returning `upstream.body` keeps the Worker under its memory limit no matter how large the PDF is.
- A Worker on the free plan has 10 ms of CPU time, but waiting on a subrequest is not CPU time. A 20-second render is fine.
Why not run the browser yourself
You can. Puppeteer and Playwright both work, and for a script you run by hand they are the right answer. The cost arrives at the point it becomes a service someone depends on: one long-lived browser per process rather than one per request, a semaphore so four renders do not become forty, a hard timeout that force-closes a hung page before it holds a slot forever, a scheduled restart because Chromium leaks, and a Chromium version you are now responsible for patching.
None of that is hard. All of it is work that has nothing to do with your product, and it fails under concurrency rather than in testing — which is the worst time to discover it.
Other frameworks
- PDF generation in Next.js
- PDF generation in Django
- PDF generation in Ruby on Rails
- PDF generation in Laravel
- PDF generation in AWS Lambda
- PDF generation in Supabase Edge Functions
- PDF generation in Spring Boot
- PDF generation in FastAPI
- PDF generation in Express
- PDF generation in ASP.NET Core
- PDF generation in n8n