DocuTray

Splitting a File into Documents

Split a scanned bundle into documents with Docutray: send the file and candidate types to split-async, read the typed page-range segments, then crop each segment and convert it. Runnable Python and Node.js examples.

A single file often holds several documents: a scanned batch of invoices and receipts, an expense report with its supporting documents, a bundle with a cover sheet and separator pages, a photo of three receipts on a table. Conversion and identification assume one document per file. Split finds where each document starts and ends, and tells you its type.

Split returns segments: one per document, with its page range, its document type chosen among the candidates you send and, in beta, the regions where it sits on each page. It does not extract data. To get the data of each document, crop it and convert it with that segment's document type, as the examples below do.

How split works

  1. You send the file and a list of candidate document types to POST /api/split-async. The API answers 202 with a split_id.
  2. Docutray finds every document on every page, classifies it among your candidates, and decides where each document begins and ends, including documents that share a page.
  3. You poll GET /api/split-async/status/{id}, or receive the SPLIT_* webhooks, until the status is SUCCESS or FAILED.
  4. On SUCCESS, segments covers every page of the file, in order.

Split is asynchronous only: there is no synchronous endpoint.

Start a split

FieldRequiredDescription
image / image_base64 / image_urlYesThe file, as a multipart upload, base64 (a data URI is accepted) or a public URL.
document_type_code_optionsYes1 to 20 distinct document type codes your organization can use. In multipart, a JSON array sent as a string.
document_metadataNoA JSON object returned as-is in the status and in the webhooks, up to 64 KB serialized as JSON. The key _split is reserved.
image_content_typeNoMIME type for image_base64 or image_url, when it cannot be detected.
curl -X POST https://app.docutray.com/api/split-async \
  -H "Authorization: Bearer YOUR_API_KEY" \
  -F "image=@bundle.pdf" \
  -F 'document_type_code_options=["factura", "boleta"]' \
  -F 'document_metadata={"batch": "2026-12-01"}'
202 Accepted
{
  "split_id": "cm5vm9hx30001m5cgh0p9v8qa",
  "status_url": "https://app.docutray.com/api/split-async/status/cm5vm9hx30001m5cgh0p9v8qa",
  "status": "ENQUEUED"
}

Candidates and the otro type

document_type_code_options lists the document types the file may contain. Send only the types you expect: fewer candidates mean fewer chances to confuse two similar types. Every code must be a document type your organization can use; otherwise the request fails with 403 and names the codes it cannot access.

Do not include otro in the list. It is always a candidate and marks pages that match none of your types: cover sheets, separator pages, blank pages, or documents of a type you did not list. Sending otro is rejected with 400.

Supported files

  • PDF up to 100 pages. A longer PDF is rejected with 422, and the message gives its page count and the limit. Split it into parts of at most 100 pages first.
  • Images: JPEG, PNG, GIF, BMP, WebP and single-page TIFF. An image is a one-page file, so its result is a single segment.
  • A multi-page TIFF is rejected with 422: convert it to PDF first.
  • Password-protected or unreadable PDFs are rejected with 422.

Check the status

curl https://app.docutray.com/api/split-async/status/cm5vm9hx30001m5cgh0p9v8qa \
  -H "Authorization: Bearer YOUR_API_KEY"

The status moves from ENQUEUED to PROCESSING, and ends in SUCCESS or FAILED. Poll every 2 to 3 seconds and stop at a final status. Status endpoints have their own rate limit budget, so polling does not use up the budget for starting splits.

