Split a Contract to Fit an OCR Service's Upload Limit

Split a PDF into parts whose saved size in bytes fits an upload limit, keep a map to the original page numbers, and flag any page that exceeds the limit on its own.

December 3, 202611 min readIntermediateOCRSplitPDFFile size

OCR services cap the size of each uploaded file. A long contract with scanned signature pages and exhibits is often over that cap, so it has to go up in parts, and the OCR results that come back, numbered by page within each part, have to be mapped back to the contract's own page numbers.

This notebook does that with PyMuPDF:

  1. Measure every page on its own, and flag any page that is over the limit by itself.
  2. Split the contract into consecutive page ranges whose saved size in bytes fits the limit.
  3. Save the parts, each labelled with its original page numbers, and write a map from every part page to its original page.
  4. Optionally shrink an oversized page's images to 300 dpi, the usual resolution for OCR.
  5. Check the saved parts, and map OCR results back to the original pages.

Tested with PyMuPDF 2.2.

%pip install -q pymupdf
Output
[notice] A new release of pip is available: 26.0.1 -> 26.3
[notice] To update, run: pip install --upgrade pip
Note: you may need to restart the kernel to use updated packages.

Sample document

A 20-page services agreement: 14 pages of clauses, a scanned signature page, three scanned exhibits and two schedules. The scans are stand-ins made of grey noise, which compresses about as badly as a real scan. One exhibit, a site plan, was scanned at 600 dpi and is about 3 MB on its own.

LIMIT is set to 1 MB so that this small sample needs splitting. Set it to your service's limit, in bytes (see "Choosing the limit" below). Replace path with your own contract.

import os

import pymupdf

LIMIT = 1_000_000                                    # bytes per uploaded file

CLAUSES = ["Definitions", "Scope of Services", "Payment Terms", "Term and Renewal", "Service Levels",
           "Personnel", "Confidentiality", "Data Protection", "Intellectual Property", "Warranties",
           "Indemnities", "Limitation of Liability", "Termination", "General"]
BODY = ("{n}.{k} The Supplier shall perform its obligations under this clause with reasonable skill and care, "
        "and each party shall notify the other promptly in writing of any matter that may affect performance. "
        "Nothing in this clause limits any other right or remedy of either party under this Agreement.\n\n")
GREY = bytes(215 + i % 41 for i in range(256))


def text_page(doc, title, n):
    page = doc.new_page()
    text = f"MASTER SERVICES AGREEMENT\n\n{title}\n\n" + "".join(BODY.format(n=n, k=k) for k in range(1, 7))
    assert page.insert_textbox(pymupdf.Rect(72, 72, 523, 770), text, fontsize=11) >= 0


def scanned_page(doc, caption, rect, width, height):
    """A page holding a stand-in for a scanned image: grey noise compresses about as badly as a scan."""
    page = doc.new_page()
    page.insert_text((72, 72), caption, fontsize=14, fontname="hebo")
    pix = pymupdf.Pixmap(pymupdf.csGRAY, width, height, os.urandom(width * height).translate(GREY), False)
    page.insert_image(rect, pixmap=pix)


doc = pymupdf.open()
for n, title in enumerate(CLAUSES, start=1):
    text_page(doc, f"{n}. {title}", n)
scanned_page(doc, "Signature page (scanned)", pymupdf.Rect(72, 100, 523, 400), 900, 600)
scanned_page(doc, "Exhibit A: Certificate of insurance (scanned)", pymupdf.Rect(72, 100, 523, 500), 800, 700)
scanned_page(doc, "Exhibit B: Bank details (scanned)", pymupdf.Rect(72, 100, 523, 500), 800, 700)
scanned_page(doc, "Exhibit C: Site plan (scanned at 600 dpi)", pymupdf.Rect(72, 100, 360, 316), 2400, 1800)
text_page(doc, "Schedule 1: Pricing", 15)
text_page(doc, "Schedule 2: Contacts", 16)
doc.set_metadata({"title": "Master Services Agreement"})
doc.save("contract.pdf", garbage=3, deflate=True)

path = "contract.pdf"
doc = pymupdf.open(path)
print(f"{path}: {doc.page_count} pages, {os.path.getsize(path):,} bytes")
Output
contract.pdf: 20 pages, 4,167,599 bytes

Step 1: Measure every page on its own

The size of a part cannot be estimated reliably from the pages in it. Fonts and images shared by several pages are stored once in the original but copied into every part that uses them, and compression depends on what ends up together. So the notebook measures what will actually be uploaded: it builds each candidate part and saves it to bytes.

