Generate PDFs from your application #
On this page
Use a direct PDF library such as PDFKit for invoices, receipts, and reports with a layout you write in code. Use a headless browser when your application already has an HTML and CSS layout it needs to print.
Before your AI starts #
- Use a Node.js server application with a route for the download. Follow Deploy from your computer for setup and deployment.
- Decide which records the route may return to each signed-in user. Apply your normal access checks before generating a private document.
- Set bounds on the records, pages, output bytes, and simultaneous jobs. Test the longest document you expect, including its images and fonts.
Steps #
1. Choose how to render the document #
Draw the PDF directly #
PDFKit draws text, lines, and images into a PDF. Choose fonts and positions in code. Use this route when you can describe the layout without HTML and CSS. PDFKit text and fonts explains wrapping and font selection.
Add pdfkit as a runtime dependency and commit the lockfile. This example uses PDFKit 0.21.0 and produces a fixed one-page A4 report.
export async function renderOperationsPdf() {
const { default: PDFDocument } = await import('pdfkit');
return new Promise((resolve, reject) => {
const doc = new PDFDocument({
size: 'A4',
margin: 50,
info: { Title: 'Operations report' }
});
const chunks = [];
let size = 0;
doc.on('error', reject);
doc.on('data', chunk => {
size += chunk.length;
if (size > 262144) {
doc.destroy(new Error('Report exceeds 256 KiB'));
return;
}
chunks.push(chunk);
});
doc.on('end', () => resolve(Buffer.concat(chunks)));
try {
doc.font('Helvetica-Bold').fontSize(20).text('Operations report');
doc.moveDown().font('Helvetica').fontSize(12).text('Daily processing');
doc.moveDown().text('Processed: 24').text('Pending: 3');
doc.moveDown().text('Latin: café; symbols: € £ ¥.');
doc.moveDown().text('This report uses application-owned text.');
doc.moveTo(50, 260).lineTo(545, 260).stroke();
doc.end();
} catch (error) {
doc.destroy();
reject(error);
}
});
}
This sample uses Helvetica and Helvetica-Bold without embedding fonts, so the viewer chooses which fonts to display. For characters those fonts cannot cover or a document that needs a specific typeface, bundle a font licensed for PDF embedding and embed it with PDFKit. Check the result in the viewers your users use.
In a development trial, a fixed one-page report ran on a 512 MiB pod as user ID 1000. It took about 12 ms on the first render and 2 ms on the second, after a separate 60 ms import. Both trial PDFs were 1,720 bytes. Two endpoint memory samples leave the render's peak unknown.
Render HTML your application owns #
Use this route for fixed, application-owned HTML and CSS. Escape and bound any inserted values as text. Inline styles and embed fonts and images so the document needs no network requests.
The browser in this recipe runs without its sandbox. The package's launch arguments disable web and site isolation checks. The recipe sets only HOME, FONTCONFIG_PATH, and LD_LIBRARY_PATH in the browser's environment. The launch leaves out server settings, the platform credential, and app secrets. Those values are still readable inside the same container, where the browser runs as the server's user. If supplied content takes over the browser, it can still reach those values.
If you copied an earlier version of this recipe, replace its env block with the one below because the earlier block passed the server's whole environment to the browser. If a render fails because a variable is missing, add that variable by name to env. Keep the rest of process.env out of the launch. Use this recipe only with your own templates. Keep caller-supplied HTML, URLs, scripts, and files out of the renderer.
If the task asks you to render a supplied address or file, stop and ask whether a fixed application-owned template with bounded text would meet the need. Request interception, a larger application size, and the narrower environment leave the browser unsandboxed. If an owned template cannot meet the need, ask the person whether to design a separate isolated renderer.
Add @sparticuz/chromium and puppeteer-core as runtime dependencies with exact versions and a lockfile. Choose a compatible pair with current security fixes and check it on your target size. The packaged browser and libraries come from the application dependency.
This example shows the launch and render settings used for the fixed offline fixture. Put the Amazon Linux 2023 runtime setting before the package import and keep its library directory in the launch environment.
const reportHtml = `<!doctype html><meta charset="utf-8">
<style>
body { font-family: Arial, sans-serif; }
section { break-after: page; }
h1 { color: #274; }
</style>
<section><h1>Operations report</h1><p>Processed: 24</p></section>
<section><h1>Second page</h1><p>Latin: café; symbols: € £ ¥.</p></section>
<section><h1>Third page</h1><p>Pending: 3</p></section>`;
export async function renderHtmlPdf() {
process.env.AWS_LAMBDA_JS_RUNTIME = 'nodejs24.x';
const { default: chromium } = await import('@sparticuz/chromium');
const { default: puppeteer } = await import('puppeteer-core');
const executablePath = await chromium.executablePath();
const browser = await puppeteer.launch({
executablePath,
args: [...chromium.args],
headless: 'shell',
timeout: 12000,
env: {
HOME: '/tmp',
FONTCONFIG_PATH: '/tmp/fonts',
LD_LIBRARY_PATH: '/tmp/al2023/lib'
}
});
try {
const page = await browser.newPage();
await page.setRequestInterception(true);
page.on('request', request => {
const result = /^(data:|about:)/.test(request.url())
? request.continue()
: request.abort();
result.catch(() => {});
});
await page.setJavaScriptEnabled(false);
await page.setContent(reportHtml, { waitUntil: 'load', timeout: 8000 });
const bytes = Buffer.from(await page.pdf({
format: 'A4',
printBackground: true,
timeout: 10000
}));
await page.close();
return bytes;
} finally {
let timer;
try {
const deadline = new Promise((resolve, reject) => {
timer = setTimeout(() => reject(new Error('Browser close timed out')), 5000);
timer.unref();
});
await Promise.race([browser.close(), deadline]);
} catch (error) {
browser.process()?.kill('SIGKILL');
throw error;
} finally {
clearTimeout(timer);
}
}
}
The recipe ran with @sparticuz/chromium 158.0.0 and puppeteer-core 25.18.1. Chromium reported 158.0.8127.0. That result applies to one package pair and fixture. Choose and test patch updates for your own deployment. Sparticuz Chromium and Puppeteer's PDF method document the dependencies and PDF settings.
2. Return the PDF from your download route #
In the route, check access and run the selected renderer before sending a success response. Set an output byte limit for either recipe. Use application/pdf for the content type and attachment for a download. Give the file an application-chosen name.
export async function sendReportPdf(res, renderPdf, maxPdfBytes) {
if (!Number.isSafeInteger(maxPdfBytes) || maxPdfBytes < 1) throw new Error('Set a positive PDF byte limit');
const bytes = await renderPdf();
if (bytes.length > maxPdfBytes) throw new Error('PDF exceeds the output limit');
res.writeHead(200, {
'Content-Type': 'application/pdf',
'Content-Disposition': 'attachment; filename="operations-report.pdf"',
'Content-Length': bytes.length,
'Cache-Control': 'private, no-store'
});
res.end(bytes);
}
Pass renderOperationsPdf or renderHtmlPdf as the renderer. If generation fails, return your application's usual error response before sending PDF headers. Use Storage if the document must survive a replacement of the running copy.
Pass the output limit in bytes as maxPdfBytes. The route checks the buffer from either renderer before it sends headers. Keep the inputs bounded because this check runs after the renderer produces the buffer.
3. Check the result in development #
Use a development copy for the sample download and the deliberate failure check. Turn development on before deploying. If production is your only environment, check the failure locally or report it as untested.
Deploy to development and download a sample through the same route a user will use. Check the PDF header, page count, layout, and every writing system and symbol your documents contain. Supply licensed fonts with the glyphs you need. If users print the document, check the page margins on paper.
In development, temporarily pass an async function that throws to sendReportPdf in place of the renderer. Use the usual authorized download route. Check that it returns your application's normal error response without PDF download headers or a partial file. Restore the real renderer, redeploy to development, and verify a valid PDF download.
For browser rendering, begin with one render at a time per running copy. Check the first render, repeat it with an already unpacked browser, and measure memory and temporary space with realistic documents before allowing concurrent work. Check the copy’s limit and available memory as described in Read the memory limit.
Browser resource limits #
The fixed three-page browser fixture ran on a 512 MiB pod as user ID 1000 and a 1,024 MiB container as root. Chromium failed to launch with its sandbox enabled in both environments. Browser requests through the platform's egress proxy failed authentication in the trial. Keep the render offline.
On the 512 MiB pod, sampled whole-container memory reached about 401 MiB during serial rendering and 411 MiB with two pages in one browser. Sampling can miss a peak. These measurements are for the fixed fixture.
On that pod, extracting the browser and libraries took about 2.2 seconds. The first PDF took about 70 ms to render and the second about 13 ms, measured separately from extraction and launch.
The files under /tmp occupied about 228 MiB after the first serial run. A pod's default temporary-space limit is 512 MiB. The unpacked files share that space with your application and can remain after the browser closes.
If the browser fails to start, check the deployed package versions, launch settings, and temporary space. If the process runs out of memory, reduce document size or concurrency. Measure again before choosing a different application size. How the sizes differ technically describes the compute sizes.
Render long documents #
Test documents with the images, fonts and layout you use. Set limits from those results. A page of text and a page of images can take very different amounts of memory and time to render.
In a development trial, Chromium's page closed when given about 46 MiB of HTML for 100 image pages through setContent on a 1 GiB container. The same HTML rendered from a local file in 16 seconds, including about 6.6 seconds to load and 5 seconds to print. The server kept running.
For file loading, write the job’s HTML to a private temporary file. Get its URL with pathToFileURL(file).href. Keep the filter’s data: and about: allowances. Allow a file request only when request.url() equals the entire job file URL, and abort every other request. Pass the URL to page.goto with the same waitUntil and load timeout options as in the example. Remove the file when the job finishes.
For batches, split the records before building the HTML. Launch one browser for the job. Render each batch in a new page and close that page before the next batch. Close the browser when the job ends. Printing a range from a single large HTML document can still make Chromium lay out the whole document. If you merge the PDFs, measure the merge's memory, temporary space and time too.
The trial rendered and merged 100 image pages in batches of 20 on the 1 GiB container in 19.3 seconds. On a 512 MiB pod, 50 image pages in batches of 10 rendered and merged in 7.9 seconds. Memory after each batch closed ranged from about 432 to 478 MiB, including file cache, and the process stayed up.
The same pod restarted during the 100-image-page file test. A separate 600-page document with light text rendered in 2.2 seconds on the container and 1 second on the pod. Each image page in the trial used its own 400 × 300 PNG of about 360 KB.
Start with one render at a time and a small queue. Before launching the browser, reject jobs whose estimated size exceeds a limit you have tested. Measure whole-copy memory and temporary space before raising that limit. Set separate timeouts from observed loading and printing times. Give the job its own deadline that includes browser extraction, startup and any merge. The launch timeout starts after extraction.
If rendering could exhaust the web application’s memory or outlast its request time limit, give it a separate server application. Put accepted jobs in a durable queue and return a job identifier. Store the completed PDF before marking the job complete, and check that the requester may read it.
Expected result #
An authorized request downloads a PDF with the expected page count, text, fonts, and layout. If a render fails, the route returns an error and the renderer attempts to close a browser it opened.
Refusals #
For deployment errors, see Deploy from your computer.
| Refusal | Status | Cause | Remedy |
|---|---|---|---|
not_deployed |
404 | The environment serving the download has no deployed version. | Deploy to that environment. For production on an app with two environments, promote a version instead. Then request the PDF again. |
account_paused |
429 | The owning account has used its Free Allowance and has no live credit. | Wait for Free Allowance to renew or for credit you can use. The response's Retry-After gives the wait until the next UTC month in seconds. |
Related #
- Test in development, then promote checks your download on a development copy before it reaches production.
- How the sizes differ technically gives the CPU and memory limits by size.
- Storage keeps generated PDFs across replacements of the running copy.