Fast PDF Processing with PyMuPDF (fitz) in Python: Extract Text, Split Pages, and Export Images

Python tutorial - IT technology blog
Python tutorial - IT technology blog

1. Background & Why It Matters

When building document automation pipelines, most Python developers start with pypdf or pdfplumber. Everything runs smoothly as long as you are only processing a few dozen lightweight invoices. However, the real nightmare begins in production: the system has to ingest thousands of financial reports spanning 200 to 500 pages each, or documents packed with vector graphics.

A familiar scenario unfolds: CPU usage spikes to 100%, the process freezes, and the server throws an Out of Memory (OOM) error that crashes the container.

Why is it so slow? Pure-Python libraries must parse complex PDF binary trees directly within the Python interpreter layer. The PDF format itself contains nested layers of embedded fonts, zlib compression streams, and interconnected objects. Interpreted Python struggles significantly when handling large binary arrays.

PyMuPDF solves this problem once and for all. It provides Python bindings for MuPDF—Artifex Software’s renowned C engine known for industry-leading rendering speeds. All heavy lifting is offloaded directly to C for execution.

Real-world benchmarks on a 350-page PDF file (~45MB) speak for themselves: pypdf took over 38 seconds and consumed nearly 700MB of RAM; meanwhile, fitz took just 1.4 seconds while keeping RAM usage stable below 45MB—over 25 times faster.

2. Installation

The development team provides pre-built binary wheels for Windows, macOS, and Linux, eliminating the need to install a C compiler on your server.

Install via pip:

pip install pymupdf

A common point of confusion for newcomers is that the package name is pymupdf, yet the code imports it using import fitz. This is because the underlying MuPDF engine was originally named Fitz, and the authors kept this namespace for backward compatibility (starting from v1.24+, you can use both import pymupdf and import fitz).

Quick check of the installed version:

import fitz

print(f"PyMuPDF version: {fitz.__version__}")
print(f"MuPDF core: {fitz.VersionBind}")

3. Detailed Configuration & Usage

Below are the 3 core tasks: structured text extraction, page splitting, and extracting original images.

3.1. Reading and Extracting Text (Text Extraction)

Beyond extracting raw strings, PyMuPDF allows you to parse text into structured blocks and lines along with their bounding box coordinates. This feature is crucial when parsing invoices or building document chunking pipelines for RAG (Retrieval-Augmented Generation) applications.

import fitz

def extract_text_from_pdf(pdf_path: str):
    with fitz.open(pdf_path) as doc:
        print(f"Total pages: {len(doc)}")
        
        for page_num, page in enumerate(doc):
            # Fast raw text extraction
            raw_text = page.get_text("text")
            
            # Extract text by blocks with bounding box coordinates (x0, y0, x1, y1)
            # Each item: (x0, y0, x1, y1, "content", block_no, block_type)
            blocks = page.get_text("blocks")
            
            print(f"--- Page {page_num + 1}: {len(blocks)} blocks ---")
            for b in blocks:
                content = b[4].strip()
                if content and b[6] == 0:  # block_type 0 is text, 1 is image
                    print(f"[Block {b[5]} at ({b[0]:.1f}, {b[1]:.1f})]: {content[:70]}...")

extract_text_from_pdf("hop_dong_kinh_te.pdf")

When processing tens of thousands of digital contract documents, leveraging the "blocks" parameter allows you to filter out headers and footers based on Y-axis coordinates, saving substantial time compared to writing regex cleanup routines later.

3.2. Splitting Pages and Compressing Output Files (Split & Compress)

Need to extract a 5-page summary from a 300-page document to send via a Telegram bot? PyMuPDF copies page structures directly between memory streams without re-rendering a single pixel.

import fitz

def split_pdf(input_path: str, output_path: str, start_page: int, end_page: int):
    """
    Extract a range of pages from start_page to end_page (0-indexed, inclusive).
    """
    with fitz.open(input_path) as src_doc:
        dest_doc = fitz.open()  # Initialize empty in-memory PDF
        
        # Copy the specified page range
        dest_doc.insert_pdf(src_doc, from_page=start_page, to_page=end_page)
        
        # Save with optimization: clean up unused objects (garbage=4) and enable zlib compression (deflate=True)
        dest_doc.save(output_path, garbage=4, deflate=True)
        dest_doc.close()
        
    print(f"Exported pages {start_page + 1}-{end_page + 1} to: {output_path}")