SUCCESS
{
  "split_id": "cm5vm9hx30001m5cgh0p9v8qa",
  "status": "SUCCESS",
  "page_count": 6,
  "document_type_code_options": ["factura", "boleta"],
  "document_metadata": { "batch": "2026-12-01" },
  "request_timestamp": "2026-12-01T12:00:00.000Z",
  "response_timestamp": "2026-12-01T12:00:21.000Z",
  "segments": [
    {
      "index": 0,
      "document_type": {
        "code": "otro",
        "name": "Otro/No identificado",
        "confidence_level": "high",
        "evidence": "Cover sheet with no document data"
      },
      "pages": { "start": 1, "end": 1 },
      "regions": [{ "page": 1, "box": { "x0": 0, "y0": 0, "x1": 1, "y1": 1 } }],
      "flags": { "multiple_documents_on_page": false }
    },
    {
      "index": 1,
      "document_type": {
        "code": "factura",
        "name": "Factura",
        "confidence_level": "medium",
        "evidence": "Invoice header with folio 1234"
      },
      "pages": { "start": 2, "end": 4 },
      "regions": [
        { "page": 2, "box": { "x0": 0, "y0": 0, "x1": 1, "y1": 1 } },
        { "page": 3, "box": { "x0": 0, "y0": 0, "x1": 1, "y1": 1 } },
        { "page": 4, "box": { "x0": 0, "y0": 0, "x1": 1, "y1": 0.43 } }
      ],
      "flags": { "multiple_documents_on_page": true }
    },
    {
      "index": 2,
      "document_type": {
        "code": "boleta",
        "name": "Boleta",
        "confidence_level": "high",
        "evidence": "Receipt that starts halfway down page 4"
      },
      "pages": { "start": 4, "end": 6 },
      "regions": [
        { "page": 4, "box": { "x0": 0, "y0": 0.45, "x1": 1, "y1": 1 } },
        { "page": 5, "box": { "x0": 0, "y0": 0, "x1": 1, "y1": 1 } },
        { "page": 6, "box": { "x0": 0, "y0": 0, "x1": 1, "y1": 1 } }
      ],
      "flags": { "multiple_documents_on_page": true }
    }
  ]
}
FAILED
{
  "split_id": "cm5vm9hx30001m5cgh0p9v8qa",
  "status": "FAILED",
  "page_count": 6,
  "document_type_code_options": ["factura", "boleta"],
  "document_metadata": { "batch": "2026-12-01" },
  "request_timestamp": "2026-12-01T12:00:00.000Z",
  "response_timestamp": "2026-12-01T12:00:40.000Z",
  "error": "The model did not return one valid entry per page"
}

Only the API key's own user can read a split. A split started by another user, or by another organization, answers 403; an unknown id answers 404.

Read the segments

Segments follow the file in order and cover every page, with no gaps: the first starts at page 1 and the last ends at page_count. A page can hold more than one document, so two consecutive segments can share a page: the page where one document ends and the next one starts, or a photo or scan with several documents side by side. A photo of three receipts gives three segments, each with "pages": { "start": 1, "end": 1 }. Pages strictly inside a segment belong to that segment only.

FieldDescription
indexPosition of the segment, starting at 0.
document_type.codeOne of your candidates, or otro.
document_type.nameThe name of the document type.
document_type.confidence_levelhigh, medium or low: the lowest confidence among the parts of the segment.
document_type.evidenceA short explanation of why a new document starts where the segment starts. May be null.
pages.start, pages.endFirst and last page of the segment. 1-based and inclusive: { "start": 2, "end": 4 } is pages 2, 3 and 4.
regionsBeta. Where the document is on each of its pages: a list of { "page", "box": { "x0", "y0", "x1", "y1" } }, or null when no location is known. See Regions.
flags.multiple_documents_on_pagetrue when a page of the segment has more than one part (more than one region): parts of other documents, or several parts of this same document, such as the front and back of an ID card photographed on one page.

Two documents of the same type in a row are two segments: split separates them when the second one starts, for example a new invoice with its own header and folio. A low confidence is a good reason to send the segment to manual review before you act on it.

Regions

regions is in beta: it was measured on a synthetic set of photos and scans. Review the segments with flags.multiple_documents_on_page before you rely on them in production.

Each region is one part of the document on one page, in reading order. A page appears more than once when the document has several parts on it, like the front and back of an ID card photographed side by side.

  • Coordinates go from 0 to 1, relative to the width and height of the page as it is displayed, with the origin at the top-left corner: the same format as the field_locations of a conversion. For a PDF, the page has its rotation (/Rotate) applied and is cut to its crop box, as a PDF viewer shows it. For an image, its EXIF orientation is applied, as a photo viewer shows it.
  • The box has no margin. Add one before you crop (see Crop by region).
  • A whole page is { "x0": 0, "y0": 0, "x1": 1, "y1": 1 }: when a page holds a single document that covers it, its box is normalized to the full page.
  • regions is null when no location is known: splits finished before regions existed, or when every box of the segment was discarded. If Docutray cannot locate the documents of a shared page, it merges the segments that share it into one, with regions: null and flags.multiple_documents_on_page: true, so you never receive two segments that overlap without a way to tell them apart.
  • A page of pages without a region in that segment is never shared with another segment: send it whole.

