Nov 20, 20264 min read

Generate PDFs in a Backend Service and Store Them in a Bucket

How to generate invoices, receipts and reports as PDFs on the server: choosing a library over a headless browser, running generation off the request path, storing results in a private bucket and serving them through signed URLs, with a TypeScript example on Encore.

Illustration for Generate PDFs in a Backend Service and Store Them in a Bucket

Almost every product eventually needs PDFs, such as invoices, receipts, contracts and reports. They look like a small feature until generation takes seconds, memory spikes and a customer asks for last year's invoice again.

This guide covers the decisions that matter, the library, where generation runs and how files are stored and served. It builds a TypeScript service that generates invoices on a queue and hands out signed download links.

PDFKit or a headless browser?

Two approaches dominate, and a drawing library such as PDFKit builds the document from code, with text, tables, images and vector shapes written to a stream, which is fast, uses little memory and runs anywhere Node does, while a headless browser such as Chromium, usually driven through Puppeteer, renders HTML and CSS to PDF, so existing templates work unchanged, at the cost of hundreds of megabytes per instance, slow start-up and a process to supervise.

Pick the library for structured documents you control, like invoices and receipts. Pick the browser when the layout is complex HTML you do not want to redraw, and then run it in a dedicated worker with limits on concurrency.

Where should generation run?

Anything that can take more than a second or two belongs off the request path. The API accepts the request and publishes a job, a worker generates the file, and the client fetches the result when it is ready, following the asynchronous request-reply pattern. That keeps slow documents from tying up API instances and lets you cap worker concurrency.

Make generation a pure function of stored data, such as the invoice row, so the same job run twice produces the same file at the same key.

How should you store and serve the files?

Store the PDF in a private bucket, and keep the bucket key on the invoice row. Serve downloads by checking the caller's permission and issuing a short-lived signed URL, so the file never passes through your API and the link expires. S3 presigned URLs and Google Cloud Storage signed URLs work the same way. Set a content type of application/pdf and a download filename so browsers handle the file correctly.

Some documents are legal records: for those, store the generated file once and never regenerate it, because a template change would alter an invoice that was already sent.

PDF generation with Encore

Encore

Encore is a backend framework with built-in infrastructure, so the private bucket and the Pub/Sub topic sit in the same TypeScript service as the generator. On deploy they become an S3 bucket and SNS with SQS in your AWS account, or Cloud Storage and Pub/Sub on GCP, and encore run provides both locally.

Set up the app

Get started
brew install encoredev/tap/encore &&
encore app create
Copy

Run in your terminal to get started locally.

// invoices/invoices.ts import { api } from "encore.dev/api"; import { Bucket } from "encore.dev/storage/objects"; import { Topic, Subscription } from "encore.dev/pubsub"; import log from "encore.dev/log"; import PDFDocument from "pdfkit"; const pdfs = new Bucket("invoice-pdfs"); // private by default interface InvoiceRequested { invoiceId: string; customer: string; lines: { description: string; amountCents: number }[]; } export const invoiceRequested = new Topic<InvoiceRequested>("invoice-requested", { deliveryGuarantee: "at-least-once", }); function render(inv: InvoiceRequested): Promise<Buffer> { return new Promise((resolve, reject) => { const doc = new PDFDocument({ size: "A4", margin: 50 }); const chunks: Buffer[] = []; doc.on("data", (c: Buffer) => chunks.push(c)); doc.on("end", () => resolve(Buffer.concat(chunks))); doc.on("error", reject); doc.fontSize(20).text(`Invoice ${inv.invoiceId}`); doc.fontSize(12).text(`Billed to ${inv.customer}`).moveDown(); let total = 0; for (const l of inv.lines) { total += l.amountCents; doc.text(`${l.description} ${(l.amountCents / 100).toFixed(2)}`); } doc.moveDown().text(`Total ${(total / 100).toFixed(2)}`); doc.end(); }); } // The key is derived from the invoice ID, so a redelivered message overwrites the same file. const keyFor = (invoiceId: string) => `invoices/${invoiceId}.pdf`; export const _generate = new Subscription(invoiceRequested, "generate-invoice-pdf", { handler: async (inv) => { const pdf = await render(inv); await pdfs.upload(keyFor(inv.invoiceId), pdf, { contentType: "application/pdf" }); log.info("invoice pdf stored", { invoiceId: inv.invoiceId, bytes: pdf.length }); }, maxConcurrency: 3, retryPolicy: { minBackoff: "10s", maxRetries: 5 }, }); export const request = api( { method: "POST", path: "/invoices", expose: true }, async (inv: InvoiceRequested): Promise<{ invoiceId: string }> => { await invoiceRequested.publish(inv); return { invoiceId: inv.invoiceId }; }, ); export const download = api( { method: "GET", path: "/invoices/:invoiceId/pdf", expose: true }, async ({ invoiceId }: { invoiceId: string }): Promise<{ url: string }> => { // Check that the caller may read this invoice before signing. const { url } = await pdfs.signedDownloadUrl(keyFor(invoiceId), { ttl: 300 }); return { url }; }, );

Install the library with npm install pdfkit and its types with npm install --save-dev @types/pdfkit. The subscriber limits itself to three documents at a time per instance, so memory stays flat, and a retry writes the same key. In a real service, add an auth handler and the permission check before signing.

A coding agent can add a second document type, such as a receipt, as another topic and generator in one change, and check the output locally by reading the file back from the local bucket.

Best fit: TypeScript teams that generate invoices, receipts or reports and want queued generation, private storage and signed links in their own AWS or GCP account.

Frequently asked questions

What is the best way to generate PDFs in a backend?

For structured documents such as invoices and receipts, a drawing library like PDFKit is fast, light on memory and needs no browser. For layouts that already exist as HTML and CSS, a headless browser renders them faithfully but uses far more memory and needs careful process management.

Should PDF generation happen inside the API request?

No. Generation can take seconds and use a lot of memory, so most backends enqueue a job, store the finished file in object storage and give the client a download link when it is ready. Only small, fast documents belong on the request path.

How should generated PDFs be stored and served?

Keep them in a private bucket under a predictable key, such as invoices/<invoice-id>.pdf, and serve them through short-lived signed URLs after an authorization check. A predictable key also makes regeneration idempotent, because writing the same invoice twice overwrites the same object.

How do I generate PDFs with Encore?

Declare an object storage bucket and a Pub/Sub topic in a TypeScript service, generate the PDF in a subscriber with PDFKit, upload it to the bucket and return a signed download URL from an API. Encore provisions the bucket and topic in your AWS or GCP account on deploy.

Deploy to your cloud on AWS and Google Cloud
without managing infrastructure

Encore lets developers and agents define application infrastructure directly in code, then automatically provisions it from local development to production in your AWS or GCP account.

~/orders — claude
Claude Code
Claude Code v2.1.180Opus 5.5~/orders