May 15, 2026

PDF Merge API Guide: Combine Multiple PDFs in One API Call

PDF mergePDF APIcombine PDFNode.jsPython

Bundle invoices into a monthly report. Assemble a multi-document contract package. Archive a batch of event certificates into a single downloadable PDF. PDF merging is a common requirement across web apps, back-office automation, and SaaS platforms.

The FUNBREW PDF merge API (POST /api/pdf/merge) combines 2–50 PDF files into one with a single API call and returns a timed download URL. No local library (pypdf, iText, etc.) required — just HTTP.

This guide covers the full API specification, working code examples in cURL, Node.js, Python, and PHP, best practices for high-volume merging, and common failure modes.

For the full PDF generation pipeline (HTML to PDF, batch processing, S3 archival), see the PDF Batch Processing Guide. For certificate automation, see the PDF Certificate Automation Guide.

API Specification

FUNBREW PDF provides two endpoints for merging PDFs. Both have the same requirements:

  • SaaS edition only (the Open edition has no merge endpoint)
  • Plan: a plan with the merge feature (the current Free, Pro and Business plans all include it). A plan without it gets 403
  • API key scope: generate
  • Monthly quota: the merged result is stored as a new PDF, so it counts as one PDF toward your monthly quota (the source PDFs you generated are counted separately)

Endpoint 1: Merge server-side files

POST /api/pdf/merge
Content-Type: application/json
Authorization: Bearer {API key}

Request body

Parameter Type Required Description
filenames string[] One of the two Filenames to merge: the data.filename returned by a generation endpoint such as /api/pdf/generate-from-html (owned by your company and not expired)
upload_ids string[] One of the two IDs of files whose tus upload (/api/pdf/uploads) has completed
expiration_hours integer No Lifetime of the merged file in hours (0–168, default 24; 0 means no expiry)
max_downloads integer No Maximum downloads (0–100, default 10; 0 means unlimited)

filenames and upload_ids together must contain 2–50 entries. Pages are ordered by filenames first, then by upload_ids.

About watermark: a watermark field passes validation but is not applied — the merged PDF has no watermark. If you need one, add it to each PDF with the watermark field of a generation endpoint (generate-from-html etc.) before merging.

Success response (200)

{
  "success": true,
  "data": {
    "filename": "9b2f6c1e-4a7d-4c3e-8f21-5d0a6b7c8e90.pdf",
    "download_url": "https://pdf.funbrew.cloud/api/pdf/download/9b2f6c1e-4a7d-4c3e-8f21-5d0a6b7c8e90.pdf",
    "file_size": 204800,
    "expires_at": "2026-05-16T10:00:00.000000Z"
  }
}

file_size is in bytes. Fetching download_url also needs an API key with the download scope (send a GET with the Authorization header). With expiration_hours set to 0, expires_at is null.

Endpoint 2: Upload and merge local files

POST /api/pdf/merge-upload
Content-Type: multipart/form-data
Authorization: Bearer {API key}

Request parameters

Parameter Type Required Description
files[] file No PDF files to upload (PDF only, max 50 MB each, up to 50 files)
filenames[] string[] No Existing server filenames to include alongside uploaded files (up to 50)
expiration_hours integer No Lifetime in hours (0–168, default 24)
max_downloads integer No Maximum downloads (0–100, default 10)

The combined count of files[] and filenames[] must be at least 2. Uploaded files[] come first in the merged PDF, followed by filenames[]. Here too, watermark is not applied to the result.

For files over 50 MB, upload them with tus resumable upload (/api/pdf/uploads) and pass them to /api/pdf/merge as upload_ids. See the Resumable Upload (tus) Guide.

Error responses

