Split & Merge PDFs

Two endpoints for restructuring PDF documents:

Endpoint Method Purpose
/v1/pdf/split GET Split a PDF into single pages or page-range groups
/v1/pdf/merge POST Concatenate 2–20 PDFs (in the order provided) into one file

Base URL: https://pdf.toolkitapi.io

All binary output is returned as a base64-encoded string in the JSON response (pdf field, or parts[].pdf for split). Inputs are always fetched by public URL — the API downloads the document itself, so the URL must be reachable without authentication.

Splitting a PDF

Parameters (GET /v1/pdf/split)

Parameter Type Required Default Description
url string (≤ 2048 chars) ✅ — Public http/https URL of the PDF
pages string ❌ all all for one part per page, or a page spec such as 1-3,5,8-10

Page numbers are 1-based. In a page spec, each comma-separated token is either a single page (5) or an inclusive range (8-10). Each token becomes one output part, so 1-3,5,8-10 produces exactly three parts:

  1. pages 1–3 (labelled "1-3")
  2. page 5 (labelled "5")
  3. pages 8–10 (labelled "8-10")

Request

curl "https://pdf.toolkitapi.io/v1/pdf/split?url=https://example.com/report.pdf&pages=1-3,5,10-12" \
  -H "X-API-Key: YOUR_KEY"
import base64
import requests

resp = requests.get(
    "https://pdf.toolkitapi.io/v1/pdf/split",
    headers={"X-API-Key": "YOUR_KEY"},
    params={
        "url": "https://example.com/report.pdf",
        "pages": "1-3,5,10-12",
    },
    timeout=60,
)
resp.raise_for_status()
data = resp.json()

for part in data["parts"]:
    # part["pages"] is a human-readable label: "1-3", "5", "10-12"
    with open(f"part-{part['pages']}.pdf", "wb") as f:
        f.write(base64.b64decode(part["pdf"]))
    print(part["pages"], part["page_count"], part["file_size"], "bytes")
const params = new URLSearchParams({
  url: "https://example.com/report.pdf",
  pages: "1-3,5,10-12",
});

const resp = await fetch(`https://pdf.toolkitapi.io/v1/pdf/split?${params}`, {
  headers: { "X-API-Key": "YOUR_KEY" },
});
if (!resp.ok) throw new Error(`Split failed: ${resp.status} ${await resp.text()}`);

const data = await resp.json();
for (const part of data.parts) {
  const bytes = Buffer.from(part.pdf, "base64"); // or atob() in the browser
  // write to disk (Node) / trigger a download (browser)
  console.log(part.pages, part.page_count, part.file_size);
}
console.log(`${data.total_parts} of ${data.source_page_count} source pages`);

Response

{
  "parts": [
    { "pages": "1-3", "pdf": "JVBERi0xLjQK...", "page_count": 3, "file_size": 184320 },
    { "pages": "5",   "pdf": "JVBERi0xLjQK...", "page_count": 1, "file_size": 61200 },
    { "pages": "10-12", "pdf": "JVBERi0xLjQK...", "page_count": 3, "file_size": 173004 }
  ],
  "total_parts": 3,
  "source_page_count": 12
}
Field Type Description
parts[].pages string Page range label for this part ("5" for a single page)
parts[].pdf string Base64-encoded PDF bytes for this part
parts[].page_count int Pages in this part
parts[].file_size int Size of this part in bytes
total_parts int Number of parts produced
source_page_count int Total pages in the source PDF

Tip: pages=all on a 40-page document returns 40 separate base64 blobs in one response. For large documents, prefer explicit ranges to keep the payload manageable.

Merging PDFs

Parameters (POST /v1/pdf/merge)

Body is JSON:

Field Type Required Constraints Description
pdf_urls array of strings ✅ 2–20 URLs, http/https only PDFs to merge, in order

Request

curl -X POST "https://pdf.toolkitapi.io/v1/pdf/merge" \
  -H "X-API-Key: YOUR_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "pdf_urls": [
      "https://example.com/cover.pdf",
      "https://example.com/body.pdf",
      "https://example.com/appendix.pdf"
    ]
  }'
import base64
import requests

resp = requests.post(
    "https://pdf.toolkitapi.io/v1/pdf/merge",
    headers={"X-API-Key": "YOUR_KEY"},
    json={
        "pdf_urls": [
            "https://example.com/cover.pdf",
            "https://example.com/body.pdf",
            "https://example.com/appendix.pdf",
        ]
    },
    timeout=120,
)
resp.raise_for_status()
data = resp.json()

