← Back to blog

Split, Rotate, and Compress PDFs with curl and Python

September 28, 2026 · Eric · 6 min read

Most "PDF surgery" work is boring and repetitive: one contract needs to become twelve single-page files, a scanner produced sideways pages again, and a 40 MB report has to fit through an email attachment limit. The usual fix is installing qpdf, Ghostscript, or a pile of Python libraries on every machine that touches the file — and then keeping those installs current forever.

Agent Media Tools runs those operations server-side instead. POST /api/split-pdf, POST /api/pdf-rotate, and POST /api/compress-pdf accept a multipart PDF upload and hand back real files or real size numbers. No local toolchain, no wrapper script, and nothing to keep patched. Here's how the three behave, what each one returns, and where the authentication boundaries actually sit.

The three endpoints at a glance

EndpointBodyAuthReturns
/api/split-pdfpdfsession or agent keyPage count plus one download URL per page
/api/pdf-rotatepdf, angle, pagessessionRotated PDF URL plus rotated/total counts
/api/compress-pdfpdfsession or agent keyOriginal size, compressed size, savings percent

All three upload the file as multipart form data with the field name pdf, and PDF uploads are capped at 75 MB. Rotate is the odd one out on authentication: it accepts a logged-in session only, while split and compress accept either a session or an agent API key. That difference matters if you're wiring this into an autonomous pipeline, so plan for it.

Two ways to authenticate

Agent keys are the cleanest path for automation. Create one from the API keys panel in the toolbox, or while logged in:

curl -s -X POST https://agentmediatools.com/api/agent/keys \
  -b cookies.txt \
  -H 'Content-Type: application/json' \
  -d '{"name":"pdf-pipeline"}'

The response contains the key itself exactly once — it starts with mt_. Store it as an environment variable and send it as a Bearer token:

export AMT_API_KEY=mt_your_key_here
curl -H "Authorization: Bearer $AMT_API_KEY" ...

If you'd rather use a session cookie, log in and keep the cookie jar:

curl -s -c cookies.txt -X POST https://agentmediatools.com/api/login \
  -H 'Content-Type: application/json' \
  -d '{"username":"you@example.com","password":"your-password"}'

Then pass -b cookies.txt on every PDF call. Server-side, both paths log against the same daily tool-call budget, so pick one and stay consistent.

Split: one PDF in, a page per file out

Splitting explodes a document into single-page PDFs. The response is a manifest, not a zip, so you can decide what to do with each page:

curl -s -X POST https://agentmediatools.com/api/split-pdf \
  -H "Authorization: Bearer $AMT_API_KEY" \
  -F "pdf=@contract.pdf"
{
  "success": true,
  "pages": 12,
  "files": [
    { "filename": "<page file>.pdf", "downloadUrl": "/downloads/<dirId>/<page file>.pdf" }
  ],
  "dirId": "<dirId>"
}

Download URLs are relative — prepend the host. A complete Python round trip that writes every page to disk looks like this:

import os, pathlib, requests

BASE = "https://agentmediatools.com"
HEADERS = {"Authorization": f"Bearer {os.environ['AMT_API_KEY']}"}

with open("contract.pdf", "rb") as fh:
    resp = requests.post(f"{BASE}/api/split-pdf",
                         headers=HEADERS,
                         files={"pdf": fh},
                         timeout=180)
resp.raise_for_status()
data = resp.json()

out = pathlib.Path("pages")
out.mkdir(exist_ok=True)
for item in data["files"]:
    page = requests.get(BASE + item["downloadUrl"], headers=HEADERS, timeout=180)
    page.raise_for_status()
    (out / item["filename"]).write_bytes(page.content)

print(f"{data['pages']} pages written to {out}/")

Use the filenames from the response rather than guessing a pattern — page numbering pads differently at 10+ pages, and the manifest is authoritative.

Rotate: fix the sideways scans

Rotation takes an optional angle (degrees; defaults to 90) and an optional pages value — either a comma-separated list like 1,3,5 or the literal all:

curl -s -X POST https://agentmediatools.com/api/pdf-rotate \
  -b cookies.txt \
  -F "pdf=@scan.pdf" \
  -F "angle=90" \
  -F "pages=1,2,3" \
  -o rotated.pdf

The JSON response reports exactly what moved, which is useful when a document arrives partially rotated and you need a log line that proves what was corrected:

{ "success": true, "filename": "<name>.pdf",
  "downloadUrl": "/downloads/<name>.pdf",
  "pages": 3, "total": 12 }

Two honest notes. First, this route requires a session login — agent keys are rejected, so a fully headless pipeline needs a cookie jar or a different tool. Second, rotation only changes orientation; it does not straighten a skewed scan or fix a rotated-then-cropped page. Verify the output on odd documents before you trust it in a batch.

Compress: shrink it and prove the savings

Compression returns the before and after in bytes, so you can assert on the result instead of hoping:

curl -s -X POST https://agentmediatools.com/api/compress-pdf \
  -H "Authorization: Bearer $AMT_API_KEY" \
  -F "pdf=@annual-report.pdf"
{
  "success": true,
  "filename": "<name>.pdf",
  "originalSize": 41943040,
  "compressedSize": 6123520,
  "savingsPercent": 85,
  "downloadUrl": "/downloads/<name>.pdf"
}

A batch loop that keeps only files worth keeping:

import os, pathlib, requests

BASE = "https://agentmediatools.com"
HEADERS = {"Authorization": f"Bearer {os.environ['AMT_API_KEY']}"}
dest = pathlib.Path("compressed"); dest.mkdir(exist_ok=True)

for src in pathlib.Path("inbox").glob("*.pdf"):
    with open(src, "rb") as fh:
        resp = requests.post(f"{BASE}/api/compress-pdf",
                             headers=HEADERS,
                             files={"pdf": fh},
                             timeout=300)
    result = resp.json()
    if not result.get("success"):
        print(f"{src.name}: {result.get('error')}")
        continue
    print(f"{src.name}: {result['savingsPercent']}% smaller")
    if result["savingsPercent"] > 5:
        blob = requests.get(BASE + result["downloadUrl"], headers=HEADERS, timeout=300)
        (dest / src.name).write_bytes(blob.content)

Compression is general-purpose optimization, not a guarantee. Always confirm that text stayed selectable and that embedded images still look correct on documents you care about — the route reduces size, it doesn't validate your document for you.

Pulling text and images out for agents

Two more routes in the same family are worth knowing, because they have separate session and agent versions:

The agent variant has a 20 MB response ceiling for the generated images. Go past it and you get HTTP 413 with the code GENERATED_RESPONSE_TOO_LARGE — a signal to rasterize fewer pages per call rather than retry the same request.

Limits, errors, and the 429 you will eventually hit

Daily tool-call limits are real and shared with the rest of the platform: 25 calls per day on a free account or free agent key, and 1,000 per day on a Pro key. Exceed it and every PDF route starts returning HTTP 429 with a message naming the limit. Paid plans are the answer for sustained batch work; free agent keys fall back to purchased usage credits when the daily count runs out.

The other statuses are worth handling explicitly:

What about MCP?

If your agent talks MCP instead of HTTP, the PDF surface there is different. The MCP server exposes merge_pdfs, pdf_pages, pdf_form_fill, pdf_to_markdown, and ocr_extract. Split, rotate, and compress are not MCP tools — they stay on the REST endpoints covered above, so an MCP-only agent should call them over HTTP or use the pdf_pages tool when it needs page-level extraction rather than a full split.

Wrap up

Three tedious PDF jobs, three endpoints, no local toolchain. Authenticate with an mt_ agent key, post multipart pdf fields, read the manifest or the savings numbers out of the JSON response, and handle 429 before it pages you at 2 a.m. For merge, page-level extract/delete/reorder, and PDF-to-Markdown work, the existing merge guide and PDF processing overview cover the neighbouring routes — and the per-tool pages below document each endpoint's parameters.

Try it in the Toolbox

Split, rotate, and compress a PDF in the browser — or call the same endpoints from your agent with an API key.

Open toolbox