> ## Documentation Index
> Fetch the complete documentation index at: https://nvd-54.mintlify.site/llms.txt
> Use this file to discover all available pages before exploring further.

# PyMuPDF4LLMLoader 集成

> 使用 LangChain Python 集成 PyMuPDF4LLMLoader 文档加载器。

This guide provides a quick overview for getting started with the `PyMuPDF4LLMLoader` [document loader](https://python.langchain.com/docs/concepts/#document-loaders). For detailed documentation of all `PyMuPDF4LLMLoader` features and configurations head to the [GitHub repository](https://github.com/lakinduboteju/langchain-pymupdf4llm).

## 概述

### 集成详情

| Class                                                                         | Package                                                                   | Local | Serializable | JS support |
| :---------------------------------------------------------------------------- | :------------------------------------------------------------------------ | :---: | :----------: | :--------: |
| [`PyMuPDF4LLMLoader`](https://github.com/lakinduboteju/langchain-pymupdf4llm) | [`langchain-pymupdf4llm`](https://pypi.org/project/langchain-pymupdf4llm) |   ✅   |       ❌      |      ❌     |

### 加载器特性

|        Source       | Document Lazy Loading | Native Async Support | Extract Images | Extract Tables |
| :-----------------: | :-------------------: | :------------------: | :------------: | :------------: |
| `PyMuPDF4LLMLoader` |           ✅           |           ❌          |        ✅       |        ✅       |

## 设置

To access PyMuPDF4LLM document loader you'll need to install the `langchain-pymupdf4llm` integration package.

### 凭证

No credentials are required to use PyMuPDF4LLMLoader.

要启用模型调用的自动追踪，请设置你的 [LangSmith](/langsmith/home) API 密钥：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
os.environ["LANGSMITH_API_KEY"] = getpass.getpass("Enter your LangSmith API key: ")
os.environ["LANGSMITH_TRACING"] = "true"
```

### 安装

安装 **langchain-community** and **langchain-pymupdf4llm**。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-community langchain-pymupdf4llm
```

## 初始化

现在我们可以实例化模型对象并加载文档：

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_pymupdf4llm import PyMuPDF4LLMLoader

file_path = "./example_data/layout-parser-paper.pdf"
loader = PyMuPDF4LLMLoader(file_path)
```

## 加载

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
docs = loader.load()
docs[0]
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
Document(metadata={'producer': 'pdfTeX-1.40.21', 'creator': 'LaTeX with hyperref', 'creationdate': '2021-06-22T01:27:10+00:00', 'source': './example_data/layout-parser-paper.pdf', 'file_path': './example_data/layout-parser-paper.pdf', 'total_pages': 16, 'format': 'PDF 1.5', 'title': '', 'author': '', 'subject': '', 'keywords': '', 'moddate': '2021-06-22T01:27:10+00:00', 'trapped': '', 'modDate': 'D:20210622012710Z', 'creationDate': 'D:20210622012710Z', 'page': 0}, page_content='\`\`\`\nLayoutParser: A Unified Toolkit for Deep\n\n## Learning Based Document Image Analysis\n\n\`\`\`\n\nZejiang Shen[1] (�), Ruochen Zhang[2], Melissa Dell[3], Benjamin Charles Germain\nLee[4], Jacob Carlson[3], and Weining Li[5]\n\n1 Allen Institute for AI\n\`\`\`\n              shannons@allenai.org\n\n\`\`\`\n2 Brown University\n\`\`\`\n             ruochen zhang@brown.edu\n\n\`\`\`\n3 Harvard University\n_{melissadell,jacob carlson}@fas.harvard.edu_\n4 University of Washington\n\`\`\`\n              bcgl@cs.washington.edu\n\n\`\`\`\n5 University of Waterloo\n\`\`\`\n              w422li@uwaterloo.ca\n\n\`\`\`\n\n**Abstract. Recent advances in document image analysis (DIA) have been**\nprimarily driven by the application of neural networks. Ideally, research\noutcomes could be easily deployed in production and extended for further\ninvestigation. However, various factors like loosely organized codebases\nand sophisticated model configurations complicate the easy reuse of important innovations by a wide audience. Though there have been on-going\nefforts to improve reusability and simplify deep learning (DL) model\ndevelopment in disciplines like natural language processing and computer\nvision, none of them are optimized for challenges in the domain of DIA.\nThis represents a major gap in the existing toolkit, as DIA is central to\nacademic research across a wide range of disciplines in the social sciences\nand humanities. This paper introduces LayoutParser, an open-source\nlibrary for streamlining the usage of DL in DIA research and applications. The core LayoutParser library comes with a set of simple and\nintuitive interfaces for applying and customizing DL models for layout detection, character recognition, and many other document processing tasks.\nTo promote extensibility, LayoutParser also incorporates a community\nplatform for sharing both pre-trained models and full document digitization pipelines. We demonstrate that LayoutParser is helpful for both\nlightweight and large-scale digitization pipelines in real-word use cases.\n[The library is publicly available at https://layout-parser.github.io.](https://layout-parser.github.io)\n\n**Keywords: Document Image Analysis · Deep Learning · Layout Analysis**\n\n    - Character Recognition · Open Source library · Toolkit.\n\n### 1 Introduction\n\n\nDeep Learning(DL)-based approaches are the state-of-the-art for a wide range of\ndocument image analysis (DIA) tasks including document image classification [11,\n\n')
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import pprint

pprint.pp(docs[0].metadata)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{'producer': 'pdfTeX-1.40.21',
 'creator': 'LaTeX with hyperref',
 'creationdate': '2021-06-22T01:27:10+00:00',
 'source': './example_data/layout-parser-paper.pdf',
 'file_path': './example_data/layout-parser-paper.pdf',
 'total_pages': 16,
 'format': 'PDF 1.5',
 'title': '',
 'author': '',
 'subject': '',
 'keywords': '',
 'moddate': '2021-06-22T01:27:10+00:00',
 'trapped': '',
 'modDate': 'D:20210622012710Z',
 'creationDate': 'D:20210622012710Z',
 'page': 0}
```

## 惰性加载

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pages = []
for doc in loader.lazy_load():
    pages.append(doc)
    if len(pages) >= 10:
        # do some paged operation, e.g.
        # index.upsert(page)

        pages = []
len(pages)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
6
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from IPython.display import Markdown, display

part = pages[0].page_content[778:1189]
print(part)
# Markdown rendering
display(Markdown(part))
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pprint.pp(pages[0].metadata)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
{'producer': 'pdfTeX-1.40.21',
 'creator': 'LaTeX with hyperref',
 'creationdate': '2021-06-22T01:27:10+00:00',
 'source': './example_data/layout-parser-paper.pdf',
 'file_path': './example_data/layout-parser-paper.pdf',
 'total_pages': 16,
 'format': 'PDF 1.5',
 'title': '',
 'author': '',
 'subject': '',
 'keywords': '',
 'moddate': '2021-06-22T01:27:10+00:00',
 'trapped': '',
 'modDate': 'D:20210622012710Z',
 'creationDate': 'D:20210622012710Z',
 'page': 10}
```

metadata 属性至少包含以下键：

* source
* page (if in mode *page*)
* total\_page
* creationdate
* creator
* producer

额外的元数据因解析器而异。
这些信息可能很有用（例如用于分类你的 PDF）。

## Splitting mode & custom pages delimiter

加载 PDF 文件时，你可以用两种不同的方式分割它：

* By page
* As a single text flow

默认情况下，PyMuPDF4LLMLoader will split the PDF by page.

### Extract the PDF by page. each page is extracted as a langchain document object

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = PyMuPDF4LLMLoader(
    "./example_data/layout-parser-paper.pdf",
    mode="page",
)
docs = loader.load()

print(len(docs))
pprint.pp(docs[0].metadata)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
16
{'producer': 'pdfTeX-1.40.21',
 'creator': 'LaTeX with hyperref',
 'creationdate': '2021-06-22T01:27:10+00:00',
 'source': './example_data/layout-parser-paper.pdf',
 'file_path': './example_data/layout-parser-paper.pdf',
 'total_pages': 16,
 'format': 'PDF 1.5',
 'title': '',
 'author': '',
 'subject': '',
 'keywords': '',
 'moddate': '2021-06-22T01:27:10+00:00',
 'trapped': '',
 'modDate': 'D:20210622012710Z',
 'creationDate': 'D:20210622012710Z',
 'page': 0}
```

In this mode the pdf is split by pages and the resulting Documents metadata contains the `page` (page number). But in some cases we could want to process the pdf as a single text flow (so we don't cut some paragraphs in half). In this case you can use the *single* mode :

### Extract the whole PDF as a single langchain document object

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = PyMuPDF4LLMLoader(
    "./example_data/layout-parser-paper.pdf",
    mode="single",
)
docs = loader.load()

print(len(docs))
pprint.pp(docs[0].metadata)
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
1
{'producer': 'pdfTeX-1.40.21',
 'creator': 'LaTeX with hyperref',
 'creationdate': '2021-06-22T01:27:10+00:00',
 'source': './example_data/layout-parser-paper.pdf',
 'file_path': './example_data/layout-parser-paper.pdf',
 'total_pages': 16,
 'format': 'PDF 1.5',
 'title': '',
 'author': '',
 'subject': '',
 'keywords': '',
 'moddate': '2021-06-22T01:27:10+00:00',
 'trapped': '',
 'modDate': 'D:20210622012710Z',
 'creationDate': 'D:20210622012710Z'}
```

Logically, in this mode, the `page` (page\_number) metadata disappears. Here's how to clearly identify where pages end in the text flow :

### Add a custom *pages\_delimiter* to identify where are ends of pages in *single* mode

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = PyMuPDF4LLMLoader(
    "./example_data/layout-parser-paper.pdf",
    mode="single",
    pages_delimiter="\n-------THIS IS A CUSTOM END OF PAGE-------\n\n",
)
docs = loader.load()

part = docs[0].page_content[10663:11317]
print(part)
display(Markdown(part))
```

默认`pages_delimiter` is \n-----\n\n.
This could simply be \n, or \f to clearly indicate a page change, or \<!-- PAGE BREAK --> for seamless injection in a Markdown viewer without a visual effect.

# Extract images from the PDF

You can extract images from your PDFs (in text form) with a choice of three different solutions:

* rapidOCR (lightweight Optical Character Recognition tool)
* Tesseract (OCR tool with high precision)
* Multimodal language model

The result is inserted at the end of text of the page.

### Extract images from the PDF with rapidOCR

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU rapidocr-onnxruntime pillow
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders.parsers import RapidOCRBlobParser

loader = PyMuPDF4LLMLoader(
    "./example_data/layout-parser-paper.pdf",
    mode="page",
    extract_images=True,
    images_parser=RapidOCRBlobParser(),
)
docs = loader.load()

part = docs[5].page_content[1863:]
print(part)
display(Markdown(part))
```

请注意，RapidOCR 设计用于处理中文和英文，不支持其他语言。

### Extract images from the PDF with tesseract

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU pytesseract
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders.parsers import TesseractBlobParser

loader = PyMuPDF4LLMLoader(
    "./example_data/layout-parser-paper.pdf",
    mode="page",
    extract_images=True,
    images_parser=TesseractBlobParser(),
)
docs = loader.load()

print(docs[5].page_content[1863:])
```

### Extract images from the PDF with multimodal model

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
pip install -qU langchain-openai
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
import os

from dotenv import load_dotenv

load_dotenv()
```

```text theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
True
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from getpass import getpass

if not os.environ.get("OPENAI_API_KEY"):
    os.environ["OPENAI_API_KEY"] = getpass("OpenAI API key =")
```

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders.parsers import LLMImageBlobParser
from langchain_openai import ChatOpenAI

loader = PyMuPDF4LLMLoader(
    "./example_data/layout-parser-paper.pdf",
    mode="page",
    extract_images=True,
    images_parser=LLMImageBlobParser(
        model=ChatOpenAI(model="gpt-5.4-mini", max_tokens=1024)
    ),
)
docs = loader.load()

print(docs[5].page_content[1863:])
```

# Extract tables from the PDF

With PyMUPDF4LLM you can extract tables from your PDFs in *markdown* format :

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
loader = PyMuPDF4LLMLoader(
    "./example_data/layout-parser-paper.pdf",
    mode="page",
    # "lines_strict" is the default strategy and
    # is the most accurate for tables with column and row lines,
    # but may not work well with all documents.
    # "lines" is a less strict strategy that may work better with
    # some documents.
    # "text" is the least strict strategy and may work better
    # with documents that do not have tables with lines.
    table_strategy="lines",
)
docs = loader.load()

part = docs[4].page_content[3210:]
print(part)
display(Markdown(part))
```

## Working with files

许多文档加载器涉及文件解析。这类加载器之间的差异通常在于文件的解析方式，而不是文件的加载方式。 For example, you can use `open` to read the binary content of either a PDF or a markdown file, but you need different parsing logic to convert that binary data into text.

As a result, it can be helpful to decouple the parsing logic from the loading logic, which makes it easier to reuse a given parser regardless of how the data was loaded.
你可以使用此策略用相同的解析参数分析不同的文件。

```python theme={"theme":{"light":"catppuccin-latte","dark":"catppuccin-mocha"}}
from langchain_community.document_loaders import FileSystemBlobLoader
from langchain_community.document_loaders.generic import GenericLoader
from langchain_pymupdf4llm import PyMuPDF4LLMParser

loader = GenericLoader(
    blob_loader=FileSystemBlobLoader(
        path="./example_data/",
        glob="*.pdf",
    ),
    blob_parser=PyMuPDF4LLMParser(),
)
docs = loader.load()

part = docs[0].page_content[:562]
print(part)
display(Markdown(part))
```

***

## API 参考

For detailed documentation of all `PyMuPDF4LLMLoader` features and configurations head to the GitHub repository: [github.com/lakinduboteju/langchain-pymupdf4llm](https://github.com/lakinduboteju/langchain-pymupdf4llm)

***

<div className="source-links">
  <Callout icon="terminal-2">
    [通过 MCP 将这些文档连接到](/use-these-docs) Claude、VSCode 等工具以获取实时答案。
  </Callout>

  <Callout icon="edit">
    [在 GitHub 上编辑此页面](https://github.com/langchain-ai/docs/edit/main/src/oss/python/integrations/document_loaders/pymupdf4llm.mdx) 或 [提交 issue](https://github.com/langchain-ai/docs/issues/new/choose)。
  </Callout>
</div>