HTTP Status Cause
401 Unauthorized Missing or invalid API key
403 Forbidden Your plan has no merge feature, or the API key lacks the generate scope
422 Unprocessable Entity Fewer than 2 or more than 50 files, file not found (including another company's file), expired, missing on storage, non-PDF or over-50 MB upload, parameter out of range
429 Too Many Requests Per-minute request limit or monthly PDF quota reached
500 Internal Server Error A PDF could not be read (encrypted PDF, PDF with a compressed cross-reference, etc. — see below)

Code Examples

In the generation examples, page size goes inside options as page-size (A3, A4, A5, Letter, Legal). The data.filename from the generation response can be passed straight to the merge API's filenames.

cURL (merge server-side files)

Generate PDFs first, then merge them using the returned filenames.

# Step 1: Generate the first PDF (capture the filename)
RESPONSE=$(curl -s -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
  -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "html": "<h1>Invoice #001</h1><p>May 2026</p>",
    "options": { "page-size": "A4" }
  }')
FILE1=$(echo "$RESPONSE" | jq -r '.data.filename')

# Step 2: Generate the second PDF
RESPONSE=$(curl -s -X POST https://pdf.funbrew.cloud/api/pdf/generate-from-html \
  -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "html": "<h1>Invoice #002</h1><p>May 2026</p>",
    "options": { "page-size": "A4" }
  }')
FILE2=$(echo "$RESPONSE" | jq -r '.data.filename')

# Step 3: Merge both PDFs
curl -s -X POST https://pdf.funbrew.cloud/api/pdf/merge \
  -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
  -H "Content-Type: application/json" \
  -d "{
    \"filenames\": [\"$FILE1\", \"$FILE2\"],
    \"expiration_hours\": 48,
    \"max_downloads\": 5
  }" | jq .

cURL (upload and merge local files)

If the PDFs are on your machine, use the merge-upload endpoint.

curl -s -X POST https://pdf.funbrew.cloud/api/pdf/merge-upload \
  -H "Authorization: Bearer $FUNBREW_PDF_API_KEY" \
  -F "files[]=@invoice-001.pdf" \
  -F "files[]=@invoice-002.pdf" \
  -F "files[]=@invoice-003.pdf" \
  -F "expiration_hours=72" \
  -F "max_downloads=10" | jq .

Node.js (merge server-side files)

Uses the built-in fetch of Node.js 18 or later.

const API_KEY  = process.env.FUNBREW_PDF_API_KEY;
const BASE_URL = "https://pdf.funbrew.cloud";

function escapeHtml(value) {
  return String(value)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

/**
 * Generate a PDF and return the server-side filename.
 */
async function generatePdf(html, options = {}) {
  const response = await fetch(`${BASE_URL}/api/pdf/generate-from-html`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      html,
      options: { "page-size": "A4", ...options },
    }),
  });

  if (!response.ok) {
    throw new Error(`PDF generation failed: HTTP ${response.status}`);
  }

  const { data } = await response.json();
  return data.filename;
}

/**
 * Merge server-side PDF files by filename.
 */
async function mergePdfs(filenames, options = {}) {
  const response = await fetch(`${BASE_URL}/api/pdf/merge`, {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      filenames,
      expiration_hours: options.expirationHours ?? 24,
      max_downloads:    options.maxDownloads ?? 10,
    }),
  });

  if (!response.ok) {
    const body = await response.text();
    throw new Error(`PDF merge failed: HTTP ${response.status} — ${body}`);
  }

  return response.json(); // { success, data: { filename, download_url, file_size, expires_at } }
}

// Example: generate 3 invoices and merge them
async function generateAndMergeInvoices(invoices) {
  console.log(`Generating ${invoices.length} invoices...`);

  // Parallel generation (with many items, limit concurrency to stay under the per-minute request limit)
  const filenames = await Promise.all(
    invoices.map((inv) =>
      generatePdf(`
        <div style="font-family: sans-serif; padding: 40px;">
          <h1>Invoice ${escapeHtml(inv.number)}</h1>
          <p>Client: ${escapeHtml(inv.client)}</p>
          <p>Amount: $${inv.amount.toLocaleString()}</p>
          <p>Date: ${escapeHtml(inv.date)}</p>
        </div>
      `)
    )
  );

  console.log(`Generated ${filenames.length} files. Merging...`);

  const result = await mergePdfs(filenames, {
    expirationHours: 48,
    maxDownloads: 5,
  });

  console.log("Merge complete:", result.data.download_url);
  return result.data;
}

// Run
generateAndMergeInvoices([
  { number: "#001", client: "Acme Corp",    amount: 15_000, date: "May 15, 2026" },
  { number: "#002", client: "Beta Ltd",     amount: 28_000, date: "May 15, 2026" },
  { number: "#003", client: "Gamma GmbH",   amount: 9_500,  date: "May 15, 2026" },
]).then(console.log).catch(console.error);

Node.js (upload local files)

const FormData = require("form-data");
const fs       = require("fs");
const path     = require("path");
const fetch    = require("node-fetch"); // node-fetch v2 (to send a form-data stream)

