Turn Stripe invoices into your own branded PDFs
Fetch the Stripe invoice and its line items, map them to Quire's invoice fields (number, dates, customer, items, discount and tax rates), and send that JSON to the Quire API to get a PDF back. It takes about 60 lines of Node.js, and it runs on the invoice.paid webhook so every paid invoice gets your own branded PDF.
Stripe already generates an invoice PDF (invoice_pdf on the Invoice object). Make your own when you want it to match your brand, to carry information Stripe’s PDF doesn’t, or to look the same as invoices you issue outside Stripe.
1. Install
npm install quirepdf stripe
npx quirepdf-cli login [email protected] # saves a key; set it as QUIRE_API_KEY on your server
2. Map the Stripe invoice to Quire’s invoice fields
The fields used here are documented on the Invoice object: number, created, due_date, currency, status, customer_name, customer_email, customer_address, total_excluding_tax and total, plus each line’s description, quantity and amount.
import Stripe from "stripe";
import { Quire, type InvoiceData } from "quirepdf";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
const quire = new Quire(); // reads QUIRE_API_KEY
const SELLER = {
name: "Northwind Studio",
address: ["221 Market Street, Suite 400", "San Francisco, CA 94105", "United States"],
email: "[email protected]",
};
const fmtDate = (unix: number) =>
new Date(unix * 1000).toLocaleDateString("en-GB", { day: "numeric", month: "short", year: "numeric" });
export async function stripeInvoiceToPdf(invoiceId: string): Promise<Uint8Array> {
const inv = await stripe.invoices.retrieve(invoiceId);
// All line items, not just the first page that comes embedded in the invoice.
const lines: Stripe.InvoiceLineItem[] = [];
for await (const line of stripe.invoices.listLineItems(invoiceId, { limit: 100 })) lines.push(line);
// Stripe amounts are in the currency's smallest unit: cents for USD, but yen for JPY.
const fmt = new Intl.NumberFormat("en", { style: "currency", currency: inv.currency });
const minor = 10 ** (fmt.resolvedOptions().maximumFractionDigits ?? 2);
const symbol = fmt.formatToParts(0).find((p) => p.type === "currency")?.value ?? "";
// The invoice template computes totals from rates, so turn Stripe's amounts into rates.
const linesTotal = lines.reduce((sum, l) => sum + l.amount, 0);
const afterDiscount = inv.total_excluding_tax ?? linesTotal;
const discountAmount = linesTotal - afterDiscount;
const taxAmount = inv.total - afterDiscount;
const a = inv.customer_address;
const data: InvoiceData = {
number: inv.number ?? inv.id,
status: inv.status === "paid" ? "paid" : inv.status === "void" ? "void" : inv.status === "draft" ? "draft" : "due",
issued: fmtDate(inv.created),
due: fmtDate(inv.due_date ?? inv.created),
currency: symbol,
seller: SELLER,
customer: {
name: inv.customer_name ?? inv.customer_email ?? "Customer",
email: inv.customer_email ?? undefined,
address: a
? [a.line1, a.line2, [a.city, a.state, a.postal_code].filter(Boolean).join(" "), a.country].filter((x): x is string => !!x)
: [],
},
items: lines.map((l) => {
const qty = l.quantity ?? 1;
return { description: l.description ?? "Item", qty, unit_price: l.amount / minor / (qty || 1) };
}),
discount: discountAmount > 0 ? { label: "Discount", rate: discountAmount / linesTotal } : undefined,
tax: taxAmount > 0 ? { label: "Tax", rate: taxAmount / afterDiscount } : undefined,
payment: inv.hosted_invoice_url ? { method: "Card or bank transfer", link: inv.hosted_invoice_url } : undefined,
};
const pdf = await quire.render(data, { template: "invoice" });
return pdf.bytes;
}
A few notes on the mapping:
- Totals add up. The template computes subtotal, discount, tax and total from the items and the two rates. Because the rates come from Stripe’s own amounts, the result matches Stripe’s
total. - Zero-decimal currencies such as JPY are converted correctly by reading the currency’s decimal places from
Intl. The invoice template still prints two decimals (¥1,200.00). - Several tax rates on one invoice (for example state and city tax) show as one combined “Tax” line. If you need them listed separately, read
total_taxes. - Tax-inclusive prices: this mapping assumes tax is added on top. With inclusive pricing, line amounts already include tax; compute the rates from
subtotal_excluding_taxinstead.
3. Generate the PDF when an invoice is paid
A Next.js route handler for Stripe’s invoice.paid event (the same works in Express):
// app/api/stripe/webhook/route.ts
import Stripe from "stripe";
import { stripeInvoiceToPdf } from "@/lib/stripe-invoice-pdf";
const stripe = new Stripe(process.env.STRIPE_SECRET_KEY!);
export async function POST(req: Request) {
const event = stripe.webhooks.constructEvent(
await req.text(),
req.headers.get("stripe-signature")!,
process.env.STRIPE_WEBHOOK_SECRET!,
);
if (event.type === "invoice.paid") {
const invoice = event.data.object as Stripe.Invoice;
const pdf = await stripeInvoiceToPdf(invoice.id!);
await saveAndEmail(invoice, pdf); // your storage and email
}
return new Response("ok");
}
Quire doesn’t store documents, so keep the PDF in your own storage (S3, R2, your database) or regenerate it on demand. Rendering takes milliseconds.
4. Test without using your quota
Pass test: true while you build. You get the same PDF with a watermark, free and not counted:
const pdf = await quire.render(data, { template: "invoice", test: true });
Use Stripe’s test mode and stripe trigger invoice.paid to fire the webhook locally.