split_pdf("bao_cao_quy_4.pdf", "ban_tom_tat.pdf", start_page=0, end_page=4)

The garbage=4 and deflate=True flags are the secret sauce here. They prune unused orphan fonts and compress duplicate data streams. Output files typically see a 30% to 60% size reduction compared to conventional page-splitting methods.

3.3. Extracting Original Images (XObject Image Extraction)

Many online scripts suggest taking screenshots of PDF pages (rendering pixmaps) and then cropping the images. That approach causes pixelation, shifts color profiles, and consumes massive amounts of RAM. PyMuPDF inspects the PDF dictionary directly to extract the original embedded image streams (JPEG, PNG):

import os
import fitz

def extract_images(pdf_path: str, output_dir: str = "extracted_images"):
    os.makedirs(output_dir, exist_ok=True)
    
    with fitz.open(pdf_path) as doc:
        img_count = 0
        
        for page_index, page in enumerate(doc):
            # Retrieve list of XObject images on the page
            image_list = page.get_images(full=True)
            
            for img_index, img_info in enumerate(image_list):
                xref = img_info[0]  # XObject reference number
                base_image = doc.extract_image(xref)
                
                image_bytes = base_image["image"]
                image_ext = base_image["ext"]  # Original image extension: png, jpeg, jpx...
                
                filename = os.path.join(output_dir, f"p{page_index + 1}_img{img_index + 1}.{image_ext}")
                with open(filename, "wb") as f:
                    f.write(image_bytes)
                
                img_count += 1
                print(f"Saved: {filename} ({base_image['width']}x{base_image['height']}px)")
                
        print(f"Completed! Extracted {img_count} original images.")

extract_images("profile_cong_ty.pdf")

4. Testing & Monitoring

Deploying code to an automated pipeline requires robust error handling and strict resource monitoring.

4.1. Processing Speed Benchmark

Use time.perf_counter to measure throughput accurately in pages per second:

import time
import fitz

def benchmark_extraction(pdf_path: str):
    start_time = time.perf_counter()
    
    with fitz.open(pdf_path) as doc:
        total_pages = len(doc)
        total_characters = sum(len(page.get_text()) for page in doc)
        
    elapsed = time.perf_counter() - start_time
    pages_per_sec = total_pages / elapsed if elapsed > 0 else 0
    
    print(f"--- Benchmark Results ---")
    print(f"Document: {total_pages} pages | {total_characters:,} characters")
    print(f"Elapsed time: {elapsed:.3f}s | Throughput: {pages_per_sec:.1f} pages/sec")

benchmark_extraction("sach_huong_dan_500_trang.pdf")

4.2. Handling Corrupted Files and Managing Memory Allocation

In practice, roughly 2% of user-uploaded files will have issues: truncated uploads due to network drops, malware, non-standard encoding, or password protection. Always wrap your processing logic in a try-except block:

import fitz

def safe_process_pdf(file_path: str):
    try:
        # Always use a context manager to automatically free C pointers
        with fitz.open(file_path) as doc:
            if doc.is_encrypted:
                print(f"[Skipped] {file_path}: File is password-protected.")
                return None
            
            if doc.is_repaired:
                print(f"[Warning] {file_path}: Syntax errors detected, but MuPDF repaired the file.")
                
            return [page.get_text() for page in doc]
            
    except fitz.FileDataError as err:
        print(f"[File Error] Corrupted or invalid PDF format ({file_path}): {err}")
        return None
    except Exception as err:
        print(f"[System Error] {file_path}: {err}")
        return None

safe_process_pdf("corrupted_invoice.pdf")

Critical memory caveat: MuPDF allocates document structures directly on the C heap. If you open tens of thousands of files inside a for loop without calling doc.close() or using a with block, Python’s Garbage Collector will not reclaim C memory in time. As a result, RAM usage creeps steadily upward until the container hits an OOM crash. Always be disciplined and use with fitz.open(...) in all scenarios.

Share: