"""PDF page rendering for UI preview.""" from __future__ import annotations from pathlib import Path import fitz from PIL import Image from app.input_document import open_input_document def open_document(path: str | Path) -> fitz.Document: """Open a supported PDF or image for preview.""" return open_input_document(path) def page_count(doc: fitz.Document) -> int: return doc.page_count def render_page( doc: fitz.Document, page_index: int, max_width: int = 900, max_height: int = 700, dpi: float = 120.0, ) -> Image.Image: """Render a PDF page to a Pillow RGB image, scaled to fit max dimensions.""" if page_index < 0 or page_index >= doc.page_count: raise IndexError(f"Page index {page_index} out of range (0..{doc.page_count - 1})") page = doc.load_page(page_index) zoom = dpi / 72.0 mat = fitz.Matrix(zoom, zoom) pix = page.get_pixmap(matrix=mat, alpha=False) image = Image.frombytes("RGB", (pix.width, pix.height), pix.samples) if image.width > max_width or image.height > max_height: image.thumbnail((max_width, max_height), Image.Resampling.LANCZOS) return image def close_document(doc: fitz.Document | None) -> None: if doc is not None: doc.close()