"""Fit a rendered badge image onto a printer label (pure Pillow, no hardware).""" from __future__ import annotations from dataclasses import dataclass from PIL import Image from brother_ql.labels import ALL_LABELS, FormFactor, Label PRINT_DPI = 300 # Small rounding differences between the renderer and the label spec are cropped. OVERSHOOT_TOLERANCE_PX = 3 class LayoutTooLarge(Exception): """The badge cannot be printed on the loaded label, even rotated.""" @dataclass class LabelSpec: identifier: str width_px: int height_px: int # 0 for endless/continuous labels die_cut: bool def find_label(identifier: str) -> LabelSpec: for label in ALL_LABELS: if label.identifier == identifier: width, height = label.dots_printable return LabelSpec( identifier=label.identifier, width_px=int(width), height_px=int(height), die_cut=label.form_factor == FormFactor.DIE_CUT, ) raise KeyError(f"unknown label identifier: {identifier}") def _mm(px: int) -> int: return round(px * 25.4 / PRINT_DPI) def _too_large(badge: Image.Image, spec: LabelSpec) -> LayoutTooLarge: return LayoutTooLarge( f"layout {_mm(badge.width)}x{_mm(badge.height)} mm does not fit label {spec.identifier}" ) def _fits(w: int, h: int, spec: LabelSpec) -> bool: if w > spec.width_px + OVERSHOOT_TOLERANCE_PX: return False if spec.die_cut and h > spec.height_px + OVERSHOOT_TOLERANCE_PX: return False return True def _crop_to(w: int, h: int, spec: LabelSpec) -> tuple[int, int]: return ( min(w, spec.width_px), min(h, spec.height_px) if spec.die_cut else h, ) def compose(badge: Image.Image, label: LabelSpec | str) -> Image.Image: """Return a bitmap sized for `label`, ready for brother_ql convert().""" spec = find_label(label) if isinstance(label, str) else label if badge.mode != "RGB": badge = badge.convert("RGB") if not _fits(badge.width, badge.height, spec): rotated = badge.transpose(Image.Transpose.ROTATE_270) if not _fits(rotated.width, rotated.height, spec): raise _too_large(badge, spec) badge = rotated if spec.die_cut: canvas = Image.new("RGB", (spec.width_px, spec.height_px), "white") target = _crop_to(badge.width, badge.height, spec) if (badge.width, badge.height) != target: badge = badge.crop((0, 0, target[0], target[1])) canvas.paste(badge, ((spec.width_px - badge.width) // 2, (spec.height_px - badge.height) // 2)) return canvas # Endless: fixed width, length follows the badge. target_w = min(badge.width, spec.width_px) if badge.width != target_w: badge = badge.crop((0, 0, target_w, badge.height)) canvas = Image.new("RGB", (spec.width_px, badge.height), "white") canvas.paste(badge, ((spec.width_px - badge.width) // 2, 0)) return canvas