pdf-ppt / backend /pdf_processor.py
asemxin2000's picture
Upload folder using huggingface_hub
8576e2e verified
Raw
History Blame Contribute Delete
1.42 kB
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()