PDF Merge, Split, Compress & Watermark: API Guide
Generating a PDF is rarely the end of the story. You often need to combine multiple PDFs into one, extract specific pages, reduce file size for email, or stamp a "DRAFT" watermark — all without manual intervention. This is PDF post-processing, and automating it well separates a basic implementation from a production-grade document workflow.
This guide covers six core PDF manipulation scenarios — merge, split, compress, watermark, page numbers, and headers/footers — comparing three approaches: generating the PDF you want in the first place, FUNBREW PDF's post-processing APIs, and PDF libraries.
For the basics of generating PDFs from HTML, see our HTML to PDF Complete Guide. For invoice automation, see Automate Invoice PDFs with API.
PDF Manipulation Overview
PDF post-processing needs fall into a few clear categories:
PDF Post-Processing
├── Structure
│ ├── Merge (combine multiple PDFs into one)
│ └── Split (take some pages out of one PDF)
├── Optimization
│ └── Compress (reduce file size)
├── Content Addition
│ ├── Watermarks
│ ├── Page numbers
│ └── Headers / footers
└── Security
├── Password protection
└── Permission control
There are two primary approaches: library-based (pypdf, pdf-lib, Ghostscript) and API-based (FUNBREW PDF). Libraries give fine-grained control but require managing dependencies, memory, and language-specific implementations. APIs need nothing installed on your server and work the same way from any language over HTTP.
FUNBREW PDF provides HTML-to-PDF generation plus post-processing APIs for merging (/api/pdf/merge), splitting (/api/pdf/split), compression (/api/pdf/compress), and page numbers (/api/pdf/page-numbers), and a watermark option at generation time. The post-processing APIs are SaaS edition only and each requires a plan that includes that feature (otherwise you get a 403). Password protection can be set at generation time with password (when generating from HTML, Markdown, or a template; the PDF then requires that password to open). There is no permission control (such as disabling printing). Try generation in the playground.
Calling the API
The generation API returns JSON with filename, download_url, and more — not the PDF bytes. You fetch the PDF from download_url (API key required). The Python examples below use these two helpers.
import requests
API_KEY = "YOUR_API_KEY"
BASE_URL = "https://pdf.funbrew.cloud"
HEADERS = {"Authorization": f"Bearer {API_KEY}"}
def generate_pdf(html: str, **extra) -> dict:
"""Generate a PDF from HTML and return the response data (filename, download_url, ...)."""
response = requests.post(
f"{BASE_URL}/api/pdf/generate-from-html",
headers=HEADERS,
json={"html": html, "options": {"page-size": "A4"}, **extra},
timeout=60,
)
response.raise_for_status()
return response.json()["data"]
def download_pdf(data: dict, path: str) -> None:
"""Fetch the PDF bytes from download_url and save them."""
response = requests.get(data["download_url"], headers=HEADERS, timeout=60)
response.raise_for_status()
with open(path, "wb") as f:
f.write(response.content)
1. PDF Merging
Use Cases
- Combine invoice + terms of service + payment confirmation into a single PDF
- Merge separately generated monthly report chapters for distribution
- Bundle application document sets (application form, consent form, instructions)
Design "one PDF from the start" with HTML
Rather than generating separate PDFs and merging them afterward, design your HTML to produce the combined document in a single request using CSS page-break-before (the current property name is break-before).
<!DOCTYPE html>
<html>
<head>
<style>
.page { page-break-before: always; }
</style>
</head>
<body>
<!-- Invoice (page 1) -->
<div class="invoice-section">
<h1>Invoice</h1>
<p>Invoice #: INV-2026-001</p>
<!-- ... -->
</div>
<!-- Terms of Service (starts on new page) -->
<div class="page terms-section">
<h1>Terms of Service</h1>
<p>Article 1...</p>
</div>
</body>
</html>
# 1. Generate (the response is JSON; data.download_url points to the PDF)
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": "<html>...(HTML above)...</html>",
"options": { "page-size": "A4" },
"filename": "combined-document.pdf"
}'
# 2. Download (use the file name returned in data.filename)
curl -H "Authorization: Bearer YOUR_API_KEY" \
https://pdf.funbrew.cloud/api/pdf/download/RETURNED_FILENAME.pdf \
-o combined-document.pdf
Python implementation
from html import escape
# generate_pdf / download_pdf are defined in "Calling the API"
invoice_html = """
<div class="invoice">
<h1>Invoice</h1>
<table>
<tr><th>Item</th><th>Amount</th></tr>
<tr><td>API usage</td><td>$500</td></tr>
</table>
</div>
"""
terms_html = """
<div style="page-break-before: always;">
<h1>Terms of Service</h1>
<p>Article 1 (Application of the Terms)...</p>
</div>
"""
combined_html = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {{ font-family: sans-serif; margin: 40px; }}
h1 {{ color: #333; }}
table {{ width: 100%; border-collapse: collapse; }}
th, td {{ border: 1px solid #ccc; padding: 8px; }}
</style>
</head>
<body>
<p>To: {escape("Sample Corp")}</p>
{invoice_html}
{terms_html}
</body>
</html>"""
data = generate_pdf(combined_html)
download_pdf(data, "invoice-with-terms.pdf")
print("PDF created: invoice-with-terms.pdf")
Node.js implementation
const fs = require("fs");
const API_KEY = process.env.PDF_API_KEY;
const BASE_URL = "https://pdf.funbrew.cloud";
async function combineSections(sections) {
// Join section HTML (page-break-before on every section except the first)
const combinedHtml = sections
.map((section, index) => {
const style = index > 0 ? 'style="page-break-before: always;"' : "";
return `<div ${style}>${section.html}</div>`;
})
.join("\n");
const fullHtml = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body { font-family: sans-serif; margin: 40px; }
</style>
</head>
<body>${combinedHtml}</body>
</html>`;
// 1. Generate (returns JSON)
const genResponse = await fetch(`${BASE_URL}/api/pdf/generate-from-html`, {
method: "POST",
headers: {
Authorization: `Bearer ${API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ html: fullHtml, options: { "page-size": "A4" } }),
});
if (!genResponse.ok) throw new Error(`Generation failed: ${genResponse.status}`);
const { data } = await genResponse.json();
// 2. Fetch the PDF bytes from download_url
const pdfResponse = await fetch(data.download_url, {
headers: { Authorization: `Bearer ${API_KEY}` },
});
if (!pdfResponse.ok) throw new Error(`Download failed: ${pdfResponse.status}`);
return Buffer.from(await pdfResponse.arrayBuffer());
}
// Usage
const sections = [
{ html: "<h1>Invoice</h1><p>Amount: $500</p>" },
{ html: "<h1>Terms of Service</h1><p>Article 1...</p>" },
{ html: "<h1>Payment Confirmed</h1><p>Thank you.</p>" },
];
combineSections(sections).then((pdfBuffer) => {
fs.writeFileSync("combined.pdf", pdfBuffer);
console.log("PDF created: combined.pdf");
});
Merging PDFs you already generated (/api/pdf/merge)
To combine PDFs that were generated separately, use the merge API. Pass 2 to 50 filenames returned by the generation API, in the order you want them merged (files uploaded with tus can be added via upload_ids). To send PDF files from your machine directly, use the multipart /api/pdf/merge-upload (files[], up to 50 MB per file). Merging requires a plan with the merge feature (every plan, including Free).
curl -X POST https://pdf.funbrew.cloud/api/pdf/merge \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"filenames": ["INVOICE_FILENAME.pdf", "TERMS_FILENAME.pdf"],
"expiration_hours": 24
}'
Like the generation API, the response is JSON with data.filename, data.download_url, data.file_size, and data.expires_at.
2. PDF Splitting
Use Cases
- Extract a specific month's pages from a consolidated annual report
- Separate a bulk-generated application set into individual PDFs
- Deliver large PDFs in page-range segments for download
Generate one file per record from the start
Instead of splitting afterward, generate individual PDFs directly — one per record.
from html import escape
# generate_pdf / download_pdf are defined in "Calling the API"
def invoice_template(data: dict) -> str:
return f"""<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="font-family: sans-serif; margin: 40px;">
<h1>Invoice</h1>
<p>To: {escape(data['customer_name'])}</p>
<p>Invoice #: {escape(data['invoice_no'])}</p>
<p>Amount: ${data['amount']:,.2f}</p>
</body>
</html>"""
customers = [
{"customer_name": "Acme Corp", "invoice_no": "INV-001", "amount": 5000.00},
{"customer_name": "Globex Inc", "invoice_no": "INV-002", "amount": 8000.00},
{"customer_name": "Initech LLC", "invoice_no": "INV-003", "amount": 3000.00},
]
# Sequential generation (see pdf-api-batch-processing for parallel patterns)
for customer in customers:
data = generate_pdf(
invoice_template(customer),
filename=f"invoice_{customer['invoice_no']}.pdf",
)
path = f"invoice_{customer['invoice_no']}.pdf"
download_pdf(data, path)
print(f"Generated: {path}")
Each plan has a per-minute request limit (Free: 10 per minute), and downloading a PDF also counts as a request. For large-scale bulk generation, see the Batch Processing Guide (the batch API is available on every plan, including Free).
Extracting pages from an existing PDF (/api/pdf/split)
To take some pages out of an existing PDF, use the split API. Set pages to comma-separated page numbers and ranges such as "1-3,5", and you get back one PDF containing those pages in that order (for one file per page, call it once per page). Pages outside the document return a 422. A plan with the split feature is required.
# generate_pdf / download_pdf / HEADERS / BASE_URL are defined in "Calling the API"
def split_pdf(filename: str, pages: str, path: str) -> None:
response = requests.post(
f"{BASE_URL}/api/pdf/split",
headers=HEADERS,
json={"filename": filename, "pages": pages},
timeout=60,
)
response.raise_for_status()
data = response.json()["data"] # filename, download_url, file_size, pages_extracted, expires_at
download_pdf(data, path)
# Example: extract April (pages 10-14) from an annual report
split_pdf("ANNUAL_REPORT_FILENAME.pdf", "10-14", "report-april.pdf")
3. PDF Compression
Common reasons PDFs get large
| Cause | Solution |
|---|---|
| High-resolution embedded images | Pre-compress and resize images |
| Many web fonts and weights loaded | Load only the fonts and weights you use |
HTML-level optimization
Optimizing the HTML you pass to FUNBREW PDF API keeps the output PDF smaller.
<!DOCTYPE html>
<html>
<head>
<style>
/* Load only the weights you use (display=swap controls rendering while loading; it does not reduce size) */
@import url('https://fonts.googleapis.com/css2?family=Inter:wght@400;700&display=swap');
body {
font-family: 'Inter', sans-serif;
background: white;
color: black;
}
</style>
</head>
<body>
<!-- Pre-compress images before embedding -->
<!-- BAD: <img src="original-4k-photo.jpg"> -->
<!-- GOOD: <img src="compressed-800px.jpg" width="400"> -->
<img src="logo-compressed.png" width="200" height="60" alt="Logo">
</body>
</html>
Where the characters are known in advance (headings, for example), the Google Fonts text= parameter returns a font file containing only those characters.
Image pre-compression (Python)
from PIL import Image
import io
import base64
def compress_image_to_base64(
image_path: str,
max_width: int = 800,
quality: int = 85
) -> str:
"""Compress an image and return it as a base64 data URI."""
with Image.open(image_path) as img:
if img.width > max_width:
ratio = max_width / img.width
new_size = (max_width, int(img.height * ratio))
img = img.resize(new_size, Image.LANCZOS)
buffer = io.BytesIO()
img.convert("RGB").save(buffer, format="JPEG", quality=quality, optimize=True)
buffer.seek(0)
b64 = base64.b64encode(buffer.read()).decode()
return f"data:image/jpeg;base64,{b64}"
logo_b64 = compress_image_to_base64("logo.png", max_width=400, quality=90)
html = f"""<html><body>
<img src="{logo_b64}" width="200" alt="Logo">
<h1>Report</h1>
</body></html>"""
Node.js image optimization
const sharp = require("sharp");
async function compressImageToBase64(imagePath, maxWidth = 800, quality = 85) {
const buffer = await sharp(imagePath)
.resize({ width: maxWidth, withoutEnlargement: true })
.jpeg({ quality, progressive: true })
.toBuffer();
return `data:image/jpeg;base64,${buffer.toString("base64")}`;
}
async function generateCompactPDF(title, content) {
const logoBase64 = await compressImageToBase64("logo.png", 400, 90);
const html = `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body style="font-family: sans-serif; margin: 40px;">
<img src="${logoBase64}" width="200" alt="Logo">
<h1>${title}</h1>
<p>${content}</p>
</body>
</html>`;
const res = await fetch("https://pdf.funbrew.cloud/api/pdf/generate-from-html", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.PDF_API_KEY}`,
"Content-Type": "application/json",
},
body: JSON.stringify({ html, options: { "page-size": "A4" } }),
});
if (!res.ok) throw new Error(`Generation failed: ${res.status}`);
// data contains filename, download_url, and file_size (bytes)
return (await res.json()).data;
}
Compressing a generated PDF (/api/pdf/compress)
To shrink a finished PDF, use the compress API. Pass a filename (as returned by the generation API) and a quality (low / medium / high, default medium), and you get a new PDF re-compressed with Ghostscript (the original file is not modified). It requires a plan with the compress feature, and the compressed result counts toward your monthly PDF quota.
curl -X POST https://pdf.funbrew.cloud/api/pdf/compress \
-H "Authorization: Bearer YOUR_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"filename": "RETURNED_FILENAME.pdf",
"quality": "medium"
}'
The response includes original_size, compressed_size, and savings_percent. See the PDF Compression API Guide for details.
4. Watermarks
FUNBREW PDF's watermark parameter
The simplest option is adding watermark to the generation request. The text (up to 255 characters) is stamped in the center of every page in light gray, rotated 45 degrees. Japanese text works too.
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>Contract</h1><p>This document is a draft.</p>",
"options": { "page-size": "A4" },
"watermark": "DRAFT"
}'
If you need control over position, size, color, or repetition, draw the watermark with CSS instead.
Diagonal text watermark with CSS
The CSS specification says that in paged media, position: fixed boxes are repeated on every page. Actual behavior depends on the rendering engine, so check the output with the engine you use (options.engine: fast or quality).
<!DOCTYPE html>
<html>
<head>
<style>
.watermark {
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%) rotate(-45deg);
font-size: 80px;
font-weight: bold;
color: rgba(200, 200, 200, 0.3);
z-index: 1000;
pointer-events: none;
white-space: nowrap;
user-select: none;
}
.content {
position: relative;
z-index: 1;
margin: 40px;
}
</style>
</head>
<body>
<div class="watermark">DRAFT</div>
<div class="content">
<h1>Contract</h1>
<p>This document is a draft. Not for distribution.</p>
</div>
</body>
</html>
Per-user confidential watermark (Python)
from datetime import datetime
from html import escape
# generate_pdf / download_pdf are defined in "Calling the API"
def generate_confidential_pdf(content_html: str, user_name: str, doc_id: str) -> dict:
"""Generate a PDF with a repeating user-info watermark for audit trails."""
timestamp = datetime.now().strftime("%Y-%m-%d %H:%M")
label = escape(f"{user_name} • {timestamp} • {doc_id}")
strips = "".join(
f'<div style="position: absolute; top: {i * 200}px; left: -100px; '
f"width: 150%; transform: rotate(-30deg); font-size: 14px; "
f"color: rgba(150, 150, 150, 0.2); white-space: nowrap; "
f'letter-spacing: 10px;">{label}</div>'
for i in range(-2, 10)
)
full_html = f"""<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
body {{ font-family: sans-serif; margin: 40px; }}
</style>
</head>
<body>
<div style="position: fixed; top: 0; left: 0; width: 100%; height: 100%;
z-index: 9999; pointer-events: none; overflow: hidden;">
{strips}
</div>
<div style="position: relative; z-index: 1;">
{content_html}
</div>
</body>
</html>"""
return generate_pdf(full_html)
data = generate_confidential_pdf(
content_html="<h1>Confidential Report</h1><p>Internal use only.</p>",
user_name="John Smith",
doc_id="DOC-2026-001",
)
download_pdf(data, "confidential.pdf")
Logo watermark (bottom-right corner)
<style>
.logo-watermark {
position: fixed;
bottom: 30px;
right: 30px;
opacity: 0.15;
z-index: 1000;
}
</style>
<img class="logo-watermark" src="data:image/png;base64,..." width="100" alt="">
5. Page Numbers & Headers/Footers
FUNBREW PDF's /api/pdf/page-numbers
The generation API has no header, footer, or page-number options. To add page numbers to a generated PDF, use the page-number API. You can set position (bottom-center, bottom-left, bottom-right, top-center, top-left, top-right; default bottom-center), a starting number start_number, and font_size (6 to 24, default 10). The label is a string containing {page} (page number) and {total} (total pages), defaulting to {page}. Numbers are drawn in Helvetica, so keep the label to Latin characters. A plan with the page_number feature is required.
# HEADERS / BASE_URL / download_pdf are defined in "Calling the API"
def add_page_numbers(filename: str, path: str) -> None:
response = requests.post(
f"{BASE_URL}/api/pdf/page-numbers",
headers=HEADERS,
json={"filename": filename, "position": "bottom-right", "font_size": 9},
timeout=60,
)
response.raise_for_status()
data = response.json()["data"] # filename, download_url, file_size, total_pages, expires_at
download_pdf(data, path)
add_page_numbers("REPORT_FILENAME.pdf", "report-numbered.pdf")
CSS @page rule
To control the header and footer text yourself, use margin boxes in the CSS @page rule (@top-center, @bottom-center, etc.) with counter(page) / counter(pages). Chromium added margin boxes and page counters in Chrome 131. FUNBREW PDF's fast engine is wkhtmltopdf, so request the quality engine (Pro or higher) when you use margin boxes, and check the output. If they don't render in your environment, use the page-number API above.
<!DOCTYPE html>
<html>
<head>
<style>
@page {
size: A4;
margin: 25mm 20mm 30mm 20mm;
/* Header */
@top-center {
content: "Monthly Report — April 2026";
font-size: 10px;
color: #666;
}
/* Footer: page number */
@bottom-center {
content: counter(page) " / " counter(pages);
font-size: 10px;
color: #666;
}
/* Footer left: company name */
@bottom-left {
content: "FUNBREW Inc.";
font-size: 10px;
color: #999;
}
/* Footer right: date */
@bottom-right {
content: "2026-04-06";
font-size: 10px;
color: #999;
}
}
/* Override for the first page (cover page — no header) */
@page :first {
@top-center { content: ""; }
}
body {
font-family: sans-serif;
font-size: 11pt;
line-height: 1.6;
}
</style>
</head>
<body>
<h1>Monthly Report</h1>
<p>Executive summary content...</p>
<div style="page-break-before: always;">
<h2>Chapter 2: Data Analysis</h2>
<p>...</p>
</div>
</body>
</html>
Dynamic header/footer with JavaScript
async function generateReport({ title, author, date, sections }) {
const sectionsHtml = sections
.map(
({ title: sTitle, content }, i) => `
<div ${i > 0 ? 'style="page-break-before: always;"' : ""}>
<h2>${sTitle}</h2>
${content}
</div>`
)
.join("");
// Values go inside CSS strings, so escape quotes and backslashes
const css = (s) => String(s).replace(/["\\]/g, "\\$&");
const html = `<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<style>
@page {
size: A4;
margin: 25mm 20mm 30mm 20mm;
@top-left { content: "${css(title)}"; font-size: 9px; color: #666; }
@top-right { content: "${css(author)}"; font-size: 9px; color: #666; }
@bottom-center {
content: "— " counter(page) " —";
font-size: 9px; color: #999;
}
@bottom-right { content: "${css(date)}"; font-size: 9px; color: #999; }
}
@page :first {
@top-left { content: ""; }
@top-right { content: ""; }
}
body { font-family: sans-serif; font-size: 11pt; line-height: 1.7; }
h1 { text-align: center; margin-bottom: 50px; }
h2 { color: #333; border-bottom: 2px solid #333; padding-bottom: 5px; }
</style>
</head>
<body>
<!-- Cover page -->
<div style="text-align: center; padding-top: 100px;">
<h1>${title}</h1>
<p style="color: #666;">${author} | ${date}</p>
</div>
${sectionsHtml}
</body>
</html>`;
const response = await fetch("https://pdf.funbrew.cloud/api/pdf/generate-from-html", {
method: "POST",
headers: {
Authorization: `Bearer ${process.env.PDF_API_KEY}`,
"Content-Type": "application/json",
},
// Margin boxes need the quality (Chromium) engine
body: JSON.stringify({ html, options: { "page-size": "A4", engine: "quality" } }),
});
if (!response.ok) throw new Error(`Generation failed: ${response.status}`);
return (await response.json()).data; // filename, download_url, ...
}
const report = await generateReport({
title: "Q1 2026 Business Report",
author: "Business Planning Dept.",
date: "April 6, 2026",
sections: [
{ title: "Executive Summary", content: "<p>...</p>" },
{ title: "Revenue Performance", content: "<table>...</table>" },
{ title: "Next Quarter Plan", content: "<p>...</p>" },
],
});
6. FUNBREW PDF API Reference Patterns
Basic curl calls
# Basic PDF generation (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": "<!DOCTYPE html><html><body><h1>Test</h1></body></html>",
"options": {
"page-size": "A4",
"margin-top": 20,
"margin-bottom": 20,
"margin-left": 15,
"margin-right": 15
}
}'
# Landscape
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": "...",
"options": { "page-size": "A4", "orientation": "Landscape" }
}'
Both return JSON; fetch the PDF from data.download_url.
Python client with error handling
import time
from typing import Optional
import requests
class FunbrewPDFClient:
"""FUNBREW PDF API client (retries only on 429, 5xx, and network errors)."""
BASE_URL = "https://pdf.funbrew.cloud"
def __init__(self, api_key: str, max_retries: int = 3):
self.max_retries = max_retries
self.session = requests.Session()
self.session.headers.update({"Authorization": f"Bearer {api_key}"})
def generate(
self,
html: str,
page_size: str = "A4",
orientation: str = "Portrait",
margins_mm: Optional[dict] = None,
watermark: Optional[str] = None,
) -> bytes:
"""Generate a PDF and return the PDF bytes."""
margins = margins_mm or {"top": 20, "bottom": 20, "left": 15, "right": 15}
payload = {
"html": html,
"options": {
"page-size": page_size,
"orientation": orientation,
**{f"margin-{side}": value for side, value in margins.items()},
},
}
if watermark:
payload["watermark"] = watermark
data = self._request("POST", f"{self.BASE_URL}/api/pdf/generate-from-html", json=payload).json()["data"]
return self._request("GET", data["download_url"]).content
def _request(self, method: str, url: str, **kwargs) -> requests.Response:
for attempt in range(self.max_retries):
try:
response = self.session.request(method, url, timeout=60, **kwargs)
except (requests.ConnectionError, requests.Timeout):
# Note: if the server already generated the PDF, retrying a POST generates it
# again and uses another unit of your monthly quota
if attempt < self.max_retries - 1:
time.sleep(2 ** attempt)
continue
raise
if response.status_code == 429 and attempt < self.max_retries - 1:
wait = int(response.headers.get("Retry-After", 2 ** attempt))
print(f"Rate limited. Retrying in {wait}s...")
time.sleep(wait)
continue
if response.status_code >= 500 and attempt < self.max_retries - 1:
time.sleep(2 ** attempt)
continue
response.raise_for_status() # do not retry 4xx (bad input, permissions, monthly limit)
return response
raise RuntimeError("Max retries exceeded")
# Usage: draft invoice with a watermark
client = FunbrewPDFClient(api_key="YOUR_API_KEY")
html = """<!DOCTYPE html>
<html>
<head><meta charset="utf-8"></head>
<body>
<h1>Invoice (Draft)</h1>
<p>Amount: $1,000</p>
</body>
</html>"""
pdf = client.generate(html, watermark="DRAFT")
with open("invoice-draft.pdf", "wb") as f:
f.write(pdf)
For production error handling patterns, see the API Error Handling Guide. For running in production, see the Production Guide.
7. Library Comparison: pypdf vs pdf-lib vs Ghostscript vs API
Feature overview
| Tool | Language | Strengths | Limitations |
|---|---|---|---|
| pypdf (formerly PyPDF2) | Python | Merge, split, metadata | No HTML→PDF |
| pdf-lib | JavaScript | Merge, text/image overlay, forms | Embedding non-standard fonts requires registering @pdf-lib/fontkit |
| Ghostscript | CLI | Compression, format conversion | Requires installation; AGPL license (check terms for commercial use) |
| pdfkit (Python) | Python | HTML→PDF | Requires a separate wkhtmltopdf install |
| FUNBREW PDF API | Any | HTML→PDF, merge, split, compress, page numbers, watermark, password protection at generation | External API dependency; no permission control (such as disabling printing) |
PyPDF2 has been merged back into pypdf, so install pypdf for new projects. Note that Node.js's "PDFKit" has a similar name but does not convert HTML; it builds PDFs from code.
pypdf merge & split
from pypdf import PdfWriter, PdfReader
def merge_pdfs(pdf_paths: list[str], output_path: str) -> None:
writer = PdfWriter()
for path in pdf_paths:
reader = PdfReader(path)
for page in reader.pages:
writer.add_page(page)
with open(output_path, "wb") as f:
writer.write(f)
def split_pdf(input_path: str, output_dir: str) -> None:
reader = PdfReader(input_path)
for i, page in enumerate(reader.pages):
writer = PdfWriter()
writer.add_page(page)
with open(f"{output_dir}/page_{i + 1}.pdf", "wb") as f:
writer.write(f)
pdf-lib watermark (JavaScript)
import { PDFDocument, rgb, degrees } from "pdf-lib";
// Drawn with the standard Helvetica font; for non-Latin text, register
// @pdf-lib/fontkit with registerFontkit and embed a font that has those characters
async function addWatermark(pdfBytes, text) {
const doc = await PDFDocument.load(pdfBytes);
for (const page of doc.getPages()) {
const { width, height } = page.getSize();
page.drawText(text, {
x: width / 2 - 100,
y: height / 2,
size: 50,
color: rgb(0.8, 0.8, 0.8),
opacity: 0.3,
rotate: degrees(-45),
});
}
return doc.save();
}
Ghostscript compression (CLI)
# Compress with Ghostscript (/ebook: medium resolution)
gs -sDEVICE=pdfwrite \
-dCompatibilityLevel=1.4 \
-dPDFSETTINGS=/ebook \
-dNOPAUSE -dQUIET -dBATCH \
-sOutputFile=compressed.pdf \
input.pdf
# Main presets (color images):
# /screen — low resolution; downsampled to 72 dpi
# /ebook — medium resolution; downsampled to 150 dpi
# /printer — print output; no downsampling (resolution value 300)
# /prepress — prepress output; no downsampling (resolution value 300)
Choosing your approach
Prefer a library when:
- Post-processing the API doesn't offer, such as encrypting existing PDFs
- Offline or air-gapped environment
- High-volume simple operations (e.g., splitting into single pages)
Prefer an API when:
- Generating from HTML and post-processing (merge, split, compress, page numbers, watermark) through the same API
- Minimizing server dependencies (slimmer Docker images)
- Calling from multiple languages or microservices with a unified interface
- Needing complex font and CSS control
For production error handling patterns, see the API Error Handling Guide. For security best practices, see the API Security Guide.
Summary
| Operation | Recommended approach | To do it on an existing PDF |
|---|---|---|
| Merge | Design as single HTML (page-break-before: always) |
/api/pdf/merge (all plans) |
| Split | Generate one file per record | /api/pdf/split (pages: "1-3,5") |
| Compress | Pre-optimize images (sharp / Pillow) | /api/pdf/compress (quality) |
| Watermark | watermark at generation, or CSS position: fixed |
— |
| Page numbers | CSS @page with counter(page) (quality engine) |
/api/pdf/page-numbers |
| Header/footer | CSS @page with @top-center, @bottom-center |
— |
The core insight: designing your PDF generation to produce the desired output directly is usually simpler than post-processing. FUNBREW PDF's playground lets you check generated output in your browser before integrating into your codebase.
Related articles
- HTML to PDF Complete Guide — Generation fundamentals and approach comparison
- PDF Batch Processing Guide — Efficiently generating large volumes
- PDF Compression API Guide — Using the compress API
- HTML to PDF CSS Tips — Print CSS techniques for production PDFs
- Automate Invoice PDFs — Full invoice automation workflow
- PDF Report Generation Guide — Designing and generating report PDFs
- Webhook Integration Guide — Getting notified when PDFs are generated
- API Error Handling Guide — Production-quality error handling
- API Security Guide — Secure API key management and access control
Start experimenting with the free plan. The documentation covers generation options and the merge API.