PyMuPDF4LLM (also aliased as `pdf4llm`) is a Python library built on PyMuPDF, specialized in converting PDF documents into clean, structured data formats like Markdown, JSON, and plain text, specifically optimized for Large Language Model (LLM) and Retrieval-Augmented Generation (RAG) environments. It includes layout analysis, automatic OCR for scanned pages, and supports multi-column layouts and image extraction. The library is actively maintained and frequently updated, with the current stable version being 1.27.2.2.
pip install -U pymupdf4llmVerified import paths — ran on the pinned version, not inferred.
This quickstart demonstrates how to convert a PDF document into Markdown format using `pymupdf4llm.to_markdown()`. It also shows how to save the output to a file. The library can also convert to JSON and plain text using `to_json()` and `to_text()` respectively.
Remember that the first page is page 0. When using the `pages` parameter, provide 0-based page numbers (e.g., `pages=[0, 2, 4]` for the 1st, 3rd, and 5th pages).
Install Tesseract OCR on your operating system. For Python-side integration, install the `[ocr]` extras (`pip install 'pymupdf4llm[ocr]'`) which includes `opencv-python` for detection heuristics and optional OCR plugins like RapidOCR/PaddleOCR.
Review the generated Markdown for documents with highly intricate or unconventional layouts and manually adjust if specific formatting is critical. The JSON output for tables often provides more structured data if fidelity is paramount.
If header/footer exclusion is critical, process the document into Markdown or plain text, or perform post-processing on the JSON output to remove unwanted sections programmatically.
To resolve the `ImportError: Error loading shared library libstdc++.so.6`, ensure that `libstdc++` is installed in your environment. For Alpine Linux, add `apk add libstdc++` to your Dockerfile or installation commands. For other Linux distributions, use the appropriate package manager (e.g., `apt-get install libstdc++6` for Debian/Ubuntu, `yum install libstdc++` for CentOS/RHEL). Alternatively, consider using a glibc-based Python Docker image (e.g., `python:3.x-slim` or `python:3.x` based on Debian/Ubuntu) which typically includes these dependencies.