Crop by region

To crop a region:

  1. Add a margin of 2 % of the page width and height on each side and keep the result inside the page (clamp each coordinate to [0, 1]). The boxes are tight, and the margin keeps the edges of the paper.
  2. Multiply by the size of the page as displayed (in pixels for an image or a rendered PDF page) and crop.
def expand(box, margin=0.02):
    return {"x0": max(0.0, box["x0"] - margin), "y0": max(0.0, box["y0"] - margin),
            "x1": min(1.0, box["x1"] + margin), "y1": min(1.0, box["y1"] + margin)}

A box is a rectangle aligned with the page. When documents overlap or sit very close (receipts scattered on a table), the crop can include part of a neighbor. The conversion of that crop still extracts the document in its center, but review those results.

Extract each segment

Split tells you where each document is. To get its data, crop the document and send the crop to /api/convert-async with the segment's document_type.code. Skip otro segments: they have no document type to extract.

The scripts below do the whole flow: start the split, wait for it, crop every segment that is not otro, and start one conversion per segment. For each segment:

  • regions is null, or every region is a whole page: they send the segment's pages. For a PDF, a new PDF with those pages, without rendering them; for an image, the file as is.
  • Otherwise they crop by region. A PDF page is rendered at 200 dpi first (with pypdfium2 in Python and pdf.js in Node.js); an image is read with its EXIF orientation applied. One region gives a PNG; several regions, or regions plus whole pages, give a PDF with one page per region. A page without a region is sent whole.
  • A TIFF with partial regions in Node.js is sent whole, with a warning: @napi-rs/canvas does not decode TIFF. The Python script crops it.

Setting the crop box of a PDF page to the region, without rendering it, extracts the same data, but the cropped PDF still carries the whole page, other documents included, so the scripts render the page instead.

The scripts keep the split_id and the segment index in each conversion's document_metadata, so you can trace every conversion back to its place in the file.

Requires Python 3.9+ and pip install requests pypdf pypdfium2 Pillow cryptography (pypdf needs cryptography to read PDFs encrypted with AES, such as those with only an owner password, which Docutray accepts).

split_and_convert.py
"""Split a file with Docutray and convert each document with its document type.

Usage: DOCUTRAY_API_KEY=... python split_and_convert.py bundle.pdf factura boleta
"""
import io
import json
import os
import sys
import time

import pypdfium2 as pdfium
import requests
from PIL import Image, ImageOps
from pypdf import PdfReader, PdfWriter

BASE_URL = os.environ.get("DOCUTRAY_BASE_URL", "https://app.docutray.com")
HEADERS = {"Authorization": f"Bearer {os.environ['DOCUTRAY_API_KEY']}"}
MARGIN = 0.02  # 2 % of the page width and height on each side
RENDER_DPI = 200  # resolution of the PDF pages that are cropped by region
FULL_PAGE = {"x0": 0, "y0": 0, "x1": 1, "y1": 1}
MIME_TYPES = {".pdf": "application/pdf", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".png": "image/png",
              ".webp": "image/webp", ".gif": "image/gif", ".bmp": "image/bmp", ".tif": "image/tiff",
              ".tiff": "image/tiff"}


def start_split(path, codes):
    with open(path, "rb") as f:
        response = requests.post(
            f"{BASE_URL}/api/split-async",
            headers=HEADERS,
            files={"image": (os.path.basename(path), f, mime_type(path))},
            data={"document_type_code_options": json.dumps(codes)},
        )
    response.raise_for_status()
    return response.json()["split_id"]


def wait_for_split(split_id, interval=2):
    while True:
        response = requests.get(f"{BASE_URL}/api/split-async/status/{split_id}", headers=HEADERS)
        response.raise_for_status()
        split = response.json()
        if split["status"] in ("SUCCESS", "FAILED"):
            return split
        time.sleep(interval)


def mime_type(path):
    return MIME_TYPES[os.path.splitext(path)[1].lower()]


