Skip to content

Generate in bulk

This page turns the employee list into one print-ready badge per employee, using the badge from the photo recipe and a Node.js script.

Rendering is synchronous and CPU-bound, and takes about a second for a rich page. An account renders 2 PDFs at a time, and a server 4 at most. Beyond that, an export answers 429 with EXPORT_BUSY. So:

  • send 2 requests at a time, since any extra ones will fail;
  • retry on 429 after a short pause;
  • on your own instance, more CPU means faster renders, not more parallel ones.
employees.csv
firstName,lastName,position,isManager,photo
Michael,Scott,Regional Manager,true,photos/michael.jpg
Dwight,Schrute,Assistant to the Regional Manager,false,photos/dwight.jpg
Jim,Halpert,Salesman,false,

Column names match the variable names, so each row maps to a payload. The script converts isManager to a real boolean and photo to a data URL.

  • Directorybadges/
    • employees.csv
    • Directoryphotos/
      • …
    • generate.mjs
    • Directoryout/
      • …
generate.mjs
import { readFile, writeFile, mkdir } from 'node:fs/promises';
const EXPORT_URL = 'https://app.imprime.io/api/export/code/BADGE/pdf';
const API_KEY = process.env.IMPRIME_API_KEY;
const CONCURRENCY = 2; // what one account renders at a time
// Minimal CSV parsing: use a real CSV library if fields may contain commas or quotes.
const [header, ...rows] = (await readFile('employees.csv', 'utf8')).trim().split(/\r?\n/);
const keys = header.split(',');
const employees = rows.map((row) => Object.fromEntries(row.split(',').map((v, i) => [keys[i], v])));
async function payload({ isManager, photo, ...texts }) {
return {
...texts,
isManager: isManager === 'true',
// Left out when empty: the template's default photo is drawn instead.
...(photo && { photo: `data:image/jpeg;base64,${(await readFile(photo)).toString('base64')}` }),
};
}
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
async function render(employee, index) {
const body = JSON.stringify(await payload(employee));
for (let attempt = 1; ; attempt++) {
const res = await fetch(EXPORT_URL, {
method: 'POST',
headers: { 'x-api-key': API_KEY, 'Content-Type': 'application/json' },
body,
});
if (res.status === 429 && attempt < 5) {
await sleep(attempt * 1000); // the server is busy: wait, then try again
continue;
}
if (!res.ok) throw new Error(`${employee.firstName} ${employee.lastName}: ${(await res.json()).error}`);
const warnings = JSON.parse(res.headers.get('X-Export-Warnings') ?? '[]');
for (const warning of warnings) console.warn(`⚠ ${employee.lastName}: ${warning.message}`);
const file = `out/${String(index + 1).padStart(3, '0')}-${employee.lastName}.pdf`;
await writeFile(file, Buffer.from(await res.arrayBuffer()));
console.log('✓', file);
return;
}
}
await mkdir('out', { recursive: true });
// A small worker pool: at most CONCURRENCY requests in flight.
let next = 0;
const failures = [];
await Promise.all(
Array.from({ length: CONCURRENCY }, async () => {
while (next < employees.length) {
const i = next++;
await render(employees[i], i).catch((err) => failures.push(err.message));
}
}),
);
if (failures.length) {
console.error(`\n${failures.length} badge(s) failed:\n${failures.join('\n')}`);
process.exit(1);
}
Terminal window
IMPRIME_API_KEY=<key> node generate.mjs

Failures don’t stop the batch: a name longer than its max length, a missing required value or a broken photo is reported at the end, with the reason, and the other badges are generated.

To print the whole branch, you may not need one file per employee at all. Put the badge design on a page repeated over an employees list (see Page options) and send the whole list in one request. You get one PDF with one page per employee, ready for the printer.

{
"employees": [
{ "firstName": "Michael", "lastName": "Scott", "position": "Regional Manager", "isManager": true },
{ "firstName": "Dwight", "lastName": "Schrute", "position": "Assistant to the Regional Manager", "isManager": false }
]
}
  • One template per badge type: map a column to a template code in the script ({ Manager: 'BADGE_MANAGER', Staff: 'BADGE_STAFF' }).
  • A single file for the printer: merge the generated PDFs with a tool such as qpdf or pdfunite.
  • From a queue: in a web app, generate documents in a background job instead of in the request that triggers them, so retries don’t depend on the caller.