#!/usr/bin/env python3 # -*- coding: utf-8 -*- import fitz # PyMuPDF import os from pathlib import Path # =============================== # ๐Ÿ“ FOLDER SETTINGS # =============================== input_folder = Path(r"u:\Dropbox\Ordinace\Dokumentace_ke_zpracovรกnรญ\A4 expand") output_suffix = "_A4scaled.pdf" # A4 portrait size in points A4_WIDTH, A4_HEIGHT = 595, 842 # =============================== # โš™๏ธ FUNCTION # =============================== def normalize_to_A4_portrait(pdf_path: Path): output_path = pdf_path.with_name(pdf_path.stem + output_suffix) # skip if already exists if output_path.exists(): try: output_path.unlink() print(f"๐Ÿงน Deleted old: {output_path.name}") except PermissionError: print(f"โš ๏ธ Skipped {output_path.name} (open elsewhere)") return src = fitz.open(pdf_path) dst = fitz.open() changed = False for i, page in enumerate(src, 1): rect = page.rect w, h = rect.width, rect.height # check if already close to A4 size (within 2%) if abs(w - A4_WIDTH) < 12 and abs(h - A4_HEIGHT) < 17: # copy directly without change dst.insert_pdf(src, from_page=i - 1, to_page=i - 1) print(f"โœ… {pdf_path.name} page {i}: already A4, copied as-is.") continue changed = True scale = min(A4_WIDTH / w, A4_HEIGHT / h) new_w, new_h = w * scale, h * scale # horizontal center, vertical TOP x_off = (A4_WIDTH - new_w) / 2 y_off = 0 # ๐Ÿ‘ˆ place at top edge new_page = dst.new_page(width=A4_WIDTH, height=A4_HEIGHT) new_page.show_pdf_page( fitz.Rect(x_off, y_off, x_off + new_w, y_off + new_h), src, page.number ) print(f"๐Ÿ“„ {pdf_path.name} page {i}: {w:.0f}ร—{h:.0f} โ†’ {new_w:.0f}ร—{new_h:.0f} (top-aligned)") dst.save(output_path) src.close() dst.close() if changed: print(f"โœ… Saved normalized A4 PDF: {output_path.name}\n") else: print(f"โžก๏ธ No change needed: {pdf_path.name}\n") # =============================== # ๐Ÿš€ MAIN LOOP # =============================== for file in input_folder.glob("*.pdf"): normalize_to_A4_portrait(file) print("\n๐ŸŽ‰ All PDFs processed โ€” scaled to A4 portrait, top-aligned.")