Skip to main content

Overview

PyMuPDF4LLM integrates with LangChain through a custom document loader that wraps to_markdown() and returns LangChain Document objects. Each document carries the page’s Markdown content in its page_content field and PyMuPDF4LLM’s page metadata in its metadata field.

Installation

Make sure PyMuPDF4LLM LangChain is installed:

Basic Usage

PyMuPDF4LLMLoader follows the LangChain BaseLoader interface. Call load() to get a list of Document objects — one per page.

Document Structure

Each Document contains:
  • page_content — the Markdown text of the page
  • metadata — a dictionary of page and document-level metadata
Example metadata:

Building a RAG Pipeline

Combine PyMuPDF4LLMLoader with LangChain’s Chroma vector store and a chat model to build a retrieval-augmented generation pipeline:

Text Splitting

For large documents, split pages into smaller chunks before embedding to improve retrieval precision. LangChain’s MarkdownHeaderTextSplitter is a natural fit because PyMuPDF4LLM output preserves Markdown headings:
MarkdownHeaderTextSplitter produces semantically meaningful chunks by splitting on headings rather than character count. This works especially well with PyMuPDF4LLM output because heading structure is faithfully preserved.
You can also use RecursiveCharacterTextSplitter for a simpler fixed-size approach:

Lazy Loading

For large documents or memory-constrained environments, use lazy_load() to yield documents one at a time rather than loading everything into memory at once:

Loading Multiple Documents

Combine multiple loaders to build an index across a folder of PDFs:

Using with LCEL

PyMuPDF4LLMLoader works naturally inside LangChain Expression Language (LCEL) chains. Here’s a complete retrieval chain using the pipe syntax:

Metadata Filtering

Because each document carries source and page metadata, you can scope retrieval to specific pages or files using metadata filters:

Full Pipeline Example


Next Steps

PyMuPDF Pro

Use PyMuPDF4LLM with Office documents.

Extract Markdown

Full walkthrough of to_markdown() options.

OCR

Enable OCR for scanned PDFs before indexing.