File size: 1,423 Bytes
8576e2e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
import os
import tempfile
import fitz  # PyMuPDF
from PIL import Image

def convert_pdf_to_images(pdf_path: str, output_dir: str = None, dpi: int = 300) -> list[str]:
    """
    Convert a PDF file to a list of high-resolution images.
    
    Args:
        pdf_path: Path to the PDF file.
        output_dir: Directory to store the output images. If None, uses a temporary directory.
        dpi: DPI for the output images. 300 is recommended for OCR accuracy.
        
    Returns:
        List of absolute paths to the generated images.
    """
    if output_dir is None:
        output_dir = tempfile.mkdtemp(prefix="pdf_images_")
    
    os.makedirs(output_dir, exist_ok=True)
    
    doc = fitz.open(pdf_path)
    image_paths = []
    
    # Calculate zoom factor for desired DPI (default PyMuPDF DPI is 72)
    zoom = dpi / 72.0
    mat = fitz.Matrix(zoom, zoom)
    
    for page_num in range(len(doc)):
        page = doc.load_page(page_num)
        pix = page.get_pixmap(matrix=mat, alpha=False)
        
        # Determine format based on output path
        output_path = os.path.join(output_dir, f"page_{page_num + 1:03d}.png")
        pix.save(output_path)
        image_paths.append(os.path.abspath(output_path))
        
    doc.close()
    return image_paths

def test_conversion():
    # Helper for fast testing
    print("PyMuPDF integration works.")

if __name__ == "__main__":
    test_conversion()