make_part() builds a part exactly as it will be saved, including its metadata and page labels, so the bytes measured are the bytes uploaded. A page that is over the limit on its own can never fit in any part. It is flagged, and its images are listed with their resolution, which shows whether it can be made smaller.

def make_part(doc, first, last):
    """Pages first..last (0-based) as a PDF, exactly as it will be uploaded. Returns the bytes."""
    part = pymupdf.open()
    part.insert_pdf(doc, from_page=first, to_page=last)
    title = doc.metadata.get("title") or os.path.basename(doc.name)
    part.set_metadata({"title": f"{title} (pages {first + 1}-{last + 1})",
                       "subject": f"Pages {first + 1}-{last + 1} of {os.path.basename(doc.name)}"})
    # viewers show the original page numbers
    part.set_page_labels([{"startpage": 0, "prefix": "", "style": "D", "firstpagenum": first + 1}])
    return part.tobytes(garbage=3, deflate=True)


def images_on(page):
    """Each image on the page with its pixel size and effective resolution."""
    out = []
    for info in page.get_image_info():
        width_in = pymupdf.Rect(info["bbox"]).width / 72
        dpi = round(info["width"] / width_in) if width_in else 0
        out.append(f'{info["width"]} x {info["height"]} px at {dpi} dpi')
    return out


page_bytes = [len(make_part(doc, p, p)) for p in range(doc.page_count)]
oversized = [p for p, size in enumerate(page_bytes) if size > LIMIT]

for p, size in enumerate(page_bytes):
    flag = "  OVER LIMIT on its own" if size > LIMIT else ""
    print(f"page {p + 1:2}  {size:>10,} bytes{flag}")
for p in oversized:
    print(f"\npage {p + 1} images:", "; ".join(images_on(doc[p])) or "none")
Output
page  1       1,530 bytes
page  2       1,541 bytes
page  3       1,538 bytes
page  4       1,541 bytes
page  5       1,541 bytes
page  6       1,534 bytes
page  7       1,540 bytes
page  8       1,540 bytes
page  9       1,548 bytes
page 10       1,543 bytes
page 11       1,543 bytes
page 12       1,548 bytes
page 13       1,541 bytes
page 14       1,540 bytes
page 15     378,366 bytes
page 16     392,275 bytes
page 17     392,286 bytes
page 18   3,000,376 bytes  OVER LIMIT on its own
page 19       1,552 bytes
page 20       1,552 bytes

page 18 images: 2400 x 1800 px at 600 dpi

Page 18, the site plan, is about three times the limit on its own: its scan is 2400 x 1800 pixels at 600 dpi. Step 4 shows how to bring it down to 300 dpi.

Step 2: Split into parts that fit

The contract is split into consecutive page ranges, so every part reads in order. Each part grows one page at a time for as long as the saved part still fits. The page that would push it over starts the next part. A page that is over the limit on its own ends up in a part by itself, flagged, so it never drags other pages over the limit with it.

Some services also limit the number of pages per file; pass max_pages for that.

def split_to_limit(doc, limit, max_pages=None):
    """Consecutive page ranges whose saved size fits the limit, as dicts with first, last and data."""
    parts, first = [], 0
    while first < doc.page_count:
        last, data = first, make_part(doc, first, first)
        while last + 1 < doc.page_count and (max_pages is None or last + 2 - first <= max_pages):
            bigger = make_part(doc, first, last + 1)
            if len(bigger) > limit:
                break
            last, data = last + 1, bigger
        parts.append({"first": first, "last": last, "data": data})
        first = last + 1
    return parts


parts = split_to_limit(doc, LIMIT)
for i, p in enumerate(parts, start=1):
    flag = "  OVER LIMIT" if len(p["data"]) > LIMIT else ""
    print(f'part {i}: pages {p["first"] + 1}-{p["last"] + 1}  {len(p["data"]):>10,} bytes{flag}')
Output
part 1: pages 1-16     779,505 bytes
part 2: pages 17-17     392,286 bytes
part 3: pages 18-18   3,000,376 bytes  OVER LIMIT
part 4: pages 19-20       2,400 bytes

The clauses and the first two scans fit in part 1. Exhibit B on its own is part 2, because adding the site plan would exceed the limit. The site plan is part 3 by itself, flagged, and the schedules make part 4.

Step 3: Save the parts and the page map

Each part is saved with its page range in the file name, and with page labels, so a viewer shows the contract's own page numbers: part 4 opens at page 19. A manifest.json lists the pages that are over the limit on their own and records, for every part, its file, size in bytes, SHA-256 hash, page range and whether it is over the limit, plus a map from every original page to its part and page within the part. Keep the manifest with the OCR job: it is what turns results back into contract page numbers.