def expand(box, margin=MARGIN):
    """The region plus the margin on each side, kept inside the page."""
    return {"x0": max(0.0, box["x0"] - margin), "y0": max(0.0, box["y0"] - margin),
            "x1": min(1.0, box["x1"] + margin), "y1": min(1.0, box["y1"] + margin)}


def pieces(segment):
    """What to send for a segment, in order: (page, box) pairs; box None means the whole page.

    A page of the segment without a region is sent whole: Docutray never puts a page
    without a region in two segments. With `regions` null every page is sent whole.
    """
    regions = segment["regions"] or []
    result = []
    for page in range(segment["pages"]["start"], segment["pages"]["end"] + 1):
        boxes = [region["box"] for region in regions if region["page"] == page]
        if not boxes:
            result.append((page, None))
        for box in boxes:
            result.append((page, None if box == FULL_PAGE else box))
    return result


def page_image(path, page):
    """The page as displayed: PDF rotation and crop box applied, EXIF orientation applied to images."""
    if mime_type(path) == "application/pdf":
        pdf = pdfium.PdfDocument(path)
        image = pdf[page - 1].render(scale=RENDER_DPI / 72).to_pil()
        pdf.close()
        return image.convert("RGB")
    with Image.open(path) as image:
        return ImageOps.exif_transpose(image).convert("RGB")


def crop(image, box):
    width, height = image.size
    box = expand(box)
    return image.crop((round(box["x0"] * width), round(box["y0"] * height),
                       round(box["x1"] * width), round(box["y1"] * height)))


def segment_file(path, segment):
    """(bytes, extension, MIME type) to convert for a segment."""
    parts = pieces(segment)
    if all(box is None for _, box in parts):
        if mime_type(path) != "application/pdf":
            with open(path, "rb") as f:  # an image is a single page: send it as is
                return f.read(), os.path.splitext(path)[1].lower(), mime_type(path)
        reader, writer = PdfReader(path), PdfWriter()
        for page, _ in parts:
            writer.add_page(reader.pages[page - 1])
        output = io.BytesIO()
        writer.write(output)
        return output.getvalue(), ".pdf", "application/pdf"

    images = [page_image(path, page) if box is None else crop(page_image(path, page), box) for page, box in parts]
    output = io.BytesIO()
    if len(images) == 1:
        images[0].save(output, "PNG")
        return output.getvalue(), ".png", "image/png"
    images[0].save(output, "PDF", resolution=RENDER_DPI, save_all=True, append_images=images[1:])
    return output.getvalue(), ".pdf", "application/pdf"


def convert_segment(content, filename, content_type, code, metadata):
    response = requests.post(
        f"{BASE_URL}/api/convert-async",
        headers=HEADERS,
        files={"image": (filename, content, content_type)},
        data={"document_type_code": code, "document_metadata": json.dumps(metadata)},
    )
    response.raise_for_status()
    return response.json()["conversion_id"]


def main(path, codes):
    split_id = start_split(path, codes)
    split = wait_for_split(split_id)
    if split["status"] == "FAILED":
        sys.exit(f"Split {split_id} failed: {split['error']}")

    for segment in split["segments"]:
        code = segment["document_type"]["code"]
        start, end = segment["pages"]["start"], segment["pages"]["end"]
        if code == "otro":
            print(f"Pages {start}-{end}: otro, skipped")
            continue
        content, extension, content_type = segment_file(path, segment)
        filename = f"segment-{segment['index']}-{code}{extension}"
        metadata = {"split_id": split_id, "segment_index": segment["index"]}
        conversion_id = convert_segment(content, filename, content_type, code, metadata)
        print(f"Pages {start}-{end}: {code}, conversion {conversion_id}")


if __name__ == "__main__":
    main(sys.argv[1], sys.argv[2:])

Both scripts run in Docutray's test suite against a stand-in for the API, which checks that each conversion receives exactly the pages or the crops of its segment, with the 2 % margin.

Then follow each conversion as usual: poll /api/convert-async/status/{conversion_id} or subscribe to the conversion webhooks.

Each conversion is billed on its own, by the pages you send: a PNG crop is one page, and a PDF with one page per region counts those pages. Cropping the segment keeps that to the document, and skipping otro segments avoids paying for cover sheets and blank pages.

