Skip to main content

Overview

PyMuPDF4LLM’s extraction functions return strings or Python objects — writing them to disk is handled by standard Python. The recommended approach is pathlib.Path, which is clean, cross-platform, and available in the standard library with no additional dependencies.

Saving Markdown

Always specify encoding="utf-8" when writing text files to ensure special characters, symbols, and non-Latin scripts are preserved correctly.

Saving JSON

Use Python’s built-in json module to serialise the output before writing:
indent=2 produces human-readable JSON. For large documents where file size matters, omit it to write compact single-line JSON:

Saving Plain Text


Saving Page Chunks

When using page_chunks=True, you’ll typically want to save each page as a separate file. Use the page number from the chunk metadata to name each file:

Saving with a Matching Filename

To derive the output filename from the input document automatically:
Path.with_suffix() swaps the file extension cleanly, keeping the same directory and stem.

Saving to a Different Directory

To write output to a different folder while keeping the original filename:

Processing Multiple Files

To extract and save output for an entire folder of PDFs:

Saving Images Alongside Markdown

When write_images=True is used, images are written to disk automatically during extraction:
Image paths in the Markdown output are relative to wherever the .md file is opened from. Keep your Markdown file and image directory in the same parent folder to ensure image links resolve correctly.

File Format Summary


Next Steps

Extract Markdown

Full walkthrough of to_markdown() with all common options.

Extract JSON

Bounding boxes and layout data for custom pipelines.

Extract Text

Plain text extraction and whitespace handling.

Images & Graphics

Controlling image extraction, DPI, format, and output path.