import hashlib
import json

OUT = "parts"


def save_parts(doc, parts, limit, page_bytes, out=OUT):
    os.makedirs(out, exist_ok=True)
    stem = os.path.splitext(os.path.basename(doc.name))[0]
    for name in os.listdir(out):                     # remove parts from an earlier run
        if name.startswith(f"{stem}_part") and name.endswith(".pdf"):
            os.remove(os.path.join(out, name))
    manifest = {"source": os.path.basename(doc.name), "source_pages": doc.page_count,
                "source_sha256": hashlib.sha256(open(doc.name, "rb").read()).hexdigest(),
                "limit_bytes": limit,
                "oversized_pages": [{"page": p + 1, "bytes": b} for p, b in enumerate(page_bytes) if b > limit],
                "parts": [], "page_map": {}}
    for i, p in enumerate(parts, start=1):
        name = f'{stem}_part{i:02d}_p{p["first"] + 1:03d}-{p["last"] + 1:03d}.pdf'
        with open(os.path.join(out, name), "wb") as f:
            f.write(p["data"])
        manifest["parts"].append({"part": i, "file": name, "first_page": p["first"] + 1,
                                  "last_page": p["last"] + 1, "pages": p["last"] - p["first"] + 1,
                                  "bytes": len(p["data"]), "sha256": hashlib.sha256(p["data"]).hexdigest(),
                                  "over_limit": len(p["data"]) > limit})
        for k, pno in enumerate(range(p["first"], p["last"] + 1), start=1):
            manifest["page_map"][str(pno + 1)] = {"part": i, "page": k}
    return manifest


def write_manifest(manifest, out=OUT):
    with open(os.path.join(out, "manifest.json"), "w") as f:
        json.dump(manifest, f, indent=2)


manifest = save_parts(doc, parts, LIMIT, page_bytes)
write_manifest(manifest)
for p in manifest["parts"]:
    flag = "  OVER LIMIT" if p["over_limit"] else ""
    print(f'{p["file"]:32} {p["bytes"]:>10,} bytes  pages {p["first_page"]}-{p["last_page"]}{flag}')
print("\noversized pages:", manifest["oversized_pages"])
print("original page 18 ->", manifest["page_map"]["18"])
Output
contract_part01_p001-016.pdf        779,505 bytes  pages 1-16
contract_part02_p017-017.pdf        392,286 bytes  pages 17-17
contract_part03_p018-018.pdf      3,000,376 bytes  pages 18-18  OVER LIMIT
contract_part04_p019-020.pdf          2,400 bytes  pages 19-20

oversized pages: [{'page': 18, 'bytes': 3000376}]
original page 18 -> {'part': 3, 'page': 1}

Step 4 (optional): Shrink an oversized page

An oversized page is usually a high-resolution scan. OCR engines work well at about 300 dpi, so images above that can be downsampled with Document.rewrite_images() without hurting recognition. Only the flagged parts are changed, and only their images above 300 dpi; the original contract is not touched.

If a part is still over the limit at 300 dpi, it stays flagged. Going lower costs OCR accuracy, so the options are to send that page through the service's image endpoint, split the scan, or ask for a higher limit. The page stays listed in oversized_pages, and the manifest records which parts were downsampled and their size before, so OCR results from them can be judged accordingly.

OCR_DPI = 300


def shrink_images(data, dpi=OCR_DPI):
    """The part with every image above dpi resampled to dpi. Metadata and page labels are kept."""
    part = pymupdf.open("pdf", data)
    part.rewrite_images(dpi_threshold=dpi + 1, dpi_target=dpi)
    return part.tobytes(garbage=3, deflate=True)


for entry, p in zip(manifest["parts"], parts):
    if not entry["over_limit"]:
        continue
    smaller = shrink_images(p["data"])
    print(f'part {entry["part"]}: {len(p["data"]):,} -> {len(smaller):,} bytes at {OCR_DPI} dpi', end="")
    if len(smaller) <= LIMIT:
        p["data"] = smaller
        with open(os.path.join(OUT, entry["file"]), "wb") as f:
            f.write(smaller)
        entry.update(bytes_before=entry["bytes"], bytes=len(smaller), sha256=hashlib.sha256(smaller).hexdigest(), over_limit=False,
                     images_downsampled_to_dpi=OCR_DPI)
        print(", now fits")
    else:
        print(", still over the limit: send it another way")
write_manifest(manifest)
Output
part 3: 3,000,376 -> 865,844 bytes at 300 dpi, now fits

Step 5: Check the saved parts