async function mergeLocalPdfs(filePaths, options = {}) {
  const form = new FormData();

  for (const filePath of filePaths) {
    form.append("files[]", fs.createReadStream(filePath), {
      filename:    path.basename(filePath),
      contentType: "application/pdf",
    });
  }

  if (options.expirationHours !== undefined) {
    form.append("expiration_hours", String(options.expirationHours));
  }
  if (options.maxDownloads !== undefined) {
    form.append("max_downloads", String(options.maxDownloads));
  }

  const response = await fetch("https://pdf.funbrew.cloud/api/pdf/merge-upload", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${process.env.FUNBREW_PDF_API_KEY}`,
      ...form.getHeaders(),
    },
    body: form,
  });

  if (!response.ok) {
    throw new Error(`Merge upload failed: HTTP ${response.status}`);
  }

  return response.json();
}

// Example
mergeLocalPdfs(
  ["reports/january.pdf", "reports/february.pdf", "reports/march.pdf"],
  { expirationHours: 72, maxDownloads: 3 }
).then((result) => {
  console.log("Download URL:", result.data.download_url);
  console.log("File size:",   result.data.file_size, "bytes");
});

Python (merge server-side files)

import html as html_lib
import os

import httpx

API_KEY  = os.environ["FUNBREW_PDF_API_KEY"]
BASE_URL = "https://pdf.funbrew.cloud"


def generate_pdf(html: str, **options) -> str:
    """Generate a PDF and return the server-side filename."""
    response = httpx.post(
        f"{BASE_URL}/api/pdf/generate-from-html",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "html": html,
            "options": {"page-size": "A4", **options},
        },
        timeout=120,
    )
    response.raise_for_status()
    return response.json()["data"]["filename"]


def merge_pdfs(
    filenames: list[str],
    expiration_hours: int = 24,
    max_downloads: int = 10,
) -> dict:
    """Merge server-side PDF files (2 to 50)."""
    response = httpx.post(
        f"{BASE_URL}/api/pdf/merge",
        headers={"Authorization": f"Bearer {API_KEY}"},
        json={
            "filenames":        filenames,
            "expiration_hours": expiration_hours,
            "max_downloads":    max_downloads,
        },
        timeout=300,  # many files can take a while
    )
    response.raise_for_status()
    return response.json()


# Example: generate monthly reports and merge them
def bundle_monthly_reports(month: str, departments: list[dict]) -> dict:
    """Generate per-department reports and bundle them into a single PDF."""
    filenames = []

    for dept in departments:
        html = f"""
        <html>
        <body style="font-family: sans-serif; padding: 40px;">
          <h1>{html_lib.escape(dept['name'])} Monthly Report</h1>
          <p>Period: {html_lib.escape(month)}</p>
          <p>Revenue: ${dept['revenue']:,}</p>
          <p>Target achievement: {dept['achievement_rate']:.1%}</p>
        </body>
        </html>
        """
        filename = generate_pdf(html)
        filenames.append(filename)
        print(f"Generated: {dept['name']} → {filename}")

    print(f"Merging {len(filenames)} files...")
    result = merge_pdfs(filenames, expiration_hours=72, max_downloads=5)

    print(f"Merge complete: {result['data']['download_url']}")
    return result["data"]


# Run
departments = [
    {"name": "Sales",       "revenue": 125_000, "achievement_rate": 1.08},
    {"name": "Marketing",   "revenue": 52_000,  "achievement_rate": 0.95},
    {"name": "Engineering", "revenue": 80_000,  "achievement_rate": 1.15},
]
result = bundle_monthly_reports("April 2026", departments)

Python (upload local files)

import os
from contextlib import ExitStack

import httpx


def merge_local_pdfs(
    file_paths: list[str],
    expiration_hours: int = 24,
    max_downloads: int = 10,
) -> dict:
    """Upload local PDF files and merge them."""
    with ExitStack() as stack:
        files = [
            ("files[]", (os.path.basename(p), stack.enter_context(open(p, "rb")), "application/pdf"))
            for p in file_paths
        ]
        response = httpx.post(
            "https://pdf.funbrew.cloud/api/pdf/merge-upload",
            headers={"Authorization": f"Bearer {os.environ['FUNBREW_PDF_API_KEY']}"},
            files=files,
            data={
                "expiration_hours": str(expiration_hours),
                "max_downloads":    str(max_downloads),
            },
            timeout=300,
        )
    response.raise_for_status()
    return response.json()


# Example
result = merge_local_pdfs(
    ["reports/q1.pdf", "reports/q2.pdf", "reports/q3.pdf"],
    expiration_hours=168,   # 7 days
    max_downloads=3,
)
print("Download URL:", result["data"]["download_url"])
print("File size:",   result["data"]["file_size"], "bytes")

PHP

<?php

class FunbrewPdfMerger
{
    private string $baseUrl = 'https://pdf.funbrew.cloud';

    public function __construct(private string $apiKey)
    {
    }

    /**
     * Merge server-side PDF files.
     *
     * @param string[] $filenames        Filenames to merge (data.filename from a generation call)
     * @param int      $expirationHours  Lifetime in hours (0-168)
     * @param int      $maxDownloads     Maximum downloads (0-100)
     */
    public function merge(
        array $filenames,
        int $expirationHours = 24,
        int $maxDownloads = 10
    ): array {
        $payload = [
            'filenames'        => $filenames,
            'expiration_hours' => $expirationHours,
            'max_downloads'    => $maxDownloads,
        ];

        $ch = curl_init("{$this->baseUrl}/api/pdf/merge");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => json_encode($payload),
            CURLOPT_HTTPHEADER     => [
                "Authorization: Bearer {$this->apiKey}",
                'Content-Type: application/json',
                'Accept: application/json',
            ],
            CURLOPT_TIMEOUT        => 300,
        ]);

        $body   = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($status !== 200) {
            throw new \RuntimeException("PDF merge failed: HTTP {$status} — {$body}");
        }

        return json_decode($body, true);
    }

    /**
     * Upload local PDF files and merge them.
     *
     * @param string[] $filePaths Local file paths
     */
    public function mergeUpload(
        array $filePaths,
        int $expirationHours = 24,
        int $maxDownloads = 10
    ): array {
        $postFields = [
            'expiration_hours' => $expirationHours,
            'max_downloads'    => $maxDownloads,
        ];

        foreach (array_values($filePaths) as $i => $path) {
            $postFields["files[{$i}]"] = new \CURLFile($path, 'application/pdf', basename($path));
        }

        $ch = curl_init("{$this->baseUrl}/api/pdf/merge-upload");
        curl_setopt_array($ch, [
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_POST           => true,
            CURLOPT_POSTFIELDS     => $postFields,
            CURLOPT_HTTPHEADER     => [
                "Authorization: Bearer {$this->apiKey}",
                'Accept: application/json',
            ],
            CURLOPT_TIMEOUT        => 300,
        ]);

        $body   = curl_exec($ch);
        $status = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($status !== 200) {
            throw new \RuntimeException("PDF merge upload failed: HTTP {$status} — {$body}");
        }

        return json_decode($body, true);
    }
}

// Usage (Laravel; define funbrew_pdf.key in config/services.php)
$merger = new FunbrewPdfMerger(config('services.funbrew_pdf.key'));

// Merge server-side files (filenames are the data.filename values from generation)
$result = $merger->merge(
    filenames:       [$filename1, $filename2, $filename3],
    expirationHours: 48,
    maxDownloads:    5
);

echo "Download URL: " . $result['data']['download_url'] . "\n";
echo "File size: "    . $result['data']['file_size']    . " bytes\n";

Use Case Patterns

Invoice bundle (end-of-month dispatch)

Generate all invoices for a billing period and merge them per client for a single-attachment email.

import asyncio
import html as html_lib

import aiohttp
import httpx


async def generate_invoice_async(
    session: aiohttp.ClientSession,
    invoice: dict,
    api_key: str,
) -> str:
    """Generate an invoice PDF asynchronously and return its filename."""
    rows = "".join(
        f"<tr><td>{html_lib.escape(i['name'])}</td><td>{i['qty']}</td><td>${i['price']:,}</td></tr>"
        for i in invoice["items"]
    )
    html = f"""
    <html>
    <body style="font-family: sans-serif; padding: 40px;">
      <h1>Invoice #{html_lib.escape(str(invoice['number']))}</h1>
      <table>
        <tr><th>Item</th><th>Qty</th><th>Amount</th></tr>
        {rows}
      </table>
      <p><strong>Total: ${invoice['total']:,}</strong></p>
    </body>
    </html>
    """
    async with session.post(
        "https://pdf.funbrew.cloud/api/pdf/generate-from-html",
        headers={"Authorization": f"Bearer {api_key}"},
        json={"html": html, "options": {"page-size": "A4"}},
        timeout=aiohttp.ClientTimeout(total=120),
    ) as resp:
        resp.raise_for_status()
        return (await resp.json())["data"]["filename"]


async def bundle_client_invoices(invoices: list[dict], api_key: str) -> str:
    """Generate all invoices (2 to 50) and merge them into one PDF."""
    async with aiohttp.ClientSession() as session:
        sem = asyncio.Semaphore(5)

        async def limited(inv):
            async with sem:
                return await generate_invoice_async(session, inv, api_key)

        filenames = await asyncio.gather(*[limited(inv) for inv in invoices])

    # Merge (asyncio.gather returns results in input order, so pages follow the invoices order)
    async with httpx.AsyncClient(timeout=300) as client:
        result = await client.post(
            "https://pdf.funbrew.cloud/api/pdf/merge",
            headers={"Authorization": f"Bearer {api_key}"},
            json={"filenames": list(filenames), "expiration_hours": 72},
        )
    result.raise_for_status()
    return result.json()["data"]["download_url"]

Contract package assembly

Merge a main contract, memorandum, and appendices into a single document set. buildMainContractHtml and friends are your own functions that build the HTML.

async function createContractPackage(contractData) {
  const API_KEY = process.env.FUNBREW_PDF_API_KEY;

  // Generate each document (add the DRAFT watermark at generation time; the merge API ignores watermark)
  const documents = [
    { name: "main-contract", html: buildMainContractHtml(contractData) },
    { name: "memo",          html: buildMemorandumHtml(contractData) },
    { name: "appendix",      html: buildAppendixHtml(contractData) },
  ];

  const filenames = await Promise.all(
    documents.map(async (doc) => {
      const res = await fetch("https://pdf.funbrew.cloud/api/pdf/generate-from-html", {
        method: "POST",
        headers: {
          Authorization: `Bearer ${API_KEY}`,
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          html: doc.html,
          options: { "page-size": "A4" },
          watermark: "DRAFT", // pre-signature watermark
        }),
      });
      if (!res.ok) throw new Error(`${doc.name}: HTTP ${res.status}`);
      return (await res.json()).data.filename;
    })
  );

  // Merge into a single PDF (7-day expiry, 2 downloads — one for each party)
  const mergeRes = await fetch("https://pdf.funbrew.cloud/api/pdf/merge", {
    method: "POST",
    headers: {
      Authorization: `Bearer ${API_KEY}`,
      "Content-Type": "application/json",
    },
    body: JSON.stringify({
      filenames,
      expiration_hours: 168,
      max_downloads:    2,
    }),
  });
  if (!mergeRes.ok) throw new Error(`merge: HTTP ${mergeRes.status}`);

  return (await mergeRes.json()).data.download_url;
}

Quarterly report bundle

Merge monthly report PDFs into a quarterly summary on a scheduled basis. Source files cannot be merged once they expire, so give the monthly reports a long enough expiration_hours when you generate them (up to 168 hours, or 0 for no expiry).

from datetime import date

import httpx


def merge_quarterly_reports(year: int, quarter: int, api_key: str) -> str:
    """Merge the monthly report PDFs of the given quarter."""
    start_month = (quarter - 1) * 3 + 1
    months      = [start_month, start_month + 1, start_month + 2]

    # Look up each month's filename in your own DB (get_monthly_report_filename is your own function)
    filenames = []
    for month in months:
        report_date = date(year, month, 1)
        filename    = get_monthly_report_filename(report_date)
        if filename:
            filenames.append(filename)

    if len(filenames) < 2:
        raise ValueError(f"Not enough reports to merge: {len(filenames)}")

    result = httpx.post(
        "https://pdf.funbrew.cloud/api/pdf/merge",
        headers={"Authorization": f"Bearer {api_key}"},
        json={
            "filenames":        filenames,
            "expiration_hours": 168,
            "max_downloads":    50,
        },
        timeout=300,
    )
    result.raise_for_status()
    return result.json()["data"]["download_url"]

Best Practices for Bulk Merging

1. Merge in stages for more than 50 files

/api/pdf/merge accepts at most 50 files per request. For more, merge groups into intermediate files and then merge those. The example below adds stages as needed, so it still works when there are more than 50 intermediates. It uses merge_pdfs from "Python (merge server-side files)" above.

def merge_many(filenames: list[str], chunk_size: int = 50) -> dict:
    """Merge any number of files (2 or more) into one PDF, in stages."""
    if len(filenames) < 2:
        raise ValueError("At least 2 files are required")

    current = filenames
    stage = 1
    while len(current) > chunk_size:
        chunks = [current[i:i + chunk_size] for i in range(0, len(current), chunk_size)]
        next_round = []
        for i, chunk in enumerate(chunks):
            if len(chunk) == 1:
                next_round.append(chunk[0])  # a single leftover moves on as is
                continue
            print(f"Stage {stage}: merging {i + 1}/{len(chunks)} ({len(chunk)} files)...")
            result = merge_pdfs(chunk, expiration_hours=2)  # intermediates expire after 2 hours
            next_round.append(result["data"]["filename"])
        current = next_round
        stage += 1

    return merge_pdfs(current)["data"]

Intermediate files are stored as PDFs too, so they count toward the monthly quota. Merging 100 files into one adds 3 more PDFs: 2 intermediates and the final file.

2. Separate generation from merging

Run the generation phase in parallel and merge once every PDF has been generated. Keep the concurrency below the per-minute request limit (per company; 120 per minute on Pro).

import asyncio

import aiohttp


async def generate_all_async(html_list: list[str], api_key: str, concurrency: int = 5) -> list[str]:
    """Render several HTML documents to PDF in parallel (results in html_list order)."""
    sem = asyncio.Semaphore(concurrency)

    async def generate_one(session, html):
        async with sem:
            async with session.post(
                "https://pdf.funbrew.cloud/api/pdf/generate-from-html",
                headers={"Authorization": f"Bearer {api_key}"},
                json={"html": html, "options": {"page-size": "A4"}},
                timeout=aiohttp.ClientTimeout(total=120),
            ) as resp:
                resp.raise_for_status()
                data = await resp.json()
                return data["data"]["filename"]

    async with aiohttp.ClientSession() as session:
        filenames = await asyncio.gather(*[generate_one(session, h) for h in html_list])

    return list(filenames)


def generate_and_merge_pipeline(html_list: list[str], api_key: str) -> str:
    """Generate PDFs in parallel, then merge."""
    filenames = asyncio.run(generate_all_async(html_list, api_key))
    print(f"Generated {len(filenames)} PDFs")

    # Merge (in stages when there are more than 50)
    return merge_many(filenames)["download_url"]

3. Control page order explicitly

The order of filenames (or files[]) in the request determines the page order in the merged PDF. When merge-upload mixes files[] and filenames[], the uploaded files[] come first. Sort before merging.

# Sort by invoice number before merging (filenames are the values returned by generation)
items = [
    {"filename": filename_c, "invoice_no": 3},
    {"filename": filename_a, "invoice_no": 1},
    {"filename": filename_b, "invoice_no": 2},
]
sorted_filenames = [
    item["filename"]
    for item in sorted(items, key=lambda x: x["invoice_no"])
]
# → [filename_a, filename_b, filename_c]

Each page keeps the size and orientation of its source page, so a mix of A4 portrait and A4 landscape pages stays as it is.

4. Choose expiration and download limits by use case

expiration_hours is at most 168 hours (7 days) and max_downloads at most 100. Out-of-range values return 422.

Use case expiration_hours max_downloads Rationale
Contract set (pre-signature) 168 (7 days) 2 One download each party
Internal report distribution 168 (7 days) 100 Many downloads within the week
Temporary review copy 4 3 Discard after review
Long-term storage 0 (no expiry) 0 (unlimited) Delete with DELETE /api/pdf/delete/{filename} when no longer needed

Common Failures and Fixes

File not found or expired (422)

{
  "success": false,
  "message": "File not found or not owned by your company: 9b2f6c1e-4a7d-4c3e-8f21-5d0a6b7c8e90.pdf"
}

An expired file returns "File is expired: <filename>", and a file missing from storage returns "File not found on storage: <filename>".

Root causes:

  1. Generated with another company's API key: Files are scoped to a company. The API key used to generate must belong to the same company as the one used to merge. PDFs generated in test mode (test: true) are not tied to a company and cannot be merged.
  2. File expired: Once the generation-time expiration_hours (default 24 hours) has passed, the file cannot be merged. Merge right after generation, or set a longer expiry.
  3. Wrong filename: Use the exact data.filename value returned by the generation endpoint (including .pdf). It is not the same as the filename you may pass at generation time (the download name).

Encrypted PDF error (500)

The free FPDI parser used for merging cannot read encrypted PDFs, so the request fails with a server error (500). The server-side error message is:

This PDF document is encrypted and cannot be processed with FPDI.

Fix: Remove the password before merging. Locally you can use qpdf:

qpdf --password="your-password" --decrypt encrypted.pdf decrypted.pdf

PDF with a compressed cross-reference (500)

The free FPDI parser only reads PDFs with a normal cross-reference table. PDFs that use the compressed form introduced in PDF 1.5 (cross-reference streams) cannot be read and the request fails with a server error (500). The server-side message is:

This PDF document probably uses a compression technique which is not supported by the free parser shipped with FPDI.

The version in the header (%PDF-1.7 etc.) does not tell you. Check whether the file contains /Type /XRef:

import re

with open("document.pdf", "rb") as f:
    data = f.read()

print("version:", data[:8])
print("XRef stream:", bool(re.search(rb"/Type\s*/XRef", data)))  # True means the merge API cannot read it
print("encrypted:", bool(re.search(rb"/Encrypt", data)))

If so, rewrite the file as PDF 1.4 with Ghostscript. Ghostscript's pdfwrite uses cross-reference streams when writing PDF 1.5 or later, so pass -dCompatibilityLevel=1.4.

# Convert to PDF 1.4 (normal cross-reference table) with Ghostscript
gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite -dCompatibilityLevel=1.4 \
   -sOutputFile=converted.pdf input.pdf

File size limit exceeded

Each file uploaded via merge-upload must be 50 MB or smaller. Upload large PDFs with tus and pass them to merge as upload_ids, or compress them first. When compressing with Ghostscript, add -dCompatibilityLevel=1.4 for the same reason (presets such as /ebook default to 1.5):

# Compress with Ghostscript (/screen downsamples images to 72 dpi, /ebook to 150 dpi)
gs -dBATCH -dNOPAUSE -sDEVICE=pdfwrite \
   -dCompatibilityLevel=1.4 \
   -dPDFSETTINGS=/ebook \
   -sOutputFile=compressed.pdf input.pdf

For PDFs already on the server, you can also use the PDF Compress API (POST /api/pdf/compress).

Request timeout

Merging is synchronous: the response comes back only after the merge finishes. To allow for many or large files, set a generous HTTP client timeout (300 seconds in the examples above).

# httpx
response = httpx.post(url, ..., timeout=300)

# requests
response = requests.post(url, ..., timeout=300)

Related APIs

API Endpoint Purpose
PDF generation POST /api/pdf/generate-from-html Render HTML to PDF (URL, Markdown and template sources also available)
PDF merge POST /api/pdf/merge Combine multiple PDFs
PDF split POST /api/pdf/split Split one PDF into several
PDF compress POST /api/pdf/compress Compress a stored PDF
File download GET /api/pdf/download/{filename} Download a stored file

For the full API reference, see the API Documentation. Splitting is covered in the PDF Split API Guide. For high-volume batch generation pipelines, see the PDF Batch Processing Guide. For certificate automation (bulk issuance, S3 archival, email delivery), see the PDF Certificate Automation Guide. For event-specific bulk certificate pipelines, see the Bulk Certificate Generator for Events Guide.


Summary

Key points for the FUNBREW PDF merge API:

  1. Two endpoints: Use POST /api/pdf/merge for server-side files and tus uploads, and POST /api/pdf/merge-upload for local file uploads. Both are SaaS edition, available on every plan
  2. 50-file limit: For more files, merge in stages (intermediate files count toward the monthly quota)
  3. Expiration and download limits: Set expiration_hours (up to 168 hours) and max_downloads (up to 100) to match your use case
  4. Page order: The array order in filenames / files[] directly determines the page order in the merged PDF — sort explicitly
  5. Common failures: Watch for encrypted PDFs and PDFs with a compressed cross-reference (both 500), size limit overruns, and expired source files. Add watermarks at generation time, not at merge time
  6. Parallel generation + merge: Generate in parallel within the per-minute limit, and merge once all PDFs are ready

Use the FUNBREW PDF Playground to test PDF generation before adding the merge step. Full API reference at API Documentation.

Powered by FUNBREW PDF