I ran into a small annoyance while generating PDFs in a Node.js service: the document arrived, but the browser did not offer the filename I wanted. I was looking in the wrong place: Puppeteer’s file options. The filename belonged in the HTTP response.
A file on disk and a response are different things#
Puppeteer’s page.pdf() returns the rendered PDF bytes. Its optional path writes a copy to disk. That filesystem path does not set the filename suggested to a browser receiving an HTTP response.
For a small on-demand document, we can send the generated bytes directly. This still holds the PDF in memory; it is not a streaming implementation.
Content Disposition#
The response header can suggest both how to handle the document and what to call it:
Content-Disposition: inline; filename="report.pdf"
inline asks the browser to display the PDF when it can. To request a download instead, use:
Content-Disposition: attachment; filename="report.pdf"
Browser settings can affect the final behavior. The filename is a suggestion, not control over the destination on the reader’s computer. A parameter on its own, such as filename="report.pdf", is not the syntax specified by RFC 6266.
An Express handler#
This TypeScript example renders a tiny document without depending on an external page. The filename is deliberately a fixed ASCII string.
import type { Response } from 'express';
import puppeteer from 'puppeteer';
export async function generatePDF(res: Response): Promise<void> {
const browser = await puppeteer.launch();
try {
const page = await browser.newPage();
await page.setContent('<!doctype html><html lang="en"><title>Report</title><h1>A small report</h1></html>');
const pdf = await page.pdf({ format: 'A4' });
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', 'inline; filename="report.pdf"');
res.send(Buffer.from(pdf));
} finally {
await browser.close();
}
}
Express receives a Node Buffer here. Puppeteer’s current PDF API returns a Uint8Array, so the conversion is explicit. An error propagates to the caller after cleanup; connect the handler to your application’s error handling.
For a document with remote images, fonts or client-side rendering, wait for the resources the document actually needs before calling pdf(). A network-idle condition alone is not a universal signal that a document is ready.
The small fix#
Set the filename in the response header; there is no need to save, rename and read the PDF back just for that.
If the filename comes from user input or contains non-ASCII characters, use a maintained header formatter rather than interpolating it into a header. The filename section of RFC 6266 explains the relevant parameters.
Related work#
Report generation was also part of my work on Valú, which brought together property information, maps, price distributions and shareable PDF documents.