Extract Text from PDFs in Python with PyMuPDF
Extracting text from PDF files is useful for search, indexing, analysis, migration, and accessibility workflows. PyMuPDF provides a fast Python API for reading PDF pages and extracting their text.
Install PyMuPDF
python -m pip install pymupdfCurrent PyMuPDF versions support the pymupdf import name. Older examples often use import fitz, which is still seen in existing codebases.
Extract Each Page to a Text File
from pathlib import Path
import pymupdf
def extract_text_from_pdf(pdf_path, output_dir):
output = Path(output_dir)
output.mkdir(parents=True, exist_ok=True)
with pymupdf.open(pdf_path) as document:
for page_number, page in enumerate(document, start=1):
text = page.get_text()
file_path = output / f"page_{page_number}.txt"
file_path.write_text(text, encoding="utf-8")
print(f"Saved page {page_number} to {file_path}")
extract_text_from_pdf("data/file.pdf", "output_texts")How It Works
pymupdf.open()opens the PDF document.Path.mkdir(..., exist_ok=True)creates the output directory when needed.- Iterating over the document yields each page.
page.get_text()extracts the page’s text representation.Path.write_text()writes UTF-8 text to a separate file.- The context manager closes the PDF automatically.
Extract Only Selected Pages
For example, extract pages 1 through 3:
with pymupdf.open("data/file.pdf") as document:
for page_number in range(min(3, len(document))):
text = document[page_number].get_text()
print(text)Remember that Python indexes pages from zero even though humans normally number PDF pages starting from one.
Important Limitation: Scanned PDFs
page.get_text() extracts embedded text. If a PDF page is only a scanned image, there may be little or no text to extract. In that case you need an OCR workflow rather than ordinary PDF text extraction.
Layout Considerations
PDFs store positioned text rather than semantic paragraphs. Multi-column documents, tables, headers, and unusual reading orders can therefore require extra processing. PyMuPDF supports other extraction formats such as blocks, words, dictionaries, and HTML when you need more layout information.
Conclusion
PyMuPDF makes embedded PDF text easy to extract page by page. Use a context manager to close documents reliably, write output with an explicit encoding, and distinguish normal text extraction from OCR when working with scanned documents.