Webhooks

Subscribe a webhook to the split events in Settings > Webhooks, as described in Webhook Configuration. Requests are signed like every other Docutray webhook: see Security and Verification. The X-Docutray-Event header names the event.

EventSent whenstatus
SPLIT_STARTEDDocutray starts processing the split.PROCESSING
SPLIT_COMPLETEDThe split finished; the body carries segments.SUCCESS
SPLIT_FAILEDThe split failed; the body carries error.FAILED

The body has the same fields as the status response, plus original_filename:

SPLIT_COMPLETED
{
  "split_id": "cm5vm9hx30001m5cgh0p9v8qa",
  "status": "SUCCESS",
  "page_count": 6,
  "document_type_code_options": ["factura", "boleta"],
  "document_metadata": { "batch": "2026-12-01" },
  "request_timestamp": "2026-12-01T12:00:00.000Z",
  "original_filename": "bundle.pdf",
  "response_timestamp": "2026-12-01T12:00:21.000Z",
  "segments": [
    {
      "index": 0,
      "document_type": { "code": "otro", "name": "Otro/No identificado", "confidence_level": "high", "evidence": "Cover sheet with no document data" },
      "pages": { "start": 1, "end": 1 },
      "regions": [{ "page": 1, "box": { "x0": 0, "y0": 0, "x1": 1, "y1": 1 } }],
      "flags": { "multiple_documents_on_page": false }
    },
    {
      "index": 1,
      "document_type": { "code": "boleta", "name": "Boleta", "confidence_level": "high", "evidence": "Receipt header, operation 004211" },
      "pages": { "start": 2, "end": 2 },
      "regions": [{ "page": 2, "box": { "x0": 0.05, "y0": 0.1, "x1": 0.3, "y1": 0.4 } }],
      "flags": { "multiple_documents_on_page": true }
    }
  ]
}

A webhook arrives with the data available when it is delivered. Treat webhooks as a signal and read the status when you need the definitive result.

Billing

A split is billed like an identification: a successful split counts the pages of the file against your monthly page quota. A failed split is not billed. The quota is checked when you start the split, with the file's real page count: if the pages do not fit in what is left of your quota, the request fails with 402 and nothing is processed.

Converting the segments afterwards is billed separately, like any conversion.

Limitations

  • regions is in beta. It was measured on a synthetic set of photos and scans (flat paper, even light). Check the segments with flags.multiple_documents_on_page before relying on their crops.
  • Interleaved layouts are not rebuilt. Split reads parts in order, page after page, so documents that advance in parallel across pages get mixed: two documents printed side by side on two pages (two columns), or the fronts of two ID cards on page 1 and their backs on page 2. If both documents have the same type, the result is a one-page segment for the first one and a two-page segment that mixes the second one with both continuations. If their types differ, each part comes out as its own one-page segment. Avoid sending those layouts, or review those segments.
  • Boxes are rectangles aligned with the page. A rotated or overlapping document gets the smallest rectangle that contains it, which can include part of a neighbor.
  • TIFF crops in the Node.js example. @napi-rs/canvas does not decode TIFF, so the Node.js script sends a TIFF with partial regions whole. Convert TIFFs to PNG or PDF first, or use the Python script.
  • A blank back page at the end of a document becomes an otro segment. A blank page between two pages of the same document stays in the document, but a blank page after a document's last page, such as the back of a scanned sheet, comes out as its own otro segment. It costs nothing in the cropping flow, which skips otro segments.
  • At most 100 pages per file, and at most 20 candidates per split.
  • No data extraction. Split only returns segments: convert each one to get its data.

Errors

StatusWhen
400document_type_code_options is missing, empty, has more than 20 codes or includes otro; or document_metadata uses the reserved _split key or is larger than 64 KB.
402The file's pages do not fit in your remaining monthly page quota.
403Some candidates are not accessible to your organization (the message names them), or the split belongs to another user or organization.
404The split does not exist, or the file URL answered 404.
413The file is too large.
415Unsupported content type or file type.
422The file cannot be split: more than 100 pages, a multi-page TIFF, a password-protected or unreadable PDF.
429Rate limit exceeded.

See the full request and response schemas in the API reference: Start asynchronous split and Check asynchronous split status.

On this page