PDF API Integration for SaaS: Multi-Tenant Architecture Guide
If you are building a SaaS product, PDF generation requirements will show up sooner or later. Tenants want to download invoices, export monthly reports, generate contracts, and produce certificates — none of which are worth running your own PDF rendering engine for.
This guide covers the architecture decisions involved in integrating a PDF generation API into a multi-tenant SaaS product. Rather than just showing how to call an API, it addresses the full scope: tenant isolation, template management, async processing, webhook delivery, white-labeling, rate limiting, and cost control.
Examples use FUNBREW PDF, but the patterns apply to any PDF API. For basic API calls, see the quickstart by language. For production stability concerns, see the PDF API production checklist.
When SaaS Products Need PDF Generation
PDF output requirements in SaaS products fall into five categories:
| Use case | Examples | Typical volume | Recommended pattern |
|---|---|---|---|
| Invoices and receipts | Automatic issuance at billing time | Hundreds to tens of thousands per month | Async batch |
| Monthly and weekly reports | PDF export of dashboard data | On-demand | Synchronous |
| Contracts and agreements | Auto-generation at contract signing | On-demand | Synchronous |
| Certificates and credentials | Issued on course completion | Event-driven | Async |
| Forms and slips | Purchase orders, delivery notes | Monthly batch | Async batch |
Each category has different requirements for response time, volume, and tenant isolation. Clarify which scenario you are solving before choosing an architecture.
Architecture Patterns: Sync, Async, and Batch
Pattern 1: Synchronous (user wants the PDF right now)
The simplest pattern: generate the PDF when the user clicks "Download" and return it immediately.
Browser → App server → PDF API → App server → Browser (PDF response)
FUNBREW PDF's generation API returns JSON, not the PDF itself. You GET data.download_url from the response with the same API key to fetch the PDF. Because the later examples reuse these two steps, wrap them in a helper first.
// lib/funbrew-pdf.ts: helper for "generate, then fetch download_url"
const FUNBREW_BASE_URL = 'https://pdf.funbrew.cloud';
const authHeaders = { Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}` };
export class PdfApiError extends Error {
constructor(public status: number, public retryAfter: string | null, message: string) {
super(message);
}
}
export async function generatePdf(
html: string,
options: Record<string, string | number> = { 'page-size': 'A4' },
timeoutMs = 60_000,
): Promise<Buffer> {
const res = await fetch(`${FUNBREW_BASE_URL}/api/pdf/generate-from-html`, {
method: 'POST',
headers: { ...authHeaders, 'Content-Type': 'application/json', Accept: 'application/json' },
body: JSON.stringify({ html, options }),
signal: AbortSignal.timeout(timeoutMs),
});
if (!res.ok) {
// A 429 with Retry-After (per-minute limit) clears after waiting; one without it
// (monthly or storage limit) does not
throw new PdfApiError(res.status, res.headers.get('Retry-After'), `PDF generation failed: HTTP ${res.status}`);
}
const { data } = await res.json();
const pdf = await fetch(data.download_url, {
headers: authHeaders,
signal: AbortSignal.timeout(timeoutMs),
});
if (!pdf.ok) {
throw new PdfApiError(pdf.status, pdf.headers.get('Retry-After'), `PDF download failed: HTTP ${pdf.status}`);
}
return Buffer.from(await pdf.arrayBuffer());
}
// SaaS backend: synchronous PDF endpoint
import express from 'express';
import { generatePdf } from './lib/funbrew-pdf';
const router = express.Router();
router.post('/invoices/:id/download', async (req, res) => {
const invoice = await Invoice.findByTenantAndId(
req.tenant.id, // multi-tenant: scope by tenant ID
req.params.id
);
if (!invoice) {
return res.status(404).json({ error: 'Invoice not found' });
}
const html = await renderInvoiceTemplate(invoice, req.tenant);
// Margins are numbers in mm (0-50)
const pdfBuffer = await generatePdf(html, {
'page-size': 'A4',
'margin-top': 20,
'margin-bottom': 20,
'margin-left': 15,
'margin-right': 15,
}, 30_000); // 30-second timeout
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="invoice-${invoice.number}.pdf"`);
res.send(pdfBuffer);
});
Use synchronous generation when generating and fetching the PDF finishes within the time your users are willing to wait (light HTML, few concurrent requests per tenant). The wait depends on the document, so measure it with your real templates. If users would wait too long, move to the next pattern.
Pattern 2: Asynchronous (job queue)
For heavy PDFs, large volumes, or situations where users do not need the file instantly, use a job queue. Return a job ID immediately, then notify via webhook or email when the PDF is ready.
Browser → App server (returns job ID)
↓ (enqueue job)
Worker → PDF API → S3 upload
↓
Webhook → App server → Notify browser
// BullMQ job queue for async PDF generation
import { Queue, Worker, UnrecoverableError } from 'bullmq';
import { Redis } from 'ioredis';
import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3';
import { generatePdf, PdfApiError } from './lib/funbrew-pdf';
const connection = new Redis(process.env.REDIS_URL);
const pdfQueue = new Queue('saas-pdf', { connection });
const s3 = new S3Client({ region: 'us-east-1' });
// Enqueue endpoint: returns job ID immediately
export async function enqueuePdfJob(tenantId, jobType, payload) {
const job = await pdfQueue.add(jobType, {
tenantId,
...payload,
}, {
attempts: 3,
backoff: { type: 'exponential', delay: 2000 },
// In BullMQ a lower number is a higher priority (1 is highest).
// Priority 0 (unset) jobs run before prioritized jobs, so give every job 1 or more
priority: payload.isPaidPlan ? 1 : 10,
});
return { jobId: job.id, status: 'queued' };
}
// Worker: generates PDF and stores in S3
const worker = new Worker('saas-pdf', async (job) => {
const { tenantId, invoiceId } = job.data;
const tenant = await Tenant.findById(tenantId);
const invoice = await Invoice.findById(invoiceId);
const html = await renderInvoiceTemplate(invoice, tenant);
let pdfBuffer: Buffer;
try {
pdfBuffer = await generatePdf(html, { 'page-size': 'A4' }, 120_000);
} catch (err) {
// 4xx (except a 429 with Retry-After) will not fix itself, so stop BullMQ's retries
if (err instanceof PdfApiError && err.status < 500 && !(err.status === 429 && err.retryAfter)) {
throw new UnrecoverableError(err.message);
}
throw err;
}
// Store in S3, isolated by tenant ID
const key = `tenants/${tenantId}/invoices/${invoiceId}.pdf`;
await s3.send(new PutObjectCommand({
Bucket: process.env.PDF_STORAGE_BUCKET,
Key: key,
Body: pdfBuffer,
ContentType: 'application/pdf',
ServerSideEncryption: 'AES256',
}));
await PdfJob.update(job.id, {
status: 'completed',
s3Key: key,
completedAt: new Date(),
});
return { s3Key: key };
}, { connection, concurrency: 5 });
worker.on('failed', (job, err) => {
console.error(`PDF job ${job?.id} failed:`, err.message);
});
Pattern 3: Batch processing (monthly bulk generation)
For generating all tenant invoices at month-end, batch processing is the right choice. The batch processing guide covers the mechanics; here is the SaaS-specific layer.
FUNBREW PDF also has a batch API (POST /api/pdf/batch, available on every plan), but it takes up to 100 items per call, does not accept a per-item filename, returns only a batch_id on submission, and its status response does not include download URLs (PDFs arrive through the pdf.generated webhook). For monthly invoices that you need to match back to tenant records, calling the single-generation API with limited concurrency is easier, so that is what this example does.
# Python: monthly invoices for all tenants (single-generation API, limited concurrency)
import asyncio
import os
from typing import List
import aiohttp
BASE_URL = 'https://pdf.funbrew.cloud'
HEADERS = {'Authorization': f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"}
async def generate_pdf(session: aiohttp.ClientSession, html: str) -> bytes:
"""Generate, then fetch data.download_url."""
async with session.post(
f'{BASE_URL}/api/pdf/generate-from-html',
headers={**HEADERS, 'Accept': 'application/json'},
json={'html': html, 'options': {'page-size': 'A4'}},
timeout=aiohttp.ClientTimeout(total=120),
) as resp:
resp.raise_for_status()
result = await resp.json()
async with session.get(
result['data']['download_url'],
headers=HEADERS,
timeout=aiohttp.ClientTimeout(total=120),
) as pdf_resp:
pdf_resp.raise_for_status()
return await pdf_resp.read()
async def generate_monthly_invoices(tenants: List[dict], year: int, month: int):
"""Generate monthly invoices for all tenants concurrently."""
# The per-minute request limit is per account (shared by all API keys), and each PDF
# costs two requests (generate + download). Keep concurrency within your plan's limit
semaphore = asyncio.Semaphore(5)
async def generate_one(session, tenant, invoice):
async with semaphore:
html = await render_invoice_html(invoice, tenant)
pdf_bytes = await generate_pdf(session, html)
# Store in S3 and record in the DB (you choose the filename)
await store_pdf(tenant['id'], f"invoice-{invoice['number']}.pdf", pdf_bytes)
async with aiohttp.ClientSession() as session:
tasks = []
for tenant in tenants:
invoices = await get_monthly_invoices(tenant['id'], year, month)
tasks += [generate_one(session, tenant, invoice) for invoice in invoices]
results = await asyncio.gather(*tasks, return_exceptions=True)
failures = [r for r in results if isinstance(r, Exception)]
if failures:
await notify_batch_failures(failures)
return results
Every generated PDF counts as one toward your monthly quota regardless of how you call the API, and once the plan's monthly limit is reached the API returns 429 (waiting does not help until next month). Check the remainder with GET /api/usage before a monthly run.
Multi-Tenant Template Management
The core of multi-tenancy is isolation. PDF generation is no exception — each tenant needs its own templates, branding, and configuration.
Tenant boundaries as seen from the PDF API
Your whole SaaS uses one FUNBREW PDF account (company), so isolating your tenants from each other is your application's job. On the API side:
- The per-minute request limit and the monthly generation limit are per account, shared by every API key and every tenant. Allocate capacity per tenant in your app (see below) so one tenant's bulk run does not starve the others.
- Any API key of the same account can download a generated PDF (a key from another account gets 403). Authorization that keeps tenant A's PDF away from tenant B lives in your own database (which invoice belongs to which tenant).
- API keys are issued in the dashboard (there is no REST API for creating or deleting keys). If you split keys per tenant or customer and give them a
client_label, the dashboard's PDF list and API logs can be filtered per customer (grouping API keys by client).
Template data structure
-- Per-tenant PDF template table
CREATE TABLE pdf_templates (
id UUID PRIMARY KEY DEFAULT gen_random_uuid(),
tenant_id UUID NOT NULL REFERENCES tenants(id),
slug VARCHAR(100) NOT NULL, -- 'invoice', 'report', 'contract'
name VARCHAR(255) NOT NULL,
html TEXT NOT NULL, -- Handlebars template
css TEXT,
is_active BOOLEAN DEFAULT true,
created_at TIMESTAMPTZ DEFAULT NOW(),
updated_at TIMESTAMPTZ DEFAULT NOW(),
UNIQUE (tenant_id, slug)
);
-- Default templates (fallback when tenant has no custom template)
CREATE TABLE default_pdf_templates (
slug VARCHAR(100) PRIMARY KEY,
html TEXT NOT NULL,
css TEXT
);
Fallback resolution
// Resolve template: tenant-specific first, then default
async function resolveTemplate(tenantId: string, slug: string): Promise<Template> {
const tenantTemplate = await db.query<Template>(
'SELECT * FROM pdf_templates WHERE tenant_id = $1 AND slug = $2 AND is_active = true',
[tenantId, slug]
);
if (tenantTemplate.rows.length > 0) {
return tenantTemplate.rows[0];
}
const defaultTemplate = await db.query<Template>(
'SELECT * FROM default_pdf_templates WHERE slug = $1',
[slug]
);
if (defaultTemplate.rows.length === 0) {
throw new Error(`Template not found: ${slug}`);
}
return defaultTemplate.rows[0];
}
// Render template with tenant brand data injected
async function renderTemplate(
tenantId: string,
slug: string,
variables: Record<string, unknown>
): Promise<string> {
const template = await resolveTemplate(tenantId, slug);
const tenant = await Tenant.findById(tenantId);
const enrichedVars = {
...variables,
brand: {
name: tenant.companyName,
logo_url: tenant.logoUrl,
primary_color: tenant.brandColor ?? '#2563EB',
address: tenant.address,
},
};
return Handlebars.compile(template.html)(enrichedVars);
}
Template management API for tenants
// Allow tenant admins to update their own templates
router.put('/templates/:slug', requireTenantAdmin, async (req, res) => {
const { html, css, name } = req.body;
const sanitizedHtml = sanitizeTemplateHtml(html);
// Validate by generating a preview PDF
try {
await generatePreviewPdf(sanitizedHtml, css);
} catch (err) {
return res.status(422).json({
error: 'Template rendering failed',
details: err.message,
});
}
await db.query(
`INSERT INTO pdf_templates (tenant_id, slug, name, html, css)
VALUES ($1, $2, $3, $4, $5)
ON CONFLICT (tenant_id, slug) DO UPDATE
SET name = EXCLUDED.name,
html = EXCLUDED.html,
css = EXCLUDED.css,
updated_at = NOW()`,
[req.tenant.id, req.params.slug, name, sanitizedHtml, css]
);
res.json({ success: true });
});
Template Engine Integration
Use a proper template engine rather than string concatenation to support loops, conditionals, and formatting in your PDF templates.
FUNBREW PDF's template API (generate-from-template) only replaces {{variable}} with an HTML-escaped value; it has no loops or conditionals. When you need loops, such as invoice line items, build the HTML with your own template engine as shown here and send it to generate-from-html.
Handlebars invoice template
<!-- templates/invoice.hbs -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<style>
body { font-family: 'Inter', sans-serif; margin: 0; }
.header { display: flex; justify-content: space-between; padding: 40px; }
.logo { height: 48px; }
.invoice-meta { text-align: right; color: #6B7280; font-size: 14px; }
table { width: 100%; border-collapse: collapse; }
th, td { padding: 12px 16px; text-align: left; border-bottom: 1px solid #E5E7EB; }
th { background: #F9FAFB; font-weight: 600; }
.total-row { font-size: 18px; font-weight: 700; }
{{#if brand.primary_color}}
.accent { color: {{brand.primary_color}}; }
.header-bar { background: {{brand.primary_color}}; height: 4px; }
{{/if}}
</style>
</head>
<body>
<div class="header-bar"></div>
<div class="header">
{{#if brand.logo_url}}
<img src="{{brand.logo_url}}" alt="{{brand.name}}" class="logo">
{{else}}
<h1 class="accent">{{brand.name}}</h1>
{{/if}}
<div class="invoice-meta">
<p><strong>Invoice:</strong> {{invoice.number}}</p>
<p><strong>Date:</strong> {{formatDate invoice.issued_at}}</p>
<p><strong>Due:</strong> {{formatDate invoice.due_at}}</p>
</div>
</div>
<div style="padding: 0 40px;">
<p><strong>Bill to: {{customer.name}}</strong></p>
<p style="color: #6B7280; font-size: 14px;">{{customer.address}}</p>
</div>
<div style="padding: 24px 40px;">
<table>
<thead>
<tr>
<th>Description</th>
<th style="text-align: right;">Qty</th>
<th style="text-align: right;">Unit price</th>
<th style="text-align: right;">Amount</th>
</tr>
</thead>
<tbody>
{{#each invoice.line_items}}
<tr>
<td>{{this.description}}</td>
<td style="text-align: right;">{{this.quantity}}</td>
<td style="text-align: right;">{{formatCurrency this.unit_price}}</td>
<td style="text-align: right;">{{formatCurrency this.amount}}</td>
</tr>
{{/each}}
</tbody>
<tfoot>
<tr><td colspan="3" style="text-align: right;">Subtotal</td><td style="text-align: right;">{{formatCurrency invoice.subtotal}}</td></tr>
<tr><td colspan="3" style="text-align: right;">Tax ({{invoice.tax_rate}}%)</td><td style="text-align: right;">{{formatCurrency invoice.tax_amount}}</td></tr>
<tr class="total-row">
<td colspan="3" style="text-align: right;" class="accent">Total due</td>
<td style="text-align: right;" class="accent">{{formatCurrency invoice.total_amount}}</td>
</tr>
</tfoot>
</table>
</div>
{{#if invoice.notes}}
<div style="padding: 24px 40px; color: #6B7280; font-size: 13px;">
<p><strong>Notes:</strong> {{invoice.notes}}</p>
</div>
{{/if}}
<div style="padding: 24px 40px; border-top: 1px solid #E5E7EB; font-size: 12px; color: #9CA3AF;">
<p>{{brand.name}} — {{brand.address}}</p>
</div>
</body>
</html>
// Register Handlebars helpers
const Handlebars = require('handlebars');
Handlebars.registerHelper('formatDate', (date) => {
return new Intl.DateTimeFormat('en-US', {
year: 'numeric', month: 'long', day: 'numeric',
}).format(new Date(date));
});
Handlebars.registerHelper('formatCurrency', (amount) => {
return new Intl.NumberFormat('en-US', {
style: 'currency', currency: 'USD',
}).format(amount);
});
For loops, conditionals, and nested data patterns in templates, see the PDF template engine guide.
Webhook Delivery
After async PDF generation, tenants need to know when their file is ready. Two patterns are common in SaaS.
Pattern A: Internal webhook (worker to app server)
// Worker notifies the app server after PDF is stored
async function notifyPdfCompleted(jobId: string, result: PdfResult) {
await fetch(`${process.env.APP_INTERNAL_URL}/webhooks/pdf-completed`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Internal-Secret': process.env.INTERNAL_WEBHOOK_SECRET,
},
body: JSON.stringify({
jobId,
tenantId: result.tenantId,
s3Key: result.s3Key,
completedAt: new Date().toISOString(),
}),
});
}
// App server receives the webhook and notifies the user
router.post('/webhooks/pdf-completed', verifyInternalSecret, async (req, res) => {
const { jobId, tenantId, s3Key } = req.body;
await PdfJob.markCompleted(jobId, s3Key);
const job = await PdfJob.findById(jobId);
await notifyUser(job.userId, {
type: 'pdf_ready',
downloadUrl: generateSignedUrl(s3Key, { expiresIn: '24h' }),
});
res.json({ ok: true });
});
Pattern B: Forwarding webhooks to tenants
For enterprise tenants that want events delivered to their own systems:
The event names here are ones your SaaS defines. The webhooks FUNBREW PDF itself sends are pdf.generated, pdf.downloaded and pdf.expired (available on every plan); there is no generation-failure event. FUNBREW's webhooks carry an X-Webhook-Signature header with the HMAC-SHA256 of the body as sha256=<hex>, so you can verify them the same way as below.
// Tenant webhook settings (event names defined by your SaaS)
interface TenantWebhookConfig {
tenantId: string;
url: string;
secret: string; // for HMAC signature verification
events: ('invoice_pdf.ready' | 'invoice_pdf.failed')[];
isActive: boolean;
}
async function forwardWebhookToTenant(
config: TenantWebhookConfig,
event: string,
payload: object
) {
const body = JSON.stringify({ event, data: payload, timestamp: Date.now() });
const signature = createHmacSignature(body, config.secret);
try {
const response = await fetch(config.url, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'X-Webhook-Signature': `sha256=${signature}`,
'X-Webhook-Event': event,
},
body,
signal: AbortSignal.timeout(10_000),
});
await WebhookDelivery.record({
tenantId: config.tenantId,
event,
statusCode: response.status,
success: response.ok,
});
} catch (err) {
await WebhookDelivery.recordFailure(config.tenantId, event, err.message);
await scheduleWebhookRetry(config, event, payload);
}
}
function createHmacSignature(body: string, secret: string): string {
return require('crypto')
.createHmac('sha256', secret)
.update(body)
.digest('hex');
}
For more webhook patterns, see the PDF API webhook integration guide.
Rate Limiting and Queue Design
Multiple tenants generating PDFs simultaneously means you need to control throughput at the application layer before hitting the external API's rate limits.
FUNBREW PDF's per-minute limit is Free 10, Pro 120, Business 300 requests (higher volumes by individual arrangement), counted per account in a 60-second window starting at the first request. Generation and download each count as one request, so one PDF costs two.
Fair resource distribution per tenant
To limit jobs per tenant, you can use the Groups feature of BullMQ Pro, the commercial version of BullMQ (Groups is documented under BullMQ Pro and uses QueuePro from @taskforcesh/bullmq-pro).
// BullMQ Pro: use the tenant ID as the group and rate-limit each tenant per minute
import { QueuePro } from '@taskforcesh/bullmq-pro';
// PDFs per minute for each plan of YOUR SaaS (allocate within FUNBREW's account limit)
const PLAN_PDFS_PER_MINUTE = {
free: 1,
starter: 3,
professional: 10,
enterprise: 30,
} as const;
const queue = new QueuePro('pdf-generation', { connection });
async function enqueueWithTenantLimit(
tenantId: string,
plan: keyof typeof PLAN_PDFS_PER_MINUTE,
jobData: object
) {
// Per-group (per-tenant) rate limit: max jobs per 60 seconds
await queue.setGroupRateLimit(tenantId, PLAN_PDFS_PER_MINUTE[plan], 60_000);
await queue.add('generate', jobData, {
group: { id: tenantId },
attempts: 3,
backoff: { type: 'exponential', delay: 2000 },
});
}
With open-source BullMQ only, you can do the same by keeping a Redis counter per tenant and pushing jobs over the limit back as delayed jobs.
Global rate limiter with Redis
import os
import time
import uuid
import redis
class GlobalRateLimiter:
"""Sliding window rate limiter backed by Redis."""
def __init__(self, redis_client, max_requests: int, window_seconds: int):
self.redis = redis_client
self.max_requests = max_requests
self.window = window_seconds
def acquire(self, timeout_seconds: float = 5.0) -> bool:
"""Try to acquire a request slot. Returns False on timeout."""
key = 'global:pdf_api:rate_limit'
deadline = time.time() + timeout_seconds
while time.time() < deadline:
now_ms = int(time.time() * 1000)
window_start = now_ms - self.window * 1000
member = f'{now_ms}-{uuid.uuid4()}' # avoid collisions within the same millisecond
pipe = self.redis.pipeline()
pipe.zremrangebyscore(key, '-inf', window_start)
pipe.zadd(key, {member: now_ms})
pipe.zcard(key)
pipe.expire(key, self.window + 1)
_, _, count, _ = pipe.execute()
if count <= self.max_requests:
return True
# Undo a slot we did not get; otherwise rejected requests keep eating the window
self.redis.zrem(key, member)
time.sleep(0.1)
return False
# Operate at 80% of the Pro plan's 120 requests per minute.
# Generate and download are one request each, so call acquire() before both
limiter = GlobalRateLimiter(
redis_client=redis.Redis.from_url(os.environ['REDIS_URL']),
max_requests=96,
window_seconds=60,
)
async def generate_pdf_with_rate_limit(html: str, tenant_id: str):
if not limiter.acquire(timeout_seconds=10):
raise TooManyRequestsError('PDF generation rate limit exceeded')
return await call_pdf_api(html)
Queue depth monitoring
async function getPdfQueueHealth() {
const queue = new Queue('pdf-generation', { connection });
const [waiting, active, failed, delayed] = await Promise.all([
queue.getWaitingCount(),
queue.getActiveCount(),
queue.getFailedCount(),
queue.getDelayedCount(),
]);
return {
waiting,
active,
failed,
delayed,
isHealthy: waiting < 500 && failed < 50,
};
}
White-Labeling: Dynamic Brand Injection
B2B SaaS customers expect PDFs to carry their own brand, not yours.
Brand configuration structure
interface TenantBrandConfig {
tenantId: string;
companyName: string;
logoUrl: string | null;
primaryColor: string; // '#2563EB'
secondaryColor: string;
fontFamily: string; // 'Inter', 'Roboto', etc.
footerText: string;
watermark: {
enabled: boolean;
text: string; // 'CONFIDENTIAL', 'DRAFT', etc.
opacity: number; // 0.1 to 0.3
};
}
Dynamic brand CSS generation
function generateBrandCss(brand: TenantBrandConfig): string {
return `
:root {
--color-primary: ${brand.primaryColor};
--color-secondary: ${brand.secondaryColor};
--font-family: '${brand.fontFamily}', sans-serif;
}
body { font-family: var(--font-family); }
.accent, .total-label { color: var(--color-primary); }
.header-bar {
background: var(--color-primary);
height: 4px;
}
${brand.watermark.enabled ? `
body::after {
content: '${brand.watermark.text}';
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(-45deg);
font-size: 72px;
font-weight: 900;
opacity: ${brand.watermark.opacity};
color: var(--color-primary);
pointer-events: none;
z-index: 1000;
}` : ''}
`;
}
// Render PDF with tenant brand injected
async function renderBrandedPdf(
templateSlug: string,
variables: object,
tenantId: string
): Promise<Buffer> {
const tenant = await Tenant.findById(tenantId);
const brand = tenant.brandConfig;
const template = await resolveTemplate(tenantId, templateSlug);
const brandCss = generateBrandCss(brand);
const html = Handlebars.compile(template.html)({
...variables,
brand,
__brandCss: brandCss, // inject in the template as <style>{{{__brandCss}}}</style> ({{{ }}} does not escape)
});
return generatePdf(html, { 'page-size': 'A4' });
}
Embedding logos as Base64
Passing a logo as an external URL assumes the PDF renderer can fetch it (a public URL that needs no authentication). For logos on an internal network or behind signed URLs, embedding them as Base64 in the HTML removes the dependency on that fetch.
async function embedLogoAsBase64(logoUrl: string | null): Promise<string> {
if (!logoUrl) return '';
try {
const response = await fetch(logoUrl);
if (!response.ok) return '';
const buffer = Buffer.from(await response.arrayBuffer());
const contentType = response.headers.get('content-type') ?? 'image/png';
return `data:${contentType};base64,${buffer.toString('base64')}`;
} catch {
return ''; // fail gracefully; show no logo
}
}
// Replace the logo in the brand data passed to the template with a data URL
const brand = {
...tenant.brandConfig,
logoUrl: await embedLogoAsBase64(tenant.brandConfig.logoUrl),
};
Cost Optimization: Caching, Batching, and Diffing
With multiple tenants generating PDFs continuously, API costs compound quickly. FUNBREW PDF is priced as monthly plans, each with a monthly generation limit (no per-PDF overage billing; at the limit the API returns 429 until next month). Cutting unnecessary generations directly delays the point where you need a bigger plan.
Strategy 1: Content-hash caching
Cache PDFs by hashing the HTML and options. Identical inputs produce identical PDFs — no need to regenerate.
import crypto from 'crypto';
import { S3Client, GetObjectCommand, PutObjectCommand } from '@aws-sdk/client-s3';
class PdfCacheService {
constructor(
private readonly s3: S3Client,
private readonly bucket: string,
private readonly redis: RedisClient
) {}
private getCacheKey(html: string, options: object): string {
const content = html + JSON.stringify(options);
return crypto.createHash('sha256').update(content).digest('hex');
}
async getOrGenerate(
html: string,
options: Record<string, string | number> = { 'page-size': 'A4' },
ttlSeconds = 86400
): Promise<Buffer> {
const hash = this.getCacheKey(html, options);
const redisKey = `pdf:cache:${hash}`;
const s3Key = `pdf-cache/${hash}.pdf`;
// L1: check Redis for cache existence
const cached = await this.redis.get(redisKey);
if (cached) {
// L2: retrieve PDF from S3
const s3Response = await this.s3.send(new GetObjectCommand({
Bucket: this.bucket,
Key: s3Key,
}));
return streamToBuffer(s3Response.Body);
}
// Cache miss: generate PDF (generatePdf helper from above)
const pdfBuffer = await generatePdf(html, options);
await this.s3.send(new PutObjectCommand({
Bucket: this.bucket, Key: s3Key,
Body: pdfBuffer, ContentType: 'application/pdf',
}));
await this.redis.setex(redisKey, ttlSeconds, '1');
return pdfBuffer;
}
}
Strategy 2: Diff check to avoid unnecessary regeneration
async function generateIfChanged(
tenantId: string,
entityType: string,
entityId: string,
data: object
): Promise<{ pdfBuffer: Buffer; regenerated: boolean }> {
const dataHash = crypto
.createHash('sha256')
.update(JSON.stringify(data))
.digest('hex');
const existing = await PdfRecord.findOne({ tenantId, entityType, entityId });
if (existing && existing.dataHash === dataHash) {
const pdfBuffer = await downloadFromS3(existing.s3Key);
return { pdfBuffer, regenerated: false };
}
const html = await renderTemplate(tenantId, entityType, data);
const pdfBuffer = await generatePdf(html, { 'page-size': 'A4' });
const s3Key = `tenants/${tenantId}/${entityType}/${entityId}.pdf`;
await uploadToS3(s3Key, pdfBuffer);
await PdfRecord.upsert({ tenantId, entityType, entityId, dataHash, s3Key });
return { pdfBuffer, regenerated: true };
}
Strategy 3: Per-tenant usage tracking
async function trackPdfGeneration(
tenantId: string,
generationType: 'sync' | 'async' | 'batch',
count = 1
) {
const month = new Date().toISOString().slice(0, 7);
await db.query(
`INSERT INTO pdf_usage_metrics (tenant_id, month, generation_type, count)
VALUES ($1, $2, $3, $4)
ON CONFLICT (tenant_id, month, generation_type)
DO UPDATE SET count = pdf_usage_metrics.count + EXCLUDED.count`,
[tenantId, month, generationType, count]
);
const totalThisMonth = await getTotalPdfCountForTenant(tenantId, month);
const planLimit = await getPlanPdfLimit(tenantId);
if (totalThisMonth > planLimit * 0.8) {
await notifyTenantApproachingLimit(tenantId, totalThisMonth, planLimit);
}
}
The limit here is the one your SaaS imposes on its tenants. FUNBREW PDF's account-wide usage is available from GET /api/usage and the X-Monthly-Limit / X-Monthly-Used headers on generation responses.
Cost reduction estimates
The hit rates are assumptions. Replace them with values measured on your own data.
| Optimization | 10,000/month | 100,000/month |
|---|---|---|
| Caching (assumed 30% hit rate) | -3,000 PDFs | -30,000 PDFs |
| Diff check (assumed 20% unchanged) | -2,000 PDFs | -20,000 PDFs |
| Combined (if the two do not overlap) | -5,000 PDFs | -50,000 PDFs |
Sending PDFs through the batch API only reduces the number of HTTP calls; the monthly generation count stays one per PDF.
Complete Example: Multi-Tenant Invoice PDF Service
Putting it all together: a production-ready invoice PDF service for a multi-tenant SaaS.
System diagram
┌─────────────────────────────────────────┐
│ SaaS frontend │
│ "Download invoice" button │
└───────────────────┬─────────────────────┘
│ POST /invoices/:id/pdf
┌───────────────────▼─────────────────────┐
│ SaaS backend │
│ - Tenant auth and authorization │
│ - Template resolution (custom/default) │
│ - Brand CSS generation │
│ - Cache check │
└─────┬─────────────────────┬─────────────┘
│ cache miss │ cache hit
│ │ → return from S3
┌─────▼─────────────────────│─────────────┐
│ FUNBREW PDF API │ │
│ POST /api/pdf/generate-from-html │
│ → GET data.download_url │ │
└─────┬─────────────────────│─────────────┘
│ │
┌─────▼─────────────────────│─────────────┐
│ S3 (PDF storage) │ │
│ tenants/{id}/invoices/ ◄────────────┘
└─────────────────────────────────────────┘
Full service implementation
// services/invoice-pdf.service.ts
import pLimit from 'p-limit';
import { Tenant, Invoice } from '../models';
import { PdfCacheService } from './pdf-cache.service';
import { renderTemplate, generateBrandCss } from './template.service';
import { generatePdf } from '../lib/funbrew-pdf';
export class InvoicePdfService {
constructor(private readonly cache: PdfCacheService) {}
async generateForTenant(
tenantId: string,
invoiceId: string
): Promise<{ buffer: Buffer; filename: string }> {
const [tenant, invoice] = await Promise.all([
Tenant.findById(tenantId),
Invoice.findByTenantAndId(tenantId, invoiceId),
]);
if (!invoice) throw new NotFoundError(`Invoice ${invoiceId} not found`);
const brandCss = generateBrandCss(tenant.brandConfig);
const html = await renderTemplate(tenantId, 'invoice', {
invoice,
customer: invoice.customer,
brand: tenant.brandConfig,
__brandCss: brandCss,
});
// Cache for 1 hour (invoices may be updated before being finalized)
const pdfBuffer = await this.cache.getOrGenerate(html, { 'page-size': 'A4' }, 3600);
await trackPdfGeneration(tenantId, 'sync');
return {
buffer: pdfBuffer,
filename: `invoice-${invoice.number}.pdf`,
};
}
async batchGenerateMonthly(year: number, month: number): Promise<BatchResult> {
const tenants = await Tenant.findAllActive();
const results: { tenantId: string; count: number; failed: number }[] = [];
// Concurrent PDF generations (the per-minute limit is per account and a PDF costs 2 requests)
const limit = pLimit(5);
for (const tenant of tenants) {
const invoices = await Invoice.findMonthly(tenant.id, year, month);
if (!invoices.length) continue;
const settled = await Promise.allSettled(
invoices.map((invoice) => limit(async () => {
const html = await renderTemplate(tenant.id, 'invoice', {
invoice,
customer: invoice.customer,
brand: tenant.brandConfig,
__brandCss: generateBrandCss(tenant.brandConfig),
});
const pdfBuffer = await generatePdf(html, { 'page-size': 'A4' });
// Store in S3 under a per-tenant path
await uploadToS3(`tenants/${tenant.id}/invoices/invoice-${invoice.number}.pdf`, pdfBuffer);
}))
);
const failed = settled.filter((r) => r.status === 'rejected').length;
await trackPdfGeneration(tenant.id, 'batch', invoices.length - failed);
results.push({ tenantId: tenant.id, count: invoices.length, failed });
}
return { tenants: results };
}
}
Express route
// routes/invoices.ts
router.get('/:id/pdf', requireAuth, async (req, res) => {
try {
const { buffer, filename } = await invoicePdfService.generateForTenant(
req.tenant.id,
req.params.id
);
res.setHeader('Content-Type', 'application/pdf');
res.setHeader('Content-Disposition', `attachment; filename="${filename}"`);
res.setHeader('Cache-Control', 'private, max-age=3600');
res.send(buffer);
} catch (err) {
if (err instanceof NotFoundError) {
return res.status(404).json({ error: err.message });
}
console.error('PDF generation error:', err);
res.status(500).json({ error: 'PDF generation failed. Please try again.' });
}
});
// Internal admin endpoint for monthly batch
router.post('/batch/monthly', requireAdmin, async (req, res) => {
const { year, month } = req.body;
const jobId = await batchJobQueue.enqueue('monthly-invoices', { year, month });
res.json({ jobId, status: 'queued' });
});
Summary: Design Principles for SaaS PDF Integration
| Requirement | Recommended approach |
|---|---|
| User downloads file now | Synchronous generation (when the wait is acceptable) |
| Large batch or monthly run | Async queue + webhook notification |
| Per-tenant design | Template table with default fallback |
| Brand customization | CSS variables + Base64 logo embedding |
| Cost reduction | Content-hash cache + diff check |
| Rate control | Redis sliding window limiter |
| Tenant notification | HMAC-signed webhook forwarding |
You do not need to implement everything from day one. Start with synchronous generation and basic tenant isolation, then add queuing, caching, and white-labeling as your volume and customer requirements grow.
Deeper coverage of individual components:
- Template design: PDF template engine guide
- Webhook delivery: PDF API webhook integration guide
- Batch processing: PDF batch processing guide
- Production stability: PDF API production checklist
- Security: PDF API security guide
Try the API in the playground, review the endpoint specs in the docs, and see real SaaS use cases in the use cases section.