Files
Michael-A-SloanandCursor 2c9829ef8c feat(app): add image input support and bump to 1.5.0
Allow PNG/JPG/TIFF/BMP/GIF/WebP alongside PDF for preview and DXF conversion.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-09-03 17:05:17 -04:00

49 lines
1.2 KiB
Python

"""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()