Batch PDF Generation and Email Delivery Workflows
Month-end invoices and scheduled reports at scale: queue PDF jobs with idempotency keys, stay inside your plan's rate limit, copy results to your storage, then email the stored files.
You've built a print route and generated one PDF. Now you need 400 invoices on the first of the month, or a report emailed every Monday. This guide covers that pipeline: submitting jobs, staying within rate limits, handling failures, storing results and sending emails.
For the print route and template, see Invoice and receipt PDFs. For the request fields, see the PDF generation API guide.
Pipeline overview
trigger (cron / billing run)
→ select finalized documents
→ submit one PDF job per document (Idempotency-Key = document number)
→ poll jobs until SUCCEEDED or FAILED
→ copy each PDF to your storage and record its key + checksum
→ email the stored file
→ report failures
Keep generation and delivery as separate steps. If email delivery fails, you can retry it without generating the PDFs again, and a generation failure never sends a customer half a batch.
Plan limits
| Basic | Growth | Scale | |
|---|---|---|---|
| PDF output | Yes | Yes | Yes |
| Captures per month | 2,500 | 12,000 | 50,000 |
| Requests per minute | 40 | 80 | 200 |
Async jobs (POST /api/jobs) |
Yes | Yes | Yes |
Batch submit (POST /api/jobs/batch, up to 20 per call) |
No | Yes | Yes |
Plan details are on the pricing page. Two other limits matter for batches:
- The synchronous endpoint has 30 seconds to load the page. Async jobs run on workers and suit slow reports better.
- Failed captures don't use your monthly quota, but every submission counts toward the per-minute limit.
Submit one job per document
POST /api/jobs accepts the same body as the synchronous endpoint and returns 202 with a job ID. Add an Idempotency-Key built from the document number, so you can safely run the submission step again after a crash.
import { signPrintToken } from './print-token.js';
const API = 'https://screenshotly.app/api';
const headers = {
'x-api-key': process.env.SCREENSHOTLY_API_KEY,
'Content-Type': 'application/json',
};
export async function submitInvoicePdf(invoice, attempt = 1) {
const response = await fetch(`${API}/jobs`, {
method: 'POST',
headers: { ...headers, 'Idempotency-Key': `invoice-pdf-${invoice.number}-r${attempt}` },
body: JSON.stringify({
url: `https://app.example.com/invoices/${invoice.id}/print`,
format: 'pdf',
fullPage: true,
waitForSelector: '[data-invoice-ready]',
// Jobs can wait in the queue and be retried, so allow more time than for a synchronous call.
cookies: [{ name: 'print_token', value: signPrintToken(invoice.id, 30 * 60), secure: true, httpOnly: true }],
}),
});
if (response.status === 429) {
const retryAfter = Number(response.headers.get('Retry-After') || 60);
// A long Retry-After means the monthly quota is used up, not the per-minute limit.
if (retryAfter > 120) throw new Error(`Quota exhausted; retry after ${retryAfter}s`);
await new Promise((resolve) => setTimeout(resolve, retryAfter * 1000));
return submitInvoicePdf(invoice, attempt);
}
if (!response.ok) {
throw new Error(`Submit failed for ${invoice.number}: ${response.status} ${(await response.json()).error}`);
}
const job = await response.json(); // { id, status, replayed, statusUrl }
await db.invoices.update(invoice.id, { pdfJobId: job.id, pdfAttempt: attempt });
return job;
}
signPrintToken and the print route are defined in the invoice guide.
How idempotency keys behave
A key is permanent for your workspace. Submitting the same key again returns the original job, even if that job failed, and the request body isn't compared. That's why the key includes an attempt suffix (-r1). To deliberately run a failed invoice again, increment the attempt so the key changes.
Pace submissions to your plan
Send submissions one after another, spaced to stay under your per-minute limit, and keep some headroom for other traffic on the same account:
const PER_MINUTE = 40; // Basic. Use 80 for Growth or 200 for Scale.
const spacingMs = Math.ceil(60_000 / (PER_MINUTE * 0.8));
for (const invoice of invoices) {
await submitInvoicePdf(invoice);
await new Promise((resolve) => setTimeout(resolve, spacingMs));
}
On Growth and Scale, POST /api/jobs/batch accepts up to 20 captures per call ({ "captures": [ … ] }). If you send an Idempotency-Key with a batch, each capture's key is the batch key plus :index. The whole batch is rejected with 429 if it's larger than your remaining allowance.
Collect results
GET /api/jobs/{id} returns the job's status, which is one of QUEUED, RUNNING, SUCCEEDED, FAILED or CANCELED. A failed attempt is retried with backoff, up to three attempts in total. Once the job has succeeded, the response includes a resultUrl: a signed link that expires after a few minutes. Download the file right away.
import crypto from 'node:crypto';
export async function collectInvoicePdf(invoice) {
const job = await fetch(`${API}/jobs/${invoice.pdfJobId}`, { headers }).then((r) => r.json());
if (job.status === 'QUEUED' || job.status === 'RUNNING') return 'pending';
if (job.status !== 'SUCCEEDED') {
await db.invoices.update(invoice.id, { pdfError: job.errorMessage ?? job.status });
return 'failed';
}
const pdf = Buffer.from(await fetch(job.resultUrl).then((r) => r.arrayBuffer()));
const key = `invoices/${invoice.year}/${invoice.number}.pdf`;
await storage.put(key, pdf, { contentType: 'application/pdf' });
await db.invoices.update(invoice.id, {
pdfKey: key,
pdfSha256: crypto.createHash('sha256').update(pdf).digest('hex'),
});
return 'stored';
}
Run the collector every few seconds until no invoice is pending. Polling a job's status doesn't use your capture quota.
Before trusting a stored PDF, remember that the renderer prints whatever your print route returns. Only submit invoices that are finalized, and have the print route return its own error page for anything else, so failures are easy to spot.
Webhooks are available too (webhook.url, Basic and above). They're signed with X-Screenshotly-Signature: sha256=… and delivered up to five times. The screenshot.completed payload identifies the capture by its url, not by your invoice ID, so polling by job ID is simpler for invoice batches.
Email the stored file
Attach the file from your own storage, not a fresh render:
import nodemailer from 'nodemailer';
const transporter = nodemailer.createTransport({
host: process.env.SMTP_HOST,
port: 587,
auth: { user: process.env.SMTP_USER, pass: process.env.SMTP_PASS },
});
export async function emailInvoice(invoice) {
const pdf = await storage.get(invoice.pdfKey);
await transporter.sendMail({
from: 'billing@example.com',
to: invoice.customer.email,
subject: `Invoice ${invoice.number}`,
text: `Hello ${invoice.customer.name},\n\nInvoice ${invoice.number} for ${invoice.totalFormatted} is attached. It is due on ${invoice.dueDateFormatted}.`,
attachments: [{ filename: `${invoice.number}.pdf`, content: pdf, contentType: 'application/pdf' }],
});
await db.invoices.update(invoice.id, { emailedAt: new Date() });
}
Your email provider has its own sending limits, so pace this step separately. Record emailedAt, so that a rerun skips invoices that have already been sent.
Scheduled reports
A recurring report uses the same pipeline with a single document:
import cron from 'node-cron';
// 08:00 on the first day of every month
cron.schedule('0 8 1 * *', async () => {
const report = await db.reports.createMonthly(previousMonth()); // fixes the data for this run
const job = await submitReportPdf(report); // same as submitInvoicePdf, with the report's print route
await waitUntilStored(report, job); // poll as above, then copy to storage
await emailReport(report, ['finance@example.com']);
});
Fix the report's data when the run starts, by storing a snapshot or recording the period boundaries, and render from that. That way a retry produces the same numbers. Don't pass report data in the query string: URLs are limited to 2,048 characters.
Failure checklist
| Symptom | Likely cause | What to do |
|---|---|---|
403 Plan upgrade required |
PDF (Basic+) or batch (Growth+) isn't in your plan | Check minimumPlan in the response |
Many 429s |
Submissions exceed the per-minute limit, or the month's quota is used up | Respect Retry-After, lower your pace, check usage |
400 Unsafe URL |
The print URL points at a private host | Use a public hostname for the print route |
Cookie-domain error (a 400, or a failed job) |
The cookie's domain doesn't match the print URL's host |
Leave domain unset |
| PDF shows a login page or 404 | The token expired before the job ran, or the invoice wasn't finalized | Use a longer token TTL for jobs, and only submit finalized invoices |
Resubmitted invoice still FAILED |
The same idempotency key replayed the old job | Increment the attempt suffix |
| Wrong font | fullPage was missing, so web fonts were skipped |
Send fullPage: true or use system fonts |
Retention
Screenshotly keeps job results for your account's retention period (1–30 days). How long you keep invoices yourself is set by your tax and accounting obligations, so check with your accountant. Keep the stored key, checksum, job ID and emailedAt with each invoice, so you can show exactly which file was sent and when.
See the URL to PDF API page for plans, or read the async jobs reference. Related guides: Invoice and receipt PDFs, PDF generation API guide and CSS print styling for PDFs.
About the Author