Before uploading, re-open every saved file and check it against the manifest and the original: the size on disk, the page count, the page labels, and that each page's text is the same as in the contract. Together the parts must hold every page exactly once.

def check_parts(doc, manifest, out=OUT):
    covered = []
    for p in manifest["parts"]:
        file = os.path.join(out, p["file"])
        part = pymupdf.open(file)
        assert os.path.getsize(file) == p["bytes"], f'{p["file"]}: size differs from manifest'
        assert part.page_count == p["pages"], f'{p["file"]}: page count differs'
        for k, page in enumerate(part):
            original = p["first_page"] + k
            assert page.get_label() == str(original), f'{p["file"]}: wrong page label'
            assert page.get_text() == doc[original - 1].get_text(), f'{p["file"]}: page {original} differs'
            covered.append(original)
        status = "OVER LIMIT" if p["over_limit"] else "ok"
        print(f'{p["file"]:32} {p["bytes"]:>10,} bytes  {p["bytes"] / manifest["limit_bytes"]:5.0%} of limit  {status}')
    assert covered == list(range(1, doc.page_count + 1)), "parts do not cover every page exactly once"
    print(f"\n{len(manifest['parts'])} parts, {len(covered)} pages, all checks passed")


check_parts(doc, manifest)
Output
contract_part01_p001-016.pdf        779,505 bytes    78% of limit  ok
contract_part02_p017-017.pdf        392,286 bytes    39% of limit  ok
contract_part03_p018-018.pdf        865,844 bytes    87% of limit  ok
contract_part04_p019-020.pdf          2,400 bytes     0% of limit  ok

4 parts, 20 pages, all checks passed

Step 6: Map OCR results back to the contract

OCR results come back per part, numbered by page within the part. The manifest turns each into the contract's page number. Here, each part's own text layer stands in for the OCR output, so the result can be checked against the original.

def to_original(manifest, part, page):
    """Original page number (1-based) of page `page` in part `part`."""
    p = manifest["parts"][part - 1]
    if not 1 <= page <= p["pages"]:
        raise ValueError(f'part {part} has {p["pages"]} pages, not {page}')
    return p["first_page"] + page - 1


ocr_results = []                                     # stand-in for the OCR service's response
for p in manifest["parts"]:
    for k, page in enumerate(pymupdf.open(os.path.join(OUT, p["file"])), start=1):
        ocr_results.append({"part": p["part"], "page": k, "text": page.get_text()})

for r in ocr_results:
    r["original_page"] = to_original(manifest, r["part"], r["page"])
    assert r["text"] == doc[r["original_page"] - 1].get_text()

for r in ocr_results[13:]:
    lines = [l for l in r["text"].split("\n") if l.strip() and l != "MASTER SERVICES AGREEMENT"]
    first_line = lines[0] if lines else "(no text layer: scanned)"
    print(f'part {r["part"]} page {r["page"]} -> contract page {r["original_page"]:2}  {first_line}')
Output
part 1 page 14 -> contract page 14  14. General
part 1 page 15 -> contract page 15  Signature page (scanned)
part 1 page 16 -> contract page 16  Exhibit A: Certificate of insurance (scanned)
part 2 page 1 -> contract page 17  Exhibit B: Bank details (scanned)
part 3 page 1 -> contract page 18  Exhibit C: Site plan (scanned at 600 dpi)
part 4 page 1 -> contract page 19  Schedule 1: Pricing
part 4 page 2 -> contract page 20  Schedule 2: Contacts

Choosing the limit

  • Bytes, not megabytes. Check whether the service means 10 MB as 10,000,000 bytes or 10 MiB (10,485,760 bytes), and set LIMIT in bytes.
  • Base64 adds a third. If the file is sent inside a JSON request as base64, the encoded size is about 4/3 of the file size, so use LIMIT = service_limit * 3 // 4.
  • Leave a margin when the limit applies to the whole request, including form fields and headers.

Limits to know

  • Each part is saved again for every page it grows by, so splitting a document with hundreds of large pages takes a while. For long documents, start each part with a guess from the single-page sizes and measure only near the limit.
  • Parts are consecutive page ranges. That keeps every part readable and the page map simple, but it can leave a part much smaller than the limit, like part 2 here.
  • Links between pages in different parts, bookmarks and form fields that span pages do not survive the split. OCR does not need them; keep the original for everything else.
  • rewrite_images() changes image data in the uploaded copy only. Record it, as the manifest does, wherever OCR text is used as evidence.

Next steps


Discuss This Article with the Community

Have a question, a different approach, or something you built after reading this? Share it on the forum or join the Discord, we'd love to hear from you.

PyMuPDF Logo

© 2026 Artifex Software Inc. All rights reserved.