Batch PDF Parsing: Let Each Process Open Its Own File

Multi-process tasks should pass serializable parameters, with each worker process independently opening the document rather than sharing Document or Page object

Working with large PDFs often means splitting the job across several processes. Done carelessly, this crashes workers, corrupts output, or quietly loses pages. This guide is for developers who process PDFs in Python and want parallel extraction that stays reliable.

The core idea is simple: pass only plain values to each worker, and let each worker open the file itself. They do not guarantee results on every real file, so keep your originals and verify output against the criteria below before you rely on it.

By the end, you will know why sharing Document or Page objects fails, what a safe task parameter looks like, which edge cases to guard against, and where a manual review is still needed.

How do you run PDF work in parallel safely? The short answer

Send each worker only serializable parameters, such as a filename string and page numbers, and let each worker open the document itself.

Your situationWhat to doWhy
You want to split a PDF across processesPass (segment_id, filename, start_page, end_page) to each workerPlain strings and integers can be serialized and sent safely
You are tempted to pass a Document objectDo not pass it; pass the filename insteadDocument holds handles bound to the creating process, so it breaks across processes
A page range may exceed the documentCheck the range against doc.page_count at the worker entry pointPrevents index-out-of-bounds errors
Several workers write to one output fileGive each worker its own temporary file, then merge in the main processAvoids interleaved or corrupted content
Pages are scanned imagesAdd an OCR stepPlain-text extraction may return nothing for pages without a text layer

Why can't you pass a Document object to a child process?

The root cause is that Document internally holds pointers to underlying C structures and file handles. These resources belong to the memory space of the process that created them. Once the object crosses a process boundary, the pointers become invalid, and another process cannot use the handles legally.

The correct approach is to pass only serializable parameters, such as the filename and a page range. Each child process then calls pymupdf.open() inside its own memory space. This is not a performance defect. A child process is an independent entity, so it needs its own document instance to extract or render safely in any case.

Correct input and dangerous boundaries

Correct input

Pass a tuple such as (segment_id, filename, start_page, end_page):

  • filename is a string path.
  • start_page and end_page are integers.

On receipt, the child process opens the file itself, processes its page range, and returns a list of results.

Error and boundary cases

  • Out-of-range pages: If you pass (18, 25) but the document actually contains only 20 pages, the child process triggers an index-out-of-bounds error when it accesses page 21, because that page does not exist.
  • Passing a Document object: This is a common mistake. It is interrupted by a pickle failure.
  • Concurrent writes: If several child processes write to the same output file at once, the content can interleave or become corrupted unless you add synchronization.

To handle these cases:

  1. Check the page range at the child process entry point against doc.page_count.
  2. Give every I/O operation its own target path or memory buffer.
  3. Exclude non-serializable objects from task parameters at design time. Do not rely on runtime exception handling to catch them.

Complete Python example and dependencies

The example is self-contained. Its dependencies are listed in the import section, and it builds its inputs in memory. The example runs invocations serially so the code stays easy to audit. It demonstrates safe segmentation and independently opened worker functions, not multi-process performance.

import pymupdf
def partition(total, chunk):
    if type(chunk) is not int or chunk <= 0:
        raise ValueError("positive chunk required")
    return [(start, min(start + chunk, total)) for start in range(0, total, chunk)]
def worker(raw, start, end):
    with pymupdf.open(stream=raw, filetype="pdf") as doc:
        return [(i, doc[i].get_text()) for i in range(start, end)]
with pymupdf.open() as doc:
    for index in range(5):
        doc.new_page().insert_text((50, 50), f"Page {index}")
    raw = doc.tobytes()
tasks = partition(5, 2)
assert tasks == [(0, 2), (2, 4), (4, 5)]
results = [item for start, end in tasks for item in worker(raw, start, end)]
assert [i for i, text in results] == list(range(5))
assert all(f"Page {i}" in text for i, text in results)
assert partition(0, 2) == []

Note: pool.map uses a chunksize of 1 here, which suits tasks with large granularity. If you have a very large number of pages and each one processes quickly, a larger chunksize reduces inter-process communication (IPC) overhead. This example focuses on safety rather than tuning.

Acceptance criteria and manual review boundary

Use the table below to interpret what you observe.

Observation of the phenomenonpossible causesprocessing decision
pickle.PicklingError or the child process silently crashespassed non-serializable objects such as Document/Pageonly passes basic types such as strings, integers, and tuples
section page numbers return an empty stringThe page range exceeds the actual number of pages, or the page is a pure image with no text layervalidates page number boundaries; for pages consisting solely of images, OCR tagging is required (this is expected behavior)
output file content is corruptedmulti-process writing to the same fileEach process writes to its own temporary file, and the main process merges them.
memory usage grows linearly with the number of processesEach process loads the complete documentaccepts this overhead; if the document is too large, switch to paginated streaming processing

Limits of this approach

  • Cross-page context: Do not use this approach for tasks that need cross-page context, such as a table spanning several pages or a full-text index. Each process works in isolation. For these tasks, go back to single-process handling or design a chunking-and-aggregation strategy.
  • Scope of verification: The code only shows safe parallel extraction. It does not prove end-to-end usability. Check text quality, encoding, and how well the format is preserved by sampling and reviewing output yourself.
  • Scanned PDFs: Plain-text extraction may fail completely, so include an OCR step.

Translating documents with this checklist

Before you send a document for translation, confirm that the page order, source locations, and text integrity are correct. Then submit the same sample to the translation process.

After translation, check that headings, body text, and figure captions still correspond correctly. Do not judge the result only by whether the text reads smoothly.

OmniDoc translates PDF, Word, PowerPoint and Excel files: scanned pages are recognized first, table cells are translated one by one so tables keep their rows and columns, and a PDF comes back as both a bilingual and a translation-only file. Paid translation adds a glossary and context translation. The examples here do not measure product performance, and nothing in this guide says OmniDoc uses the open-source libraries or internal algorithms mentioned.

Reference: PyMuPDF multiprocessing recipes

📊 At a glance

ApproachWhat the worker receivesResult
Pass a Document objectA live object bound to the parent processFails with a pickle error or an invalid handle
Pass a filename and page rangePlain strings and integersEach worker opens the file itself and processes its range

🎯 Which approach fits you?

If you process a long PDF in independent page ranges

Use the filename-and-range pattern, and validate each range against doc.page_count in the worker.

If your output goes to one file

Have each worker write to its own temporary file, then merge the results in the main process.

If your pages are scanned images

Add an OCR step, because plain-text extraction may return nothing.

If your task needs context across pages

Stay with single-process handling or design a chunking-and-aggregation strategy.

❓ FAQ

1. Why does passing a Document object to a worker fail?

A Document holds handles tied to the process that created it, so those handles become invalid once they cross a process boundary. Pass the filename instead, and let each worker open the file itself.

2. What should I pass to each worker?

Pass only serializable values, such as (segment_id, filename, start_page, end_page), where the filename is a string and the pages are integers.

3. What happens if the page range is larger than the document?

The worker fails with an index-out-of-bounds error when it reaches a page that does not exist, such as page 21 in a 20-page document. Check the range against doc.page_count at the worker's entry point to prevent this.

4. Can multiple workers write to the same output file?

Not safely without synchronization, because the content can interleave or become corrupted. Give each worker its own temporary file and merge them afterwards.

📝 Summary

Passing plain parameters and letting each worker open the PDF keeps parallel extraction safe. Check page ranges, separate your output files, and review results by hand, especially for scanned or cross-page content.

Try it now: upload a document and get it translated with the layout intact

Updated 2026-11-29