PDF Generation: API vs Library — How to Choose in 2026
Every web application eventually needs to generate PDFs. Invoices, reports, contracts, certificates — the list goes on. When that moment arrives, you face a fundamental choice:
- Library approach — install a PDF generation library on your own server
- API approach — send HTTP requests to a cloud PDF generation service
Both approaches have genuine strengths. The right choice depends on your project's specific requirements. This guide breaks down each approach in detail so you can make a confident decision.
The Library Approach
PDF generation libraries have been around for decades. They run on your infrastructure and give you direct control over the rendering process.
Popular PDF Libraries
| Library | Language | Approach |
|---|---|---|
| Puppeteer | Node.js | Controls headless Chrome to convert HTML to PDF |
| wkhtmltopdf | CLI | QtWebKit-based conversion tool (GitHub repository archived in January 2023) |
| pdfkit | Node.js | Programmatic PDF construction |
| jsPDF | JavaScript | Browser/Node.js PDF generation |
| TCPDF | PHP | Long-standing PHP PDF library (now maintenance-only; succeeded by tc-lib-pdf) |
| ReportLab | Python | Python PDF generation (open-source toolkit is BSD-licensed; ReportLab PLUS is a separate commercial product) |
| Prawn | Ruby | Ruby PDF generation |
Pros of Libraries
Full control over the process
Everything runs on your servers. You decide which fonts are installed, how rendering is configured, and what resources are allocated. For edge cases that require low-level PDF manipulation, a library gives you direct access.
No external dependencies
No network calls means no reliance on third-party uptime. Your PDF generation works offline and is unaffected by external service outages.
Predictable costs at low volume
There are no per-PDF charges. If you generate a handful of PDFs per month, running a library on an existing server costs essentially nothing extra.
Cons of Libraries
Setup and maintenance overhead
Taking Puppeteer as an example, you need to handle Chrome installation, font provisioning, memory management, zombie process cleanup, and Docker configuration:
// Puppeteer invoice generation
const puppeteer = require('puppeteer');
async function generateInvoice(html) {
// Launches a Chrome process
const browser = await puppeteer.launch({
headless: true,
args: [
'--no-sandbox', // Discouraged by Puppeteer; only for content you trust
'--disable-setuid-sandbox',
'--disable-dev-shm-usage', // For containers with a small /dev/shm
'--font-render-hinting=none',
],
});
try {
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' });
const pdf = await page.pdf({
format: 'A4',
margin: { top: '20mm', bottom: '20mm', left: '15mm', right: '15mm' },
printBackground: true,
});
return pdf;
} finally {
await browser.close(); // Must clean up or memory leaks
}
}
Font and rendering issues
CJK (Chinese, Japanese, Korean) text is a common pain point. Linux servers often lack CJK fonts, resulting in "tofu" characters (empty rectangles). The Dockerfile example in Puppeteer's own troubleshooting guide adds font packages to support Chinese, Japanese and other scripts. Those fonts make the image larger:
# Font provisioning in Docker
# (fonts-noto-cjk-extra alone is about 214MB installed on Debian bookworm)
FROM node:22-slim
RUN apt-get update && apt-get install -y \
fonts-noto-cjk \
fonts-noto-cjk-extra \
&& rm -rf /var/lib/apt/lists/*
Even with fonts installed, differences between environments (installed fonts, Chrome versions) can change the output, so check PDFs from the environment you deploy to.
Scaling is your problem
Headless Chrome runs a browser (or page) per request, so memory grows with the number of concurrent requests. How much depends heavily on the page, so you need to measure it to size your servers. You must also build your own queuing, pool management, and autoscaling infrastructure. This is solvable, but it is engineering effort that does not directly add product value.
The API Approach
A PDF generation API accepts HTML (or a template) via HTTP and gives you a PDF back (some services return the PDF bytes directly; others, like FUNBREW PDF, return a download URL in JSON). The rendering infrastructure is fully managed by the API provider.
Pros of APIs
Near-zero setup time
Get an API key, send an HTTP request, receive a PDF. You can go from zero to working PDF generation in minutes. With FUNBREW PDF, the generation call returns JSON with data.download_url; fetching that URL with the same API key gives you the PDF.
# 1. Generate (FUNBREW PDF; margins are numbers in mm, 0 to 50)
curl -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"html": "<h1>Invoice</h1><p>Total: $1,000.00</p>",
"options": {
"page-size": "A4",
"margin-top": 20,
"margin-bottom": 20
}
}'
# -> {"success":true,"data":{"filename":"...","download_url":"https://pdf.funbrew.cloud/api/pdf/download/...", ...}}
# 2. Download (use download_url as returned)
curl -H "Authorization: Bearer YOUR_API_KEY" \
-o invoice.pdf "<value of data.download_url>"
No rendering environment to maintain
The browser engine and fonts live on the provider's servers, so your local machine or server OS does not change the output. FUNBREW PDF lets you choose the fast engine (wkhtmltopdf; CSS2.1 plus partial CSS3) or the quality engine (Gotenberg/Chromium; CSS3, Flexbox, Grid; Pro plan or above). Japanese fonts are provided on the server side, but check the actual output for the characters you use.
No scaling infrastructure of your own
The provider runs the infrastructure, so you do not manage Chrome processes, memory or queues yourself. How much you can generate is set by your plan, though. With FUNBREW PDF, the monthly limit ranges from 30 PDFs (Free) to 10,000 (Business), and the per-minute limit from 10 requests (Free) to 300 (Business). For higher volume or a dedicated environment, contact us.
Language-agnostic
A REST API works from any programming language. Node.js, Python, PHP, Ruby, Go — your entire team uses the same PDF generation endpoint. This is especially valuable for organizations running multiple services in different languages. Check the quickstart guide for setup instructions in each language.
Cons of APIs
Per-PDF costs
API usage incurs charges. However, when you factor in the server resources and engineering time required by the library approach, the total cost of ownership often favors APIs — especially at scale. See the pricing comparison for details.
Network dependency
HTTP requests are required, so fully offline environments cannot use an API. Network latency is added to each request. Response time depends on your HTML and the engine, so measure with your real templates before using it synchronously.
Data privacy considerations
Your HTML content is sent to an external server. For highly sensitive data, verify that the API provider's data handling meets your compliance requirements.
Comparison Table
| Criteria | Library | API |
|---|---|---|
| Setup time | Hours to days | Minutes |
| Rendering environment | Self-provisioned (environment-dependent) | Provided by the API |
| CJK / font support | Manual font provisioning | Varies by provider (check the output) |
| Scaling | Self-managed | Handled by the provider within plan limits |
| Cost model | Server costs | Per-PDF pricing |
| Maintenance burden | High (OS, library updates) | Low |
| Offline support | Yes | No |
| Language support | Library-specific | Any language |
Decision Framework
Choose a library when:
- Simple PDFs: Text and tables only, minimal styling
- No CJK required: English-only documents
- Low volume: A few dozen PDFs per month
- Strict data locality: Regulations prohibit sending content to external services
- Existing infrastructure: You already have a stable Puppeteer/wkhtmltopdf setup
Choose an API when:
- Complex layouts: CSS Grid, Flexbox, background images, modern CSS features (with FUNBREW PDF, the
qualityengine on Pro or above) - CJK text: Japanese, Chinese, or Korean content
- Predictable volume: Your monthly PDF count fits within a plan limit
- Cross-language teams: Multiple services in different languages need PDF generation
- Speed to market: You need PDF output working today, not next sprint
Migration Path: Library to API
If you already have a Puppeteer-based setup, migration is straightforward. Your HTML templates stay exactly the same — you only replace the "HTML to PDF" conversion step.
// Before: Puppeteer (you launch and clean up the browser yourself)
const puppeteer = require('puppeteer');
const browser = await puppeteer.launch({ /* config... */ });
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' });
const pdf = await page.pdf({ format: 'A4', printBackground: true });
await browser.close();
// After: API calls (generate, then download)
const headers = { Authorization: 'Bearer YOUR_API_KEY' };
const res = await fetch('https://pdf.funbrew.cloud/api/pdf/generate-from-html', {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({ html, options: { 'page-size': 'A4' } }),
});
const { data } = await res.json();
const apiPdf = await (await fetch(data.download_url, { headers })).arrayBuffer();
For a detailed step-by-step walkthrough, see the Puppeteer to PDF API migration guide.
Code Comparison: Same Invoice, Both Approaches
Let's generate the same invoice using both approaches to see the practical difference.
Puppeteer (Library)
const puppeteer = require('puppeteer');
async function generateInvoicePdf(invoiceData) {
const html = buildInvoiceHtml(invoiceData);
const browser = await puppeteer.launch({
headless: true,
args: ['--no-sandbox', '--disable-setuid-sandbox'],
});
const page = await browser.newPage();
await page.setContent(html, { waitUntil: 'networkidle0' });
const pdfBuffer = await page.pdf({
format: 'A4',
margin: { top: '20mm', right: '15mm', bottom: '20mm', left: '15mm' },
printBackground: true,
displayHeaderFooter: true,
headerTemplate: '<span></span>',
footerTemplate:
'<div style="font-size:8px;text-align:center;width:100%;">Page <span class="pageNumber"></span></div>',
});
await browser.close();
return pdfBuffer;
}
FUNBREW PDF API
async function generateInvoicePdf(invoiceData) {
const html = buildInvoiceHtml(invoiceData); // Same HTML template
const headers = { Authorization: `Bearer ${process.env.FUNBREW_API_KEY}` };
// 1. Generate (margins are numbers in mm)
const response = await fetch('https://pdf.funbrew.cloud/api/pdf/generate-from-html', {
method: 'POST',
headers: { ...headers, 'Content-Type': 'application/json' },
body: JSON.stringify({
html,
options: {
'page-size': 'A4',
'margin-top': 20,
'margin-right': 15,
'margin-bottom': 20,
'margin-left': 15,
},
}),
});
if (!response.ok) {
throw new Error(`PDF generation failed: ${response.status}`);
}
const { data } = await response.json();
// 2. Download (needs the same API key)
const pdfResponse = await fetch(data.download_url, { headers });
return await pdfResponse.arrayBuffer();
}
The buildInvoiceHtml() function is identical in both cases. You can reuse all your existing HTML/CSS templates. Note that FUNBREW PDF's generation API has no equivalent of Puppeteer's displayHeaderFooter / footerTemplate; if you need page numbers, add them to the generated PDF with the separate POST /api/pdf/page-numbers API. Try it yourself in the Playground to see the output.
Python: ReportLab vs API
# ReportLab — build PDF programmatically with coordinates
from reportlab.lib.pagesizes import A4
from reportlab.pdfgen import canvas
def generate_invoice(data, output_path):
c = canvas.Canvas(output_path, pagesize=A4)
c.setFont("Helvetica-Bold", 20)
c.drawString(50, 780, "INVOICE")
c.setFont("Helvetica", 12)
c.drawString(50, 750, f"Invoice #: {data['number']}")
c.drawString(50, 730, f"Date: {data['date']}")
# ... manually position every element with coordinates
c.save()
# FUNBREW PDF API — use HTML templates
import requests
def generate_invoice(data):
html = render_template("invoice.html", data=data)
headers = {"Authorization": f"Bearer {API_KEY}"}
response = requests.post(
"https://pdf.funbrew.cloud/api/pdf/generate-from-html",
headers=headers,
json={"html": html, "options": {"page-size": "A4"}},
)
response.raise_for_status()
download_url = response.json()["data"]["download_url"]
pdf = requests.get(download_url, headers=headers)
pdf.raise_for_status()
return pdf.content
ReportLab uses coordinate-based positioning (the origin is the bottom-left of the page), meaning every layout change requires recalculating positions manually. With an HTML/CSS-based API, design changes are just CSS edits. For CSS tips specific to PDF output, see HTML to PDF CSS techniques.
Summary
Neither approach is universally better. The right choice depends on your context:
- Small scale, English-only, existing setup — keep your library
- CJK support, scalability, development speed — an API is the stronger choice
If you are starting a new project, consider beginning with an API to ship quickly. You can always move to a self-hosted library later if your requirements demand it.
FUNBREW PDF offers a free tier (up to 30 PDFs per month) to get started. Try the Playground to test your HTML templates interactively, or follow the complete HTML to PDF guide for a comprehensive walkthrough.
Related Articles
- HTML to PDF API Comparison 2026 — comparing API providers against each other
- Puppeteer to PDF API Migration Guide — step-by-step migration
- HTML to PDF Complete Guide — comprehensive overview
- PDF API Production Guide — best practices for production use