import fitz # PyMuPDF import argparse import os import glob def convert_pdf_to_images(pdf_path, output_dir, dpi=300, image_format="png"): """ Convert a PDF to a series of images, perfectly maintaining native page proportions. """ # Create a dedicated subfolder for each PDF's images to keep things organized pdf_name = os.path.splitext(os.path.basename(pdf_path))[0] pdf_output_dir = os.path.join(output_dir, pdf_name) if not os.path.exists(pdf_output_dir): os.makedirs(pdf_output_dir) try: doc = fitz.open(pdf_path) print(f"Processing '{pdf_name}' | Total pages: {len(doc)}") # PDFs have a standard base resolution of 72 DPI. # We calculate a zoom factor to scale the native page size up to your desired DPI. zoom = dpi / 72.0 mat = fitz.Matrix(zoom, zoom) # This matrix dynamically adapts to ANY page size for page_num in range(len(doc)): page = doc.load_page(page_num) # Apply the matrix to render the high-quality, perfectly proportioned image pix = page.get_pixmap(matrix=mat, alpha=False) output_file = os.path.join(pdf_output_dir, f"page_{page_num + 1:02d}.{image_format}") pix.save(output_file) print(f" -> Saved page {page_num + 1} (Dynamic Resolution: {pix.width}x{pix.height})") except Exception as e: print(f"Error processing {pdf_path}: {e}") def process_all_pdfs(input_path, output_dir, dpi=300, image_format="png"): """Determines if the input is a single file or a directory of files.""" if os.path.isfile(input_path): convert_pdf_to_images(input_path, output_dir, dpi, image_format) elif os.path.isdir(input_path): pdf_files = glob.glob(os.path.join(input_path, "*.pdf")) if not pdf_files: print(f"No PDF files found in directory: {input_path}") return print(f"Found {len(pdf_files)} PDF(s). Starting batch conversion...\n") for pdf in pdf_files: convert_pdf_to_images(pdf, output_dir, dpi, image_format) print("-" * 40) print("All batch conversions complete!") else: print("Invalid input path. Please provide a valid PDF file or folder.") if __name__ == "__main__": parser = argparse.ArgumentParser(description="Convert PDFs to auto-adjusting high-quality images.") parser.add_argument("input_path", help="Path to a single PDF file OR a folder containing PDFs") parser.add_argument("--output", "-o", default="output", help="Output directory (default: 'output')") parser.add_argument("--dpi", type=int, default=300, help="Output image DPI (default: 300)") parser.add_argument("--format", "-f", default="png", help="Output image format (default: png)") args = parser.parse_args() # Ensure base output directory exists if not os.path.exists(args.output): os.makedirs(args.output) process_all_pdfs(args.input_path, args.output, args.dpi, args.format)