Files
PDF-to-DWG-converter/app/pdf_preview.py
T
Michael-A-SloanandCursor 91625af67f Add portable PDF to DXF converter for BricsCAD workflows.
Includes vector/vectorize/raster modes, page review before convert, bundled OCR data, and a single-file AppData launcher build.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-07-30 13:14:57 -04:00

46 lines
1.1 KiB
Python

"""PDF page rendering for UI preview."""
from __future__ import annotations
from pathlib import Path
import fitz
from PIL import Image
def open_document(path: str | Path) -> fitz.Document:
return fitz.open(str(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()