Windows designer for Avery templates with Avery.com Word download, print, and PyInstaller build. Co-authored-by: Cursor <cursoragent@cursor.com>
254 lines
7.9 KiB
Python
254 lines
7.9 KiB
Python
"""Import PDF / Word documents and rasterize pages for Avery 60504 labels."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import math
|
|
from pathlib import Path
|
|
|
|
from PIL import Image
|
|
|
|
from .app_paths import temp_imports_dir
|
|
from .import_settings import ImportSettings, fitted_rect
|
|
from .models import LABELS_PER_SHEET, LabelDesign, LabelElement
|
|
from .template_60504 import TEMPLATE
|
|
|
|
SUPPORTED_PDF = {".pdf"}
|
|
SUPPORTED_WORD = {".docx", ".doc"}
|
|
SUPPORTED_IMPORT = SUPPORTED_PDF | SUPPORTED_WORD
|
|
|
|
|
|
class DocumentImportError(Exception):
|
|
"""Raised when a document cannot be imported."""
|
|
|
|
|
|
def _cache_dir(project_dir: Path | None = None) -> Path:
|
|
"""Session temp cache for rasterized pages (not AppData)."""
|
|
if project_dir is not None:
|
|
out = Path(project_dir) / "imports"
|
|
else:
|
|
out = temp_imports_dir()
|
|
out.mkdir(parents=True, exist_ok=True)
|
|
return out
|
|
|
|
|
|
def word_to_pdf(path: Path, out_pdf: Path) -> Path:
|
|
"""Convert .doc/.docx to PDF using Microsoft Word (Windows COM)."""
|
|
path = path.resolve()
|
|
out_pdf = out_pdf.resolve()
|
|
out_pdf.parent.mkdir(parents=True, exist_ok=True)
|
|
|
|
try:
|
|
import win32com.client # type: ignore
|
|
import pythoncom
|
|
except ImportError as exc:
|
|
raise DocumentImportError(
|
|
"Word import needs pywin32 and Microsoft Word installed.\n"
|
|
"Install with: pip install pywin32\n"
|
|
"Or save/export the document as PDF and import the PDF."
|
|
) from exc
|
|
|
|
pythoncom.CoInitialize()
|
|
word = None
|
|
doc = None
|
|
try:
|
|
word = win32com.client.Dispatch("Word.Application")
|
|
word.Visible = False
|
|
word.DisplayAlerts = 0
|
|
doc = word.Documents.Open(str(path), ReadOnly=True)
|
|
doc.SaveAs(str(out_pdf), FileFormat=17)
|
|
except Exception as exc:
|
|
raise DocumentImportError(
|
|
f"Could not convert Word document with Microsoft Word:\n{exc}\n\n"
|
|
"Save the file as PDF from Word, then import the PDF."
|
|
) from exc
|
|
finally:
|
|
if doc is not None:
|
|
doc.Close(False)
|
|
if word is not None:
|
|
word.Quit()
|
|
pythoncom.CoUninitialize()
|
|
|
|
if not out_pdf.is_file():
|
|
raise DocumentImportError("Word conversion finished but no PDF was created.")
|
|
return out_pdf
|
|
|
|
|
|
def render_pdf_pages(
|
|
pdf_path: Path,
|
|
*,
|
|
settings: ImportSettings,
|
|
cache_dir: Path | None = None,
|
|
max_pages: int | None = None,
|
|
) -> list[Path]:
|
|
"""Rasterize PDF pages to PNG files (from start_page through end / max)."""
|
|
try:
|
|
import fitz # PyMuPDF
|
|
except ImportError as exc:
|
|
raise DocumentImportError(
|
|
"PyMuPDF is required for PDF import. Run: pip install pymupdf"
|
|
) from exc
|
|
|
|
pdf_path = Path(pdf_path)
|
|
if not pdf_path.is_file():
|
|
raise DocumentImportError(f"File not found: {pdf_path}")
|
|
|
|
out_dir = _cache_dir(cache_dir)
|
|
stem = pdf_path.stem.replace(" ", "_")[:40]
|
|
images: list[Path] = []
|
|
|
|
doc = fitz.open(pdf_path)
|
|
try:
|
|
start = max(0, settings.start_page - 1)
|
|
if settings.end_page and settings.end_page > 0:
|
|
end = min(len(doc), settings.end_page)
|
|
else:
|
|
end = len(doc)
|
|
if max_pages is not None:
|
|
end = min(end, start + max_pages)
|
|
if start >= len(doc):
|
|
raise DocumentImportError(
|
|
f"Start page {settings.start_page} is beyond the document "
|
|
f"({len(doc)} page(s))."
|
|
)
|
|
if start >= end:
|
|
raise DocumentImportError("No pages selected (check start/end page).")
|
|
|
|
zoom = settings.render_dpi / 72.0
|
|
matrix = fitz.Matrix(zoom, zoom)
|
|
for page_index in range(start, end):
|
|
page = doc[page_index]
|
|
pix = page.get_pixmap(matrix=matrix, alpha=False)
|
|
dest = out_dir / f"{stem}_p{page_index + 1}_{settings.render_dpi}.png"
|
|
pix.save(str(dest))
|
|
images.append(dest)
|
|
finally:
|
|
doc.close()
|
|
|
|
if not images:
|
|
raise DocumentImportError("No pages were rendered from the PDF.")
|
|
return images
|
|
|
|
|
|
def resolve_to_images(
|
|
path: Path,
|
|
*,
|
|
settings: ImportSettings,
|
|
cache_dir: Path | None = None,
|
|
max_pages: int | None = None,
|
|
) -> list[Path]:
|
|
"""Accept PDF or Word path and return raster page images for ALL selected pages."""
|
|
path = Path(path)
|
|
suffix = path.suffix.lower()
|
|
if suffix not in SUPPORTED_IMPORT:
|
|
raise DocumentImportError(
|
|
f"Unsupported file type: {suffix}\n"
|
|
"Supported: PDF (.pdf), Word (.docx, .doc)"
|
|
)
|
|
|
|
if suffix in SUPPORTED_WORD:
|
|
out_pdf = _cache_dir(cache_dir) / f"{path.stem}_converted.pdf"
|
|
path = word_to_pdf(path, out_pdf)
|
|
|
|
return render_pdf_pages(
|
|
path,
|
|
settings=settings,
|
|
cache_dir=cache_dir,
|
|
max_pages=max_pages,
|
|
)
|
|
|
|
|
|
def image_to_label_element(image_path: Path, settings: ImportSettings) -> LabelElement:
|
|
"""Create a label image element fitted to the 60504 panel."""
|
|
with Image.open(image_path) as im:
|
|
px_w, px_h = im.size
|
|
src_w = px_w / float(settings.render_dpi)
|
|
src_h = px_h / float(settings.render_dpi)
|
|
x, y, w, h = fitted_rect(
|
|
src_w,
|
|
src_h,
|
|
TEMPLATE.label_width_in,
|
|
TEMPLATE.label_height_in,
|
|
settings,
|
|
)
|
|
return LabelElement.new_image(str(image_path), x=x, y=y, width=w, height=h)
|
|
|
|
|
|
def _label_from_image(image_path: Path, settings: ImportSettings, name: str | None = None) -> LabelDesign:
|
|
el = image_to_label_element(image_path, settings)
|
|
return LabelDesign(
|
|
name=name or Path(image_path).stem,
|
|
elements=[el],
|
|
)
|
|
|
|
|
|
def build_labels_from_images(
|
|
image_paths: list[Path],
|
|
settings: ImportSettings,
|
|
*,
|
|
active_slots: list[bool] | None = None,
|
|
) -> list[LabelDesign]:
|
|
"""
|
|
Turn all imported page images into a flat label list.
|
|
|
|
one_per_label:
|
|
PDF page N → label N. Sheets auto-created (4 labels / Letter page).
|
|
all_slots_per_page:
|
|
PDF page N → one full sheet of 4 copies (respecting active_slots).
|
|
"""
|
|
if not image_paths:
|
|
raise DocumentImportError("No images to apply.")
|
|
|
|
active = active_slots or [True, True, True, True]
|
|
mode = settings.normalized_fill_mode()
|
|
labels: list[LabelDesign] = []
|
|
|
|
if mode == "all_slots_per_page":
|
|
for img in image_paths:
|
|
for slot in range(LABELS_PER_SHEET):
|
|
if slot < len(active) and active[slot]:
|
|
labels.append(_label_from_image(img, settings, f"{Path(img).stem} (slot {slot + 1})"))
|
|
else:
|
|
labels.append(LabelDesign(name=f"Skipped slot {slot + 1}"))
|
|
return labels
|
|
|
|
# one_per_label — every PDF page becomes one label; pad final sheet to 4
|
|
for img in image_paths:
|
|
labels.append(_label_from_image(img, settings))
|
|
return labels
|
|
|
|
|
|
def import_document_to_labels(
|
|
path: Path,
|
|
settings: ImportSettings,
|
|
*,
|
|
active_slots: list[bool] | None = None,
|
|
cache_dir: Path | None = None,
|
|
) -> tuple[list[LabelDesign], list[Path], int]:
|
|
"""
|
|
Full pipeline: file → ALL selected pages → labels (+ sheet count).
|
|
|
|
Returns (labels, image_paths, sheet_count).
|
|
"""
|
|
images = resolve_to_images(path, settings=settings, cache_dir=cache_dir, max_pages=None)
|
|
labels = build_labels_from_images(images, settings, active_slots=active_slots)
|
|
sheet_count = max(1, math.ceil(len(labels) / LABELS_PER_SHEET))
|
|
return labels, images, sheet_count
|
|
|
|
|
|
# Back-compat name used by older callers
|
|
def import_document_to_slots(
|
|
path: Path,
|
|
settings: ImportSettings,
|
|
*,
|
|
active_slots: list[bool] | None = None,
|
|
existing: list[LabelDesign] | None = None,
|
|
cache_dir: Path | None = None,
|
|
) -> tuple[list[LabelDesign], list[Path]]:
|
|
labels, images, _sheets = import_document_to_labels(
|
|
path,
|
|
settings,
|
|
active_slots=active_slots,
|
|
cache_dir=cache_dir,
|
|
)
|
|
return labels, images
|