with open("merged.pdf", "wb") as f:
    f.write(base64.b64decode(data["pdf"]))

print(f"{data['page_count']} pages from {data['input_count']} files, {data['file_size']} bytes")
const resp = await fetch("https://pdf.toolkitapi.io/v1/pdf/merge", {
  method: "POST",
  headers: { "X-API-Key": "YOUR_KEY", "Content-Type": "application/json" },
  body: JSON.stringify({
    pdf_urls: [
      "https://example.com/cover.pdf",
      "https://example.com/body.pdf",
      "https://example.com/appendix.pdf",
    ],
  }),
});
if (!resp.ok) throw new Error(`Merge failed: ${resp.status} ${await resp.text()}`);

const data = await resp.json();
const bytes = Uint8Array.from(atob(data.pdf), (c) => c.charCodeAt(0));
console.log(`${data.page_count} pages from ${data.input_count} files`);

Response

{
  "pdf": "JVBERi0xLjQK...",
  "page_count": 27,
  "file_size": 1458234,
  "input_count": 3
}
Field Type Description
pdf string Merged PDF as base64
page_count int Total pages in the merged PDF
file_size int Size of the merged PDF in bytes
input_count int Number of input PDFs merged

Pages are appended in the order the URLs appear in pdf_urls. Duplicate URLs are allowed and will duplicate the content.

Common workflow: split into chunks, rewrite, merge back

A frequent document-pipeline pattern is to break a PDF apart, send individual parts to another service, and reassemble:

import base64
import requests

BASE = "https://pdf.toolkitapi.io"
HEADERS = {"X-API-Key": "YOUR_KEY"}

# 1. Split into 10-page groups (assuming a 42-page source)
ranges = ",".join(f"{i}-{min(i + 9, 42)}" for i in range(1, 43, 10))
split = requests.get(f"{BASE}/v1/pdf/split", headers=HEADERS,
                     params={"url": "https://example.com/big.pdf", "pages": ranges}).json()

# 2. Re-upload each part somewhere public (e.g. your own S3 bucket) and merge in reverse order
#    NOTE: /pdf/merge only accepts public URLs, not base64 input.
new_urls = [...]  # your uploaded part URLs, in the desired final order
merged = requests.post(f"{BASE}/v1/pdf/merge", headers=HEADERS,
                       json={"pdf_urls": new_urls}).json()

Design note: neither endpoint accepts an uploaded file directly — both read from a public URL. If your source files are private, upload them to a signed, temporary public URL (or your own object store) first, and keep those URLs short-lived.

Error cases

Status Condition Example detail
400 URL isn't a parseable PDF Could not parse the PDF
400 pdf_urls entry isn't a PDF (missing %PDF header) URL #2 does not point to a valid PDF
400 Malformed PDF in merge PDF #1 is malformed: ...
400 Page range out of bounds Page range '15-20' out of bounds (PDF has 12 pages)
400 Unparseable page spec Invalid page range: 'abc'
422 pdf_urls has < 2 or > 20 entries FastAPI validation error
413 Source PDF exceeds the download size limit payload too large
422 url/pdf_urls not reachable, or not http(s) download / validation error

Example error body:

{ "detail": "Page range '15-20' out of bounds (PDF has 12 pages)" }

Note that split and merge use 400 (not 422) for bad page specs and bad PDF content, because those checks happen inside the handler. Only request-shape validation (missing params, too many URLs, wrong types) produces FastAPI's 422.

Tips

  • Set a generous timeout. Merging or splitting large documents is CPU-bound; Python examples above use 60–120 s.
  • Decode base64 in a streaming way for large files — base64.b64decode / Buffer.from(..., "base64") are fine up to a few tens of MB, beyond that write chunks.
  • Page numbers are 1-based, inclusive. 1-1 is a valid single-page part and is labelled "1".
  • Merging ignores per-input rotation and page sizes — pages keep their original geometry, so mixed-size documents can look inconsistent. Normalize with /v1/pdf/rotate or template rendering before merging if you need uniform output.
  • Use split + merge to drop pages. There's no dedicated "delete pages" endpoint; split the ranges you want to keep and merge them back.
  • Idempotent and stateless. Neither endpoint stores anything server-side; the result only exists in the response.