Asad Ali
CTO at ZTABS and the developer behind Screenshotly. Writes about screenshot automation, API design, and building reliable SaaS backends with Next.js, Node.js, and TypeScript.
Credentials: CTO at ZTABS, full-stack developer, builder and maintainer of Screenshotly and its official JavaScript and Python clients
Frequently Asked Questions
How fast can I generate a month-end batch?
Your plan's per-minute request limit sets the pace: 40 requests per minute on Basic, 80 on Growth and 200 on Scale. Each queued job counts as a request when you submit it. Divide your batch size by that limit for a lower bound on submission time, then allow time for rendering and retries.
What happens if my script crashes halfway through submitting jobs?
Send an Idempotency-Key header such as invoice-pdf-INV-2026-0042 with each job. When you run the script again, already-submitted invoices return their original job (replayed: true) instead of creating a duplicate.
Should I regenerate a PDF when a customer asks for it again?
No. Serve the stored PDF you originally sent. If the data or template has changed since then, a new render would not match what the customer received.
How long does Screenshotly keep generated PDFs?
Job results follow your account's retention setting, from 1 to 30 days, and download links expire sooner than that. Copy each PDF to your own storage as soon as its job succeeds.
Ready to capture your first screenshot?
Get started with 100 free screenshots. No credit card required.