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 and the package's launch arguments disable web and site isolation checks. Use it 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 and a larger application size 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 inheritedLibraryPath = process.env.LD_LIBRARY_PATH;
const browser = await puppeteer.launch({
executablePath,
args: [...chromium.args],
headless: 'shell',
timeout: 12000,
env: {
...process.env,
LD_LIBRARY_PATH: inheritedLibraryPath
? `/tmp/al2023/lib:${inheritedLibraryPath}`
: '/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. 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) {
const bytes = await renderPdf();
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.
In the browser renderer you pass to sendReportPdf, check bytes.length against your output limit before returning the buffer. Throw an error if it exceeds that limit. Keep the inputs bounded because this check runs after the browser produces the buffer.
3. Check the result in development #
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.
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 the next UTC month to start. The response's Retry-After gives the wait 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.