Frameworks · Updated 2026-12-03
Generate PDFs in AWS Lambda without Chrome
The usual way to make PDFs in Lambda is to ship headless Chrome with the function. This guide shows a smaller way: the function sends a template id and your JSON to DevilPDF and gets a finished PDF back. You can return a link, save the file to S3, or send the PDF straight back through a Function URL or API Gateway.
You need a Node.js 20 or Python Lambda and a DevilPDF API key. The free plan includes 500 documents a month.
#Why headless Chrome is hard in Lambda
AWS publishes its Lambda quotas. The ones that matter here:
| Quota | Value |
|---|---|
| Deployment package (.zip, direct upload) | 50 MB zipped |
| Function code plus all layers | 250 MB unzipped |
| Response payload, synchronous invocation | 6 MB |
/tmp storage | 512 MB by default |
The @sparticuz/chromium README, the usual Chromium build for Lambda, gives the binary as 130.62 MiB uncompressed and 33.21 MiB at the best Brotli compression level. That fits, but it takes most of the 250 MB, and it is unpacked into /tmp on every cold start before the first page can render. Fonts for non-Latin scripts add more, and you keep the Chromium and Puppeteer versions in step yourself.
With an API, the function is a short HTTP request. It needs no layer, very little memory, and nothing to unpack.
#1. Store the API key
Sign up, open API keys in the dashboard and create a key. It starts with dp_live_. Add it to the function as an environment variable:
aws lambda update-function-configuration \
--function-name invoice-pdf \
--environment "Variables={DEVILPDF_API_KEY=dp_live_...}"Environment variables are encrypted at rest. If your team keeps secrets in AWS Secrets Manager or SSM Parameter Store, read the key from there once per cold start instead. Either way, never put it in client code.
Also raise the function timeout from the default 3 seconds. A one-page document usually comes back in well under a second, but DevilPDF gives a template up to 30 seconds to render, so 30 seconds is a safe setting.
#2. Render and return a link
The simplest handler returns DevilPDF's signed download link. Node.js 20 has fetch built in, so there is nothing to install.
export const handler = async (event) => {
const order = JSON.parse(
event.isBase64Encoded ? Buffer.from(event.body, "base64").toString() : event.body ?? "{}"
);
const res = await fetch("https://devilpdf.com/v1/render", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DEVILPDF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({
template: "invoice",
data: {
number: order.number,
issue_date: order.issue_date,
customer: { name: order.customer_name, address: order.customer_address },
items: order.items,
},
filename: `invoice-${order.number}`,
}),
});
const doc = await res.json();
if (!res.ok) {
return { statusCode: 502, body: JSON.stringify({ error: doc.error.message }) };
}
return { statusCode: 200, body: JSON.stringify({ url: doc.url, pages: doc.pages }) };
};Every account can use seven starter templates: invoice, quote, receipt, statement, report, packing-slip and certificate. The invoice starter adds up line items and tax itself, so each item only needs name, quantity and unit_price. Fetch GET https://devilpdf.com/v1/templates/invoice to see every field it accepts.
The link is signed and needs no API key. It stays valid for your plan's retention (24 hours on Free, up to 30 days on paid plans), or less if you set expires_in. See storage.
#3. Save the PDF to your S3 bucket
Add "output": "file" and the response body is the PDF itself. DevilPDF keeps no copy. Put the bytes in S3 with the AWS SDK v3, which is already included in the Node.js 20 runtime.
import { S3Client, PutObjectCommand } from "@aws-sdk/client-s3";
const s3 = new S3Client({});
const BUCKET = process.env.PDF_BUCKET;
async function renderPdf(body) {
const res = await fetch("https://devilpdf.com/v1/render", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.DEVILPDF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ ...body, output: "file" }),
});
if (!res.ok) {
const { error } = await res.json();
throw new Error(`${error.type}: ${error.message}`);
}
return Buffer.from(await res.arrayBuffer());
}
export const handler = async (event) => {
const order = JSON.parse(event.body ?? "{}");
const pdf = await renderPdf({
template: "invoice",
data: {
number: order.number,
customer: { name: order.customer_name },
items: order.items,
},
});
const key = `invoices/${order.number}.pdf`;
await s3.send(
new PutObjectCommand({
Bucket: BUCKET,
Key: key,
Body: pdf,
ContentType: "application/pdf",
})
);
return { statusCode: 200, body: JSON.stringify({ bucket: BUCKET, key, bytes: pdf.length }) };
};The function's execution role needs s3:PutObject on that bucket. Errors from DevilPDF still come back as JSON, which is why renderPdf checks res.ok before reading the body as a file.
#4. Return the PDF through a Function URL or API Gateway
To send the file straight to the caller, base64 the bytes and set isBase64Encoded. Reuse renderPdf from step 3.
export const handler = async (event) => {
const number = event.queryStringParameters?.number;
if (!number) return { statusCode: 400, body: "Missing ?number=" };
const order = await loadOrder(number);
const pdf = await renderPdf({ template: "invoice", data: order });
return {
statusCode: 200,
headers: {
"Content-Type": "application/pdf",
"Content-Disposition": `inline; filename="invoice-${number}.pdf"`,
},
body: pdf.toString("base64"),
isBase64Encoded: true,
};
};
// Replace with your database lookup.
async function loadOrder(number) {
return {
number,
customer: { name: "Acme Robotics Inc." },
items: [{ name: "Consulting", quantity: 3, unit_price: 150 }],
};
}Function URLs and API Gateway HTTP APIs decode the body and send the caller a binary PDF. A REST API also needs application/pdf added to its binary media types.
Remember the 6 MB response limit. Base64 makes a file about a third larger, so a PDF over about 4.5 MB will not fit. For large documents, return a link (step 2) or save to S3 (step 3) instead.
#5. The same in Python
Python Lambda runtimes include boto3. This uses urllib from the standard library, so the function has no dependencies to package.
import json
import os
import urllib.error
import urllib.request
import boto3
s3 = boto3.client("s3")
BUCKET = os.environ["PDF_BUCKET"]
def render_pdf(body):
req = urllib.request.Request(
"https://devilpdf.com/v1/render",
data=json.dumps({**body, "output": "file"}).encode(),
headers={
"Authorization": f"Bearer {os.environ['DEVILPDF_API_KEY']}",
"Content-Type": "application/json",
},
method="POST",
)
try:
with urllib.request.urlopen(req, timeout=60) as res:
return res.read()
except urllib.error.HTTPError as e:
error = json.loads(e.read())["error"]
raise RuntimeError(f"{error['type']}: {error['message']}") from None
def lambda_handler(event, context):
order = json.loads(event.get("body") or "{}")
pdf = render_pdf({
"template": "invoice",
"data": {
"number": order["number"],
"customer": {"name": order["customer_name"]},
"items": order["items"],
},
})
key = f"invoices/{order['number']}.pdf"
s3.put_object(Bucket=BUCKET, Key=key, Body=pdf, ContentType="application/pdf")
return {"statusCode": 200, "body": json.dumps({"bucket": BUCKET, "key": key})}To return the file instead, use base64.b64encode(pdf).decode() as the body and set "isBase64Encoded": True, as in step 4. If you already package requests, requests.post(..., json=body) works the same way.
#Let DevilPDF write to S3 for you
On paid plans, DevilPDF can upload each file to a bucket you own, so the bytes never pass through your function. Connect the bucket once in the dashboard under Settings → Storage (bucket, region, an access key that can only PutObject, and an optional prefix), then add "destination": "s3" to the render:
{ "template": "invoice", "data": { "number": "INV-1001" }, "filename": "INV-1001", "destination": "s3" }The file lands at <prefix>/<document id>/<filename>.pdf. In the response, url is the object's address in your bucket and expires_at is null. It also works with Cloudflare R2, Backblaze B2, Wasabi, MinIO and DigitalOcean Spaces. See your own bucket.
#Many documents at once
Do not loop over /v1/render inside one invocation for a month-end run. Send the documents to POST /v1/render/batch with a webhook_url, and let a second Lambda behind a Function URL handle each document.succeeded event as it arrives. Batch documents are always stored and returned as links, and "destination": "s3" works with batches too. For a single slow document, "async": true returns 202 straight away so your function does not wait. See async and batch and webhooks.
A failed render never counts against your allowance. For retry rules, see errors.
#Next steps
- Quickstart
- Render a document: every field
/v1/renderaccepts. - Generate PDFs in Node.js and in Python.
- Get a free API key