Tutorial: a month of invoices from one CSV, in one request
Turn a spreadsheet of customers into one PDF per row with PageRush batch renders. A Typst template, a CSV file and about twenty lines of Python or Node.js, plus what happens when a row is wrong.
- tutorial
- batch
- python
- nodejs
Month-end looks the same in most small businesses: a spreadsheet with one row per customer, and a pile of invoices to make from it. You can loop over the rows and call a PDF API once per row, but then you are writing the retry logic, counting what failed, and zipping the results yourself.
PageRush now does that loop for you. A batch render takes up to 10,000 items in one request, renders one PDF per item, and gives you a status for every item and one ZIP of the PDFs. This tutorial builds a month of invoices from a CSV file, start to finish.
You need a PageRush account (the free plan is enough for a small run), an API key from your project's settings, and either Python 3.9 or later or Node.js 20 or later. The program is shown in both.
1. The template
PageRush templates are written in Typst. Every render's data arrives as a file called data.json, so the template reads it once and uses its fields:
#let data = json("data.json")
#set page(paper: "a4", margin: 2cm)
#set text(size: 11pt)
#grid(
columns: (1fr, auto),
[*Acme Design Studio* \ 12 MG Road, Bengaluru],
align(right)[= Invoice #data.number],
)
#v(1em)
*Billed to:* #data.customer \
*Date:* #data.date
#v(1em)
#table(
columns: (1fr, auto),
stroke: 0.5pt + luma(200),
inset: 8pt,
table.header([*Description*], [*Amount*]),
[#data.description], align(right)[₹#data.amount],
)
#align(right)[*Total due: ₹#data.amount*]
Create it in the dashboard (New template, then Typst code), paste this in, and copy its id (it starts with tpl_). You can also design the same invoice in the visual editor; batches work the same either way.
2. The data
Export your spreadsheet as CSV. Each column becomes a field the template can read:
number,customer,date,description,amount
INV-2026-11-001,Asha Traders,30 Nov 2026,"Brand identity, November retainer","45,000"
INV-2026-11-002,Ravi Foods,30 Nov 2026,Menu redesign,"18,500"
INV-2026-11-003,Meera Textiles,30 Nov 2026,Catalogue layout (24 pages),"62,000"
Every value in a CSV is text, which suits this template: it prints the amount exactly as the spreadsheet has it.
3. The program
In Python
Install the SDK and set your key:
pip install pagerush
export PAGERUSH_API_KEY=pk_live_your_key
Then the whole program:
import csv
import pagerush
TEMPLATE_ID = "tpl_your_template_id"
client = pagerush.PageRush() # reads PAGERUSH_API_KEY
with open("invoices.csv", newline="", encoding="utf-8") as f:
items = [{"data": row, "filename": row["number"]} for row in csv.DictReader(f)]
batch = client.batches.create(TEMPLATE_ID, items=items, metadata={"run": "2026-11"})
print(f"Queued {batch['item_count']} invoices as {batch['id']}")
batch = client.batches.wait(batch["id"], timeout=600)
print(f"{batch['status']}: {batch['succeeded']} made, {batch['failed']} failed")
for item in batch["items"]:
if item["error"]:
print(f" row {item['index'] + 2}: {item['error']['code']} {item['error']['message']}")
if batch["succeeded"]:
with open("invoices-2026-11.zip", "wb") as f:
f.write(client.batches.download_zip(batch["id"]))
Run it, and invoices-2026-11.zip holds INV-2026-11-001.pdf, INV-2026-11-002.pdf and so on. The filename you give an item becomes its name in the ZIP; PageRush adds .pdf, keeps names safe on every operating system, and adds -2, -3 if two rows share one.
In Node.js
The same program in JavaScript. Node has no CSV reader built in, and the amounts in this file contain commas inside quotes, so use a real CSV parser rather than splitting lines on commas:
npm install pagerush csv-parse
export PAGERUSH_API_KEY=pk_live_your_key
Save this as invoices.mjs and run it with node invoices.mjs:
import { readFile, writeFile } from "node:fs/promises";
import { parse } from "csv-parse/sync";
import { PageRush } from "pagerush";
const TEMPLATE_ID = "tpl_your_template_id";
const client = new PageRush(); // reads PAGERUSH_API_KEY
const rows = parse(await readFile("invoices.csv", "utf8"), { columns: true });
const items = rows.map((row) => ({ data: row, filename: row.number }));
const created = await client.batches.create(TEMPLATE_ID, { items, metadata: { run: "2026-11" } });
console.log(`Queued ${created.item_count} invoices as ${created.id}`);
const batch = await client.batches.wait(created.id, { timeout: 600_000 });
console.log(`${batch.status}: ${batch.succeeded} made, ${batch.failed} failed`);
for (const item of batch.items ?? []) {
if (item.error) console.log(` row ${item.index + 2}: ${item.error.code} ${item.error.message}`);
}
if (batch.succeeded > 0) {
await writeFile("invoices-2026-11.zip", await client.batches.downloadZip(batch.id));
}
It produces the same ZIP. The SDK is written in TypeScript, so in a .ts file you get types for the batch and its items.
What happens behind that request
A few things are worth knowing, because they decide how you handle the result.
Your quota is checked for the whole batch before anything renders. A batch of 300 needs 300 renders' worth of quota or credits, and if you have less, the request is refused with 402 QUOTA_EXCEEDED and nothing is reserved. A batch never stops halfway because the quota ran out at row 211.
One bad row doesn't sink the run. Each item renders on its own. If row 7 is missing its customer, that item fails with TEMPLATE_COMPILE_FAILED and Typst's message, the other items carry on, and the batch finishes as partial rather than succeeded. Failed items are never charged. The loop over batch["items"] above prints which rows failed (the + 2 turns the item's index into a spreadsheet row number, counting the header), so you can fix them and send just those rows again.
Items render at your plan's pace. A batch renders as many items at a time as your plan allows concurrent renders, alongside anything else you render, in groups of up to ten from the same template. In our test, 500 invoices took about a minute and a half with two concurrent renders, the free plan's allowance; more concurrent renders go faster. wait polls until the batch is done, and its timeout (here ten minutes) is how long you are willing to wait in this program, not a limit on the batch: for thousands of rows on a small plan, raise it, or use a callback (below).
Retries are safe. The SDK sends an idempotency key with create, so if the network drops and it retries, you still get one batch, not two.
The PDFs are kept for 24 hours. Download the ZIP any time in that window (up to 10 times). Each item is also an ordinary job, so client.jobs.download(item["job_id"]) fetches one invoice on its own, for example to email it. If you would rather we kept nothing once you have the files, pass delete_after_download=True, and the PDFs are deleted as soon as the whole ZIP has been downloaded.
Don't want to poll? Use a callback
For a nightly job, waiting in a loop is fine. If the batch is started from a web app, you may prefer to be told when it is done. Pass a callback_url:
batch = client.batches.create(
TEMPLATE_ID,
items=items,
callback_url="https://example.com/webhooks/pagerush",
)
When the batch finishes, PageRush sends one signed POST to that address with the event batch.completed and the batch's summary as JSON. Verify it with your project's webhook secret, then download the ZIP:
from pagerush import webhooks
event = webhooks.construct_event(raw_body, request_headers, webhook_secret) # raises if the signature is wrong
if event.event == "batch.completed":
zip_bytes = client.batches.download_zip(event.batch_id)
In Node.js:
import { constructEvent } from "pagerush";
const event = await constructEvent(rawBody, headers, process.env.PAGERUSH_WEBHOOK_SECRET); // throws if the signature is wrong
if (event.event === "batch.completed") {
const zip = await client.batches.downloadZip(event.batch_id);
}
Pass the raw request body exactly as it arrived; parsing the JSON and serialising it again changes the bytes and the signature no longer matches. Callbacks can occasionally arrive twice, so skip a batch_id you have already handled.
The same thing without an SDK
The API is plain HTTP, so any language works:
curl -X POST https://pagerush.dev/v1/templates/tpl_your_template_id/batches \
-H "Authorization: Bearer $PAGERUSH_API_KEY" \
-H "Content-Type: application/json" \
-d '{"items": [
{"data": {"number": "INV-2026-11-001", "customer": "Asha Traders", "date": "30 Nov 2026",
"description": "Brand identity, November retainer", "amount": "45,000"},
"filename": "INV-2026-11-001"}
]}'
# Progress, and each item's result
curl -H "Authorization: Bearer $PAGERUSH_API_KEY" https://pagerush.dev/v1/batches/bat_...
# Once it has finished
curl -H "Authorization: Bearer $PAGERUSH_API_KEY" -o invoices.zip https://pagerush.dev/v1/batches/bat_.../zip
Limits
- Up to 10,000 items per batch, with the whole request under 8 MB (plenty for invoice-sized rows). For more, send several batches.
- Up to 3 batches rendering at a time per account.
- Each item counts as one render, or more for long documents (one per 50 pages started), exactly as a single render would.
The API docs have the full reference, and the SDKs for Node.js, Python, PHP and Go document batches in their READMEs. If something about batches gets in your way, tell us: we would rather hear it now.