All posts →
|Also available in:DE

PDF Processing API – Merge, Split and Auto-Rotate PDFs

Merge, split and automatically rotate PDFs with the MaraDocs PDF manipulation API. Thumbnails, page selection, orientation correction – all in one API.

•Martin Kurtz
APIPDFDocument ProcessingDevelopers
PDF Processing API – Merge, Split and Auto-Rotate PDFs

Do you need to merge several PDFs, select specific pages, or fix incorrectly rotated scans? In our law firm, case files often arrived as separate PDFs – expert opinions, client letters, court documents – that had to be merged and reordered. An API for merging and splitting PDFs that also corrects orientation would simplify this workflow considerably.

It sounds simple – until you try to integrate PyMuPDF, pikepdf or similar libraries into a robust pipeline with virus scanning and validation.

Why Building Your Own PDF Merge and Split Solution Takes Weeks

PyMuPDF, pikepdf, PyPDF2 and reportlab each cover parts of PDF manipulation. Merging works – until you run into encrypted files, corrupted streams or unusual encodings. Anyone who wants to build this themselves quickly discovers that orientation detection typically requires OCR or layout analysis – more dependencies, more infrastructure. Generating thumbnails means rendering pages to images, scaling them and encoding them. Building a reliable, validated PDF manipulation API takes time and hides complexity in edge cases.

How the MaraDocs API for Merging and Splitting PDFs Solves This in Minutes

The MaraDocs API offers PDF processing as a service. Upload, validate (viruses and format), then compose (merge/split by page), detect and correct orientation, generate thumbnails, optimize and run OCR – all through a single API. No uploads between steps; files stay in the workspace. You specify which pages from which PDFs to combine, and the API returns a single composed handle. Orientation correction uses text-based analysis, so rotated scans are corrected automatically.

Document Processing Workflow: Upload, Validate, Compose, Orient

Every MaraDocs workflow starts with upload and validation. Upload a PDF (or take one from a previous step), validate it for viruses and format, then chain operations. The compose endpoint lets you merge multiple PDFs and select specific pages: e.g. { pdf_handle: p1, pages: [{ page_number: 0 }, { page_number: 2 }] } for pages 1 and 3 of the first document, plus { pdf_handle: p2 } for the entire second document. Orientation detection uses text-based analysis to automatically correct rotated pages. For thumbnails: render a page as an image, then create a thumbnail, then convert it to JPEG – all with server-side handles, no re-uploading.

Get your API key in under a minute

Register for a free account and get your API key in under a minute. Of course we'll provide you with some developer credits.

Try MaraDocs API now →

What Sets MaraDocs Apart: Workspaces, Webview and German Data Protection Law

Most document APIs force you to upload, process, download and upload again for the next step. With MaraDocs workspaces, files stay on the server. Handles are passed between operations: validate → compose → orient → optimize. Fewer round trips, simpler code, and no need to track file identities across steps.

If the automation runs into an edge case – an incorrect page order, a corrupted stream or an unusual encoding – you can open app.maradocs.io with the workspace secret for manual review and editing. Users get full manual control when the pipeline needs human intervention.

All processing takes place in Germany (Maramia GmbH), with encryption at rest (SSE-C) and in transit (TLS). Workspaces expire after 7 days. No data leaves the EU. This is relevant for GDPR- and BDSG-sensitive workloads.

TypeScript Code for Merging and Auto-Rotating PDFs

API reference: data/upload, pdf/validate, pdf/compose, pdf/orientation, pdf/to/img, img/thumbnail, data/download/pdf

import { MaraDocsClient } from "@maramia/maradocs-sdk-ts";
import { okPdf } from "@maramia/maradocs-sdk-ts/models/pdf";

const client = new MaraDocsClient({ workspaceSecret: workspace_secret });

// Beide PDFs hochladen und validieren
const up1 = await client.data.upload(pdf1File);
const up2 = await client.data.upload(pdf2File);
const val1 = await client.pdf.validate({ unvalidated_file_handle: up1.unvalidated_file_handle });
const val2 = await client.pdf.validate({ unvalidated_file_handle: up2.unvalidated_file_handle });
const pdf1 = okPdf(val1);
const pdf2 = okPdf(val2);

// PDFs zusammenführen, bestimmte Seiten auswählen
const composed = await client.pdf.compose({
  pdfs: [
    { pdf_handle: pdf1, pages: [{ page_number: 0 }, { page_number: 2 }] },
    { pdf_handle: pdf2 },
  ],
});

// Ausrichtung automatisch erkennen und korrigieren
const oriented = await client.pdf.orientation({
  pdf_handle: composed.pdf_handle,
});

// Ergebnis herunterladen
const blob = await client.data.downloadPdf({ pdf_handle: oriented.rotated_pdf_handle });

// Optional: Vorschaubild (Seite als Bild rendern, dann Vorschaubild erstellen)
const imgResult = await client.pdf.toImg({
  pdf_handle: oriented.rotated_pdf_handle,
  pages: [0],
});
const thumb = await client.img.thumbnail({
  img_handle: imgResult.img_handles[0],
});

Python Code for Merging and Orienting PDFs

API reference: data/upload, pdf/validate, pdf/compose, pdf/orientation, data/download/pdf

# pip install python-decouple requests
"""Merge PDFs (with optional page selection) using MaraDocs. Set ACCOUNT_SECRET in .env or environment."""

import sys
import time
from pathlib import Path

import requests
from decouple import config

API_URL = "https://api.maradocs.io/v1"


def create_workspace() -> dict:
    """Create a workspace and return auth headers."""
    r = requests.post(
        f"{API_URL}/workspace",
        headers={"Authorization": f"Bearer {config('ACCOUNT_SECRET')}"},
        json={"subaccount": None},
    )
    ws = r.json()
    return {"Authorization": f"Bearer {ws['workspace_secret']}"}


def upload_file(path: Path, auth: dict) -> dict:
    """Upload a file via two-step flow (signed URL + S3 POST). Returns unvalidated_file_handle."""
    data = path.read_bytes()
    resp = requests.post(
        f"{API_URL}/data/upload",
        headers={**auth, "Content-Type": "application/json"},
        json={"name": path.name, "size": len(data)},
    ).json()
    requests.post(
        resp["post_url"],
        data=resp.get("post_header", {}),
        files={"file": (path.name, data, "application/pdf")},
    )
    return resp["unvalidated_file_handle"]


def run_job(path: str, payload: dict, auth: dict, timeout: int = 60) -> dict:
    """Run a job and poll until complete. Returns the result (unwraps response if present)."""
    url = f"{API_URL}/{path}"
    r = requests.post(url, headers=auth, json=payload).json()
    job_id = r["job_id"]
    start = time.time()
    while time.time() - start < timeout:
        poll_r = requests.get(f"{url}/{job_id}", headers=auth)
        if poll_r.status_code == 200:
            return poll_r.json()
    raise TimeoutError(f"Job {path} timed out")


def download_pdf(pdf_handle: str, auth: dict) -> bytes:
    """Request signed URL and fetch PDF bytes."""
    r = requests.post(
        f"{API_URL}/data/download/pdf",
        headers=auth,
        json={"pdf_handle": pdf_handle},
    )
    info = r.json()
    dl = requests.get(info["url"], headers=info.get("headers", {}))
    return dl.content


def main() -> None:
    paths = (
        [Path(p) for p in sys.argv[1:]]
        if len(sys.argv) > 1
        else [Path("doc1.pdf"), Path("doc2.pdf")]
    )
    auth = create_workspace()
    handles = [upload_file(p, auth) for p in paths]
    pdf_handles = [
        run_job("pdf/validate", {"unvalidated_file_handle": h}, auth)["response"][
            "pdf_handle"
        ]
        for h in handles
    ]
    if len(pdf_handles) == 2:
        compose_payload = {
            "pdfs": [
                {"pdf_handle": pdf_handles[0]},
                {
                    "pdf_handle": pdf_handles[1],
                    "pages": [{"page_number": 0}, {"page_number": 2}],
                },
            ]
        }
    else:
        compose_payload = {"pdfs": [{"pdf_handle": h} for h in pdf_handles]}
    composed = run_job("pdf/compose", compose_payload, auth)
    pdf_handle = composed.get("pdf_handle") or composed.get("response", {}).get(
        "pdf_handle"
    )
    oriented = run_job("pdf/orientation", {"pdf_handle": pdf_handle}, auth)
    rotated_handle = oriented["rotated_pdf_handle"]
    Path("merged.pdf").write_bytes(download_pdf(rotated_handle, auth))
    print("merged.pdf created")


if __name__ == "__main__":
    main()

Summary and Next Steps

An API for merging and splitting PDFs with orientation correction and thumbnails is ready to use. MaraDocs handles validation, composition, orientation and optimization in a single workflow. For more information, see: Document Scanner, Automatic Rotation, PDF Compression and Image on Blank Page.


Try it now: MaraDocs API | TypeScript SDK


Subscribe to our newsletter

Stay up to date with us and receive the latest news, articles, and resources by email.