| import fitz
|
| import argparse
|
| import os
|
| import glob
|
|
|
| def convert_pdf_to_images(pdf_path, output_dir, dpi=300, image_format="png"):
|
| """
|
| Convert the FIRST PAGE of a PDF to an image, perfectly maintaining native page proportions.
|
| """
|
|
|
| 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)} (Extracting page 1 only)")
|
|
|
|
|
| if len(doc) == 0:
|
| print(f" -> Skipping '{pdf_name}': PDF has no pages.")
|
| return
|
|
|
|
|
|
|
| zoom = dpi / 72.0
|
| mat = fitz.Matrix(zoom, zoom)
|
|
|
|
|
| page = doc.load_page(0)
|
|
|
|
|
| pix = page.get_pixmap(matrix=mat, alpha=False)
|
|
|
| output_file = os.path.join(pdf_output_dir, f"cover_page.{image_format}")
|
| pix.save(output_file)
|
| print(f" -> Saved first page (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 of first pages...\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 the first page of 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()
|
|
|
|
|
| if not os.path.exists(args.output):
|
| os.makedirs(args.output)
|
|
|
| process_all_pdfs(args.input_path, args.output, args.dpi, args.format) |