label_renderer.py 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931
  1. """PDF spool label rendering.
  2. Six fixed templates:
  3. - ``ams_holder_74x33`` — 74×33 mm single label, matches the printable label
  4. STL bundled with the Makerworld AMS Filament Label Holder (model 752566).
  5. Smaller variant — the visible window in the holder. One label per page.
  6. - ``ams_holder_75x55`` — 75×55 mm single label, fits the cardstock-insert
  7. variant of the same holder. Roomier — swatch + QR + full text column.
  8. - ``box_40x30`` — 40×30 mm single label, common DK/Brother roll size and a
  9. good fit for filament-bag/storage-bin labels (#809 follow-up). Roomy
  10. layout — swatch, QR, full text column with hex code.
  11. - ``box_62x29`` — 62×29 mm single label, sized for Brother PT/QL and Dymo
  12. generic small labels. One label per page.
  13. - ``avery_5160`` — US Letter sheet, 25.4×66.7 mm × 30 per sheet.
  14. - ``avery_l7160`` — A4 sheet, 38.1×63.5 mm × 21 per sheet.
  15. Beyond these, a sheet of any grid can be described at run time as a
  16. ``SheetLayout`` (#3296): page size, label size, columns and rows, margins and
  17. gaps. The built-in sheets are ``SheetLayout`` values too.
  18. The legacy ``ams_30x15`` preset (#809) was incorrect — the original 30×15 mm
  19. dimension didn't fit any documented variant of model 752566. Replaced by the
  20. two ``ams_holder_*`` presets above (#1426).
  21. The renderer is decoupled from the Spool model: callers build a ``LabelData``
  22. list from whatever source (local DB, Spoolman, future) so the same code path
  23. works in both modes.
  24. Layout principle, taken from the issue's user need (`#809`): the **spool ID**
  25. is the most-recognisable field at arm's length and dominates the layout. Other
  26. fields (brand, material, name, storage location) fill remaining space; the QR
  27. code provides the round-trip back to ``/inventory?spool=<id>``.
  28. Which of those appear is the caller's choice (#2981): ``fields`` names the
  29. lines to print, and ``DEFAULT_LABEL_FIELDS`` is the set every label carried
  30. before the choice existed. The label text is data only (numbers, units,
  31. dates), never words, because the PDF is not translated.
  32. ``render_labels`` returns a PDF; ``pdf_to_pngs`` rasterises it page by page
  33. for label-printer software that takes images.
  34. """
  35. from __future__ import annotations
  36. import io
  37. import unicodedata
  38. from dataclasses import dataclass
  39. from datetime import date
  40. from pathlib import Path
  41. from typing import Literal
  42. import qrcode
  43. from reportlab.lib.colors import Color, HexColor, black, white
  44. from reportlab.lib.pagesizes import A4, letter
  45. from reportlab.lib.units import mm
  46. from reportlab.pdfbase import pdfmetrics
  47. from reportlab.pdfbase.ttfonts import TTFont
  48. from reportlab.pdfgen import canvas as rl_canvas
  49. # Label text is printed in Liberation Sans, embedded in the PDF (#3553). The
  50. # PDF base fonts (Helvetica) only cover Western European characters, so names
  51. # in Polish, Czech, Cyrillic or Greek lost letters. Liberation Sans has the
  52. # same letter widths as Helvetica, so the layout and truncation are unchanged.
  53. #
  54. # Liberation Sans has no Chinese, Japanese or Korean, so a name written in one
  55. # printed as empty boxes, in the PDF and in the preview rasterised from it
  56. # (#3560). A character the label font lacks is drawn in a fallback font
  57. # instead: Droid Sans Fallback for Chinese and Japanese, and Noto Sans KR --
  58. # cut down to Hangul, which Droid lacks -- for Korean. Only the characters a
  59. # label uses are embedded. Neither has a bold or italic face, so CJK text in a
  60. # bold or italic line prints regular.
  61. _FONT_DIR = Path(__file__).resolve().parent.parent / "data" / "fonts"
  62. FONT_REGULAR = "LabelSans"
  63. FONT_BOLD = "LabelSans-Bold"
  64. FONT_ITALIC = "LabelSans-Italic"
  65. FONT_CJK = "LabelCJK"
  66. FONT_HANGUL = "LabelHangul"
  67. # Tried in this order for a character the label font cannot draw.
  68. _FALLBACK_FONTS = (FONT_CJK, FONT_HANGUL)
  69. def _register_fonts() -> None:
  70. registered = set(pdfmetrics.getRegisteredFontNames())
  71. for name, filename in (
  72. (FONT_REGULAR, "LiberationSans-Regular.ttf"),
  73. (FONT_BOLD, "LiberationSans-Bold.ttf"),
  74. (FONT_ITALIC, "LiberationSans-Italic.ttf"),
  75. (FONT_CJK, "DroidSansFallbackFull.ttf"),
  76. (FONT_HANGUL, "NotoSansKR-Hangul.ttf"),
  77. ):
  78. if name not in registered:
  79. pdfmetrics.registerFont(TTFont(name, str(_FONT_DIR / filename)))
  80. _register_fonts()
  81. def _has_glyph(font: str, ch: str) -> bool:
  82. # A TrueType font's character map, as reportlab parsed it on registration.
  83. return ord(ch) in pdfmetrics.getFont(font).face.charToGlyph # pyright: ignore[reportAttributeAccessIssue]
  84. def _font_runs(text: str, font: str) -> list[tuple[str, str]]:
  85. """Split ``text`` into (font, piece) runs: ``font`` wherever it has the
  86. character, else the first fallback that does (#3560). A character no font
  87. has stays with ``font``, which draws its missing-glyph box as before."""
  88. runs: list[tuple[str, str]] = []
  89. for ch in text:
  90. use = font
  91. if not _has_glyph(font, ch):
  92. use = next((f for f in _FALLBACK_FONTS if _has_glyph(f, ch)), font)
  93. if runs and runs[-1][0] == use:
  94. runs[-1] = (use, runs[-1][1] + ch)
  95. else:
  96. runs.append((use, ch))
  97. return runs
  98. def _text_width(text: str, font: str, size: float) -> float:
  99. return sum(pdfmetrics.stringWidth(piece, f, size) for f, piece in _font_runs(text, font))
  100. def _draw_text(c: rl_canvas.Canvas, x: float, y: float, text: str, font: str, size: float) -> None:
  101. """``drawString`` that switches to a fallback font for the characters
  102. ``font`` cannot draw, and leaves ``font`` set afterwards."""
  103. for f, piece in _font_runs(text, font):
  104. c.setFont(f, size)
  105. c.drawString(x, y, piece)
  106. x += pdfmetrics.stringWidth(piece, f, size)
  107. c.setFont(font, size)
  108. def _new_canvas(buf: io.BytesIO, pagesize: tuple[float, float]) -> rl_canvas.Canvas:
  109. """A canvas whose default font is the label font, so the PDF does not
  110. carry an unused Helvetica resource."""
  111. # types-reportlab declares initialFontName as a float; reportlab takes a font name.
  112. return rl_canvas.Canvas(
  113. buf,
  114. pagesize=pagesize,
  115. initialFontName=FONT_REGULAR, # pyright: ignore[reportArgumentType]
  116. )
  117. TemplateName = Literal[
  118. "ams_holder_74x33",
  119. "ams_holder_75x55",
  120. "box_40x30",
  121. "box_62x29",
  122. "avery_5160",
  123. "avery_l7160",
  124. ]
  125. LabelField = Literal[
  126. "brand",
  127. "material",
  128. "hex",
  129. "name",
  130. "location",
  131. "material_number",
  132. "temps",
  133. "weight",
  134. "note",
  135. "added",
  136. "qr",
  137. "spool_id",
  138. ]
  139. # Top-to-bottom order of the text lines, and the order the picker lists them.
  140. ALL_LABEL_FIELDS: tuple[LabelField, ...] = (
  141. "brand",
  142. "material",
  143. "hex",
  144. "name",
  145. "location",
  146. "material_number",
  147. "temps",
  148. "weight",
  149. "note",
  150. "added",
  151. "qr",
  152. "spool_id",
  153. )
  154. # What a label carried before the fields were selectable, so a request that
  155. # names none prints exactly what it always did.
  156. DEFAULT_LABEL_FIELDS: frozenset[LabelField] = frozenset(
  157. {"brand", "material", "hex", "name", "location", "qr", "spool_id"}
  158. )
  159. @dataclass
  160. class LabelData:
  161. """Per-spool data needed to render a label.
  162. Decoupled from the SQLAlchemy model so the same renderer serves the local
  163. inventory and the Spoolman-backed inventory.
  164. """
  165. spool_id: int
  166. name: str
  167. material: str
  168. brand: str | None = None
  169. subtype: str | None = None
  170. rgba: str | None = None # "RRGGBB" or "RRGGBBAA"; None → neutral grey
  171. extra_colors: list[str] | None = None # additional hex colours (no '#')
  172. storage_location: str | None = None
  173. deeplink_url: str = "" # what the QR encodes; caller composes it
  174. material_number: str | None = None
  175. nozzle_temp_min: int | None = None
  176. nozzle_temp_max: int | None = None
  177. label_weight: int | None = None # advertised net weight, grams
  178. note: str | None = None
  179. added: date | None = None
  180. def _temps_text(data: LabelData) -> str:
  181. """``220–240 °C``, or the one bound that is set."""
  182. lo, hi = data.nozzle_temp_min, data.nozzle_temp_max
  183. if lo and hi and lo != hi:
  184. return f"{lo}–{hi} °C"
  185. if lo or hi:
  186. return f"{lo or hi} °C"
  187. return ""
  188. def _weight_text(data: LabelData) -> str:
  189. return f"{data.label_weight} g" if data.label_weight else ""
  190. # ── Colour helpers ───────────────────────────────────────────────────────────
  191. def _color_from_hex(hex_str: str | None, fallback: Color = HexColor(0x808080)) -> Color:
  192. """Parse an RRGGBB or RRGGBBAA string (no '#') into a ReportLab Color.
  193. Alpha is honoured so multi-colour spools with translucent overlays render
  194. correctly. Falls back to ``fallback`` for None / malformed input rather
  195. than raising — labels should always print.
  196. """
  197. if not hex_str:
  198. return fallback
  199. h = hex_str.lstrip("#").strip()
  200. if len(h) not in (6, 8):
  201. return fallback
  202. try:
  203. r = int(h[0:2], 16) / 255.0
  204. g = int(h[2:4], 16) / 255.0
  205. b = int(h[4:6], 16) / 255.0
  206. a = int(h[6:8], 16) / 255.0 if len(h) == 8 else 1.0
  207. return Color(r, g, b, alpha=a)
  208. except ValueError:
  209. return fallback
  210. def _hex_code_label(rgba: str | None) -> str:
  211. """Format ``data.rgba`` as a printable ``#RRGGBB`` string for the label.
  212. Drops the alpha channel (printed labels can't show transparency) and
  213. upper-cases the hex digits to match the colour-picker convention used in
  214. the inventory UI. Returns an empty string for None / malformed input so
  215. the caller can ``if hex_code:`` skip drawing without an exception.
  216. """
  217. if not rgba:
  218. return ""
  219. h = rgba.lstrip("#").strip()
  220. if len(h) not in (6, 8):
  221. return ""
  222. rgb = h[:6]
  223. if not all(c in "0123456789abcdefABCDEF" for c in rgb):
  224. return ""
  225. return f"#{rgb.upper()}"
  226. # ── QR generation ────────────────────────────────────────────────────────────
  227. def _qr_png_bytes(payload: str, *, box_size: int = 4, border: int = 2) -> bytes:
  228. """Render ``payload`` as a tight QR PNG. Empty payload returns empty bytes
  229. so callers can skip drawing without checking ahead of time.
  230. """
  231. if not payload:
  232. return b""
  233. qr = qrcode.QRCode(
  234. version=None,
  235. # ERROR_CORRECT_L (7% recovery) rather than M (15%): a label QR only
  236. # needs to survive being scanned off clean stock, not physical damage,
  237. # and L encodes the same payload in a lower version (fewer, chunkier
  238. # modules). That extra module size is what makes the code printable on
  239. # low-resolution 203 dpi thermal printers, where M-level density bled
  240. # the modules together on small labels (#1870).
  241. error_correction=qrcode.constants.ERROR_CORRECT_L,
  242. box_size=box_size,
  243. border=border,
  244. )
  245. qr.add_data(payload)
  246. qr.make(fit=True)
  247. img = qr.make_image(fill_color="black", back_color="white")
  248. buf = io.BytesIO()
  249. img.save(buf, format="PNG")
  250. return buf.getvalue()
  251. # ── Single-label drawing ─────────────────────────────────────────────────────
  252. def _draw_swatch(c: rl_canvas.Canvas, x: float, y: float, w: float, h: float, data: LabelData) -> None:
  253. """Draw the colour swatch. Multi-colour spools use vertical stripes
  254. (matching the FilamentSwatch convention in the frontend)."""
  255. c.saveState()
  256. try:
  257. primary = _color_from_hex(data.rgba)
  258. extras = [_color_from_hex(h) for h in (data.extra_colors or []) if h]
  259. colors = [primary, *extras]
  260. if not colors:
  261. c.setFillColor(HexColor(0x808080))
  262. c.rect(x, y, w, h, stroke=0, fill=1)
  263. return
  264. stripe_w = w / len(colors)
  265. for i, col in enumerate(colors):
  266. c.setFillColor(col)
  267. c.rect(x + i * stripe_w, y, stripe_w, h, stroke=0, fill=1)
  268. # Thin black border so light-colour swatches stay visible on white labels.
  269. c.setStrokeColor(black)
  270. c.setLineWidth(0.3)
  271. c.rect(x, y, w, h, stroke=1, fill=0)
  272. finally:
  273. c.restoreState()
  274. def _roomy_qr_size(inner_w: float, inner_h: float) -> float:
  275. """QR edge length (points) for the roomy layout.
  276. Historically a flat 20% of inner width, which on the narrowest label
  277. (box_40x30, ~37.6 mm inner) rendered a ~7.5 mm QR — at 203 dpi each module
  278. fell below ~2 dots and the code bled into itself on thermal printers
  279. (#1870). A 12 mm floor keeps small labels scannable; the code is still
  280. capped by the inner height, an 18 mm absolute max, and ~45% of inner width
  281. so it can't crowd out the text column on an ultra-narrow label.
  282. """
  283. return min(max(inner_w * 0.20, 12 * mm), inner_h, 18 * mm, inner_w * 0.45)
  284. def _draw_qr(c: rl_canvas.Canvas, x: float, y: float, size: float, payload: str) -> None:
  285. """Embed a square QR at (x, y) with edge length ``size`` (in points)."""
  286. png = _qr_png_bytes(payload)
  287. if not png:
  288. return
  289. from reportlab.lib.utils import ImageReader
  290. img = ImageReader(io.BytesIO(png))
  291. c.drawImage(img, x, y, width=size, height=size, mask="auto")
  292. def _truncate_to_width(c: rl_canvas.Canvas, text: str, font: str, size: float, max_w: float) -> str:
  293. """Truncate ``text`` with an ellipsis so it fits within ``max_w`` points,
  294. measured in the fonts it will be drawn in."""
  295. if _text_width(text, font, size) <= max_w:
  296. return text
  297. ell = "…"
  298. while text and _text_width(text + ell, font, size) > max_w:
  299. text = text[:-1]
  300. return text + ell if text else ell
  301. def _is_wide(ch: str) -> bool:
  302. return unicodedata.east_asian_width(ch) in ("W", "F")
  303. # Punctuation that never starts a line, nor ends one, in Chinese and Japanese.
  304. _NO_LINE_START = frozenset("、。,.,.:;!?)】」』〉》〕}ー々")
  305. _NO_LINE_END = frozenset("(【「『〈《〔{")
  306. def _breaks_before(text: str, p: int) -> bool:
  307. """Whether a line may break before ``text[p]``."""
  308. if text[p] == " ":
  309. return True
  310. if text[p] in _NO_LINE_START or text[p - 1] in _NO_LINE_END:
  311. return False
  312. return _is_wide(text[p - 1]) or _is_wide(text[p])
  313. def _wrap_to_width(c: rl_canvas.Canvas, text: str, font: str, size: float, max_w: float, max_lines: int) -> list[str]:
  314. """Break ``text`` into at most ``max_lines`` lines of ``max_w`` points
  315. (#3621). A line breaks at its last space, or next to a Chinese, Japanese
  316. or Korean character, which run on without spaces; a word too long for a
  317. line breaks inside it. What is left after the last line is cut with an
  318. ellipsis."""
  319. lines: list[str] = []
  320. rest = text
  321. while len(lines) < max_lines - 1 and _text_width(rest, font, size) > max_w:
  322. cut = 1 # at least one character a line, however narrow the column
  323. while cut < len(rest) and _text_width(rest[: cut + 1], font, size) <= max_w:
  324. cut += 1
  325. at = next((p for p in range(cut, 0, -1) if _breaks_before(rest, p)), cut)
  326. lines.append(rest[:at].rstrip())
  327. rest = rest[at:].lstrip()
  328. if rest:
  329. lines.append(_truncate_to_width(c, rest, font, size, max_w))
  330. return lines
  331. # The most lines one row of the roomy layout may take.
  332. _ROW_MAX_LINES = 3
  333. def _draw_label(
  334. c: rl_canvas.Canvas,
  335. x: float,
  336. y: float,
  337. w: float,
  338. h: float,
  339. data: LabelData,
  340. monochrome: bool = False,
  341. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  342. ) -> None:
  343. """Render one label inside the box (x, y, w, h). Origin is bottom-left.
  344. Two layouts, picked by available height:
  345. - **Tight** (h < 20 mm): swatch on the left, three lines of text on the
  346. right (brand, material+subtype, big spool ID). No QR — at very small
  347. heights there is not enough horizontal room for swatch + text + QR
  348. without truncating away the user-need fields. Kept as the safety
  349. branch for any future ultra-small preset; the shipped templates all
  350. land in the roomy layout below.
  351. - **Roomy** (h >= 20 mm — AMS holder, box label, Avery sheets): swatch
  352. on the left, QR on the right, multi-line text in the middle column.
  353. Large spool ID anchored at bottom-left under the swatch so it stays
  354. readable at arm's length.
  355. """
  356. pad = 1.2 * mm
  357. inner_x, inner_y = x + pad, y + pad
  358. inner_w = w - 2 * pad
  359. inner_h = h - 2 * pad
  360. # Outer hairline border so labels are easy to cut out from blank stock.
  361. c.setStrokeColor(HexColor(0xCCCCCC))
  362. c.setLineWidth(0.4)
  363. c.rect(x, y, w, h, stroke=1, fill=0)
  364. is_tight = h < 20 * mm
  365. if is_tight:
  366. _draw_label_tight(c, x, y, w, h, inner_x, inner_y, inner_w, inner_h, pad, data, monochrome, fields)
  367. else:
  368. _draw_label_roomy(c, x, y, w, h, inner_x, inner_y, inner_w, inner_h, pad, data, monochrome, fields)
  369. def _draw_label_tight(
  370. c: rl_canvas.Canvas,
  371. x: float,
  372. y: float,
  373. w: float,
  374. h: float,
  375. inner_x: float,
  376. inner_y: float,
  377. inner_w: float,
  378. inner_h: float,
  379. pad: float,
  380. data: LabelData,
  381. monochrome: bool = False,
  382. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  383. ) -> None:
  384. """Tight layout (h < 20 mm). Swatch + brand/material/hex/ID, no QR.
  385. Only those four lines fit, so they are the only ``fields`` it honours.
  386. """
  387. # Monochrome: drop the colour swatch (see _draw_label_roomy) and give the
  388. # width to the text column (#1870).
  389. if monochrome:
  390. swatch_w = 0.0
  391. else:
  392. swatch_w = min(inner_h, inner_w * 0.35)
  393. swatch_y = inner_y + (inner_h - swatch_w) / 2
  394. _draw_swatch(c, inner_x, swatch_y, swatch_w, swatch_w, data)
  395. text_x = inner_x + swatch_w + pad
  396. text_w = inner_w - swatch_w - pad
  397. if text_w < 5 * mm:
  398. return # Pathological — even the swatch barely fits.
  399. c.setFillColor(black)
  400. # Top: brand — bumped to bold + larger per the #809 follow-up so it's the
  401. # easiest thing to read on a small AMS holder at arm's length.
  402. brand_size = 6.5
  403. if data.brand and "brand" in fields:
  404. c.setFont(FONT_BOLD, brand_size)
  405. brand = _truncate_to_width(c, data.brand, FONT_BOLD, brand_size, text_w)
  406. _draw_text(c, text_x, y + h - pad - brand_size, brand, FONT_BOLD, brand_size)
  407. # Second line: material + subtype, small
  408. sub_size = 5
  409. sub_line = " ".join(filter(None, [data.material, data.subtype])) if "material" in fields else ""
  410. sub_y_baseline = y + h - pad - brand_size - 0.6 - sub_size
  411. if sub_line:
  412. c.setFont(FONT_REGULAR, sub_size)
  413. sub_line = _truncate_to_width(c, sub_line, FONT_REGULAR, sub_size, text_w)
  414. _draw_text(c, text_x, sub_y_baseline, sub_line, FONT_REGULAR, sub_size)
  415. # Third line (when there's room): hex code, tiny — useful when the user
  416. # has multiple near-identical colours in the same material family.
  417. hex_code = _hex_code_label(data.rgba) if "hex" in fields else ""
  418. if hex_code:
  419. hex_size = 4.5
  420. hex_y = sub_y_baseline - 0.4 - hex_size
  421. # Don't render if it'd collide with the spool ID at the bottom.
  422. if hex_y > inner_y + 13:
  423. c.setFont(FONT_REGULAR, hex_size)
  424. c.drawString(text_x, hex_y, hex_code)
  425. # Bottom: BIG spool ID — the killer field at-a-glance.
  426. if "spool_id" not in fields:
  427. return
  428. id_size = 13
  429. c.setFont(FONT_BOLD, id_size)
  430. id_text = _truncate_to_width(c, f"#{data.spool_id}", FONT_BOLD, id_size, text_w)
  431. c.drawString(text_x, inner_y + 0.5, id_text)
  432. def _draw_label_roomy(
  433. c: rl_canvas.Canvas,
  434. x: float,
  435. y: float,
  436. w: float,
  437. h: float,
  438. inner_x: float,
  439. inner_y: float,
  440. inner_w: float,
  441. inner_h: float,
  442. pad: float,
  443. data: LabelData,
  444. monochrome: bool = False,
  445. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  446. ) -> None:
  447. """Box-label / Avery layout. Swatch left, QR right, text middle."""
  448. # Swatch: full inner height, ~18% of inner width but capped so we never
  449. # eat the text column on extreme aspect ratios. Omitted entirely in
  450. # monochrome mode — on a B&W thermal printer a colour block prints as a
  451. # muddy grey that conveys nothing, so we reclaim the space for text and
  452. # rely on the hex-code line to carry the colour (#1870, requested by
  453. # @Geoff-S). The hex code already renders below whenever rgba is set.
  454. if monochrome:
  455. swatch_w = 0.0
  456. else:
  457. swatch_w = min(inner_w * 0.18, inner_h, 16 * mm)
  458. _draw_swatch(c, inner_x, inner_y, swatch_w, inner_h, data)
  459. # Without the QR the text column runs to the right-hand padding.
  460. if "qr" in fields:
  461. qr_size = _roomy_qr_size(inner_w, inner_h)
  462. qr_x = x + w - pad - qr_size
  463. qr_y = inner_y + (inner_h - qr_size) / 2
  464. _draw_qr(c, qr_x, qr_y, qr_size, data.deeplink_url)
  465. text_right = qr_x - 1.5 * mm
  466. else:
  467. text_right = inner_x + inner_w
  468. text_x = inner_x + swatch_w + 1.5 * mm
  469. text_w = text_right - text_x
  470. if text_w < 8 * mm:
  471. return
  472. c.setFillColor(black)
  473. # Spool ID — anchored at the bottom of the text column, big and bold. The
  474. # lines above stop short of it rather than print over it.
  475. id_size = 16
  476. show_id = "spool_id" in fields
  477. floor_y = inner_y + 0.5 + id_size if show_id else inner_y
  478. name = data.name or ""
  479. # The name line is dropped when it only repeats the brand, or the subtype
  480. # already printed beside the material (a Spoolman filament named after
  481. # its colour yields both).
  482. repeats = {data.brand or ""}
  483. if "material" in fields and data.subtype:
  484. repeats.add(data.subtype)
  485. # (field, text, font, size, gap below). Sizes and gaps of the first five
  486. # are what the label has always used; the rest share the location's.
  487. rows: list[tuple[LabelField, str, str, float, float]] = [
  488. # Brand — bumped to bold + larger per the #809 follow-up.
  489. ("brand", data.brand or "", FONT_BOLD, 8, 1.2),
  490. ("material", " · ".join(filter(None, [data.material, data.subtype])), FONT_REGULAR, 7, 1.5),
  491. # Hex colour code — useful for telling near-identical material+colour
  492. # spools apart when the swatch is small or the user is colour-blind.
  493. ("hex", _hex_code_label(data.rgba), FONT_REGULAR, 6.5, 1.2),
  494. ("name", name if name not in repeats else "", FONT_BOLD, 9, 1.2),
  495. ("location", data.storage_location or "", FONT_ITALIC, 6.5, 1.2),
  496. ("material_number", data.material_number or "", FONT_REGULAR, 6.5, 1.2),
  497. ("temps", _temps_text(data), FONT_REGULAR, 6.5, 1.2),
  498. ("weight", _weight_text(data), FONT_REGULAR, 6.5, 1.2),
  499. ("note", data.note or "", FONT_ITALIC, 6.5, 1.2),
  500. ("added", data.added.isoformat() if data.added else "", FONT_REGULAR, 6.5, 1.2),
  501. ]
  502. active = [row for row in rows if row[0] in fields and row[1]]
  503. cursor_y = y + h - pad
  504. for i, (_field, text, font, size, gap) in enumerate(active):
  505. if cursor_y - size < floor_y:
  506. break
  507. # A row too wide for the column continues on further lines, as long
  508. # as every row below it still gets a line of its own (#3621).
  509. below = sum(s + g for _f, _t, _fo, s, g in active[i + 1 :])
  510. room = 1
  511. while room < _ROW_MAX_LINES and cursor_y - (room + 1) * (size + gap) - below >= floor_y:
  512. room += 1
  513. for line in _wrap_to_width(c, text, font, size, text_w, room):
  514. c.setFont(font, size)
  515. cursor_y -= size
  516. _draw_text(c, text_x, cursor_y, line, font, size)
  517. cursor_y -= gap
  518. if show_id:
  519. c.setFont(FONT_BOLD, id_size)
  520. id_text = _truncate_to_width(c, f"#{data.spool_id}", FONT_BOLD, id_size, text_w)
  521. c.drawString(text_x, inner_y + 0.5, id_text)
  522. # ── Template entry points ────────────────────────────────────────────────────
  523. PageSize = Literal["a4", "letter"]
  524. _PAGE_SIZES: dict[str, tuple[float, float]] = {"a4": A4, "letter": letter}
  525. # The same pages in millimetres, for the fit check. Written out rather than
  526. # derived from the points above so the dialog (labelSheetLayout.ts) can use the
  527. # very same numbers: letter[0] / mm is 215.8999…, not 215.9.
  528. PAGE_SIZES_MM: dict[str, tuple[float, float]] = {"a4": (210.0, 297.0), "letter": (215.9, 279.4)}
  529. # Bounds on a sheet layout (#3296). The minimum label is what the roomy layout
  530. # can fill: from 20 mm tall a label leaves the tight layout (which drops the QR
  531. # and most lines), and from 40 mm wide the text column beside the colour swatch
  532. # and the QR holds a four-digit spool ID at full size, at any height — the same
  533. # width as the smallest built-in label. The rest stops a typo asking for a
  534. # 10 000-label page.
  535. MIN_LABEL_W_MM = 40.0
  536. MIN_LABEL_H_MM = 20.0
  537. MAX_LENGTH_MM = 300.0
  538. MAX_COLS = 20
  539. MAX_ROWS = 40
  540. # Rounding slack when checking that the grid fits the page: a sheet measured in
  541. # inches converts to millimetres with a few hundredths to spare either way.
  542. _FIT_TOLERANCE_MM = 0.01
  543. @dataclass(frozen=True)
  544. class SheetLayout:
  545. """A sheet of identical labels in a grid: the built-in Avery templates and
  546. any custom sheet a user describes (#3296). Lengths are in millimetres."""
  547. page: PageSize
  548. label_w_mm: float
  549. label_h_mm: float
  550. cols: int
  551. rows: int
  552. top_mm: float
  553. left_mm: float
  554. col_gap_mm: float = 0.0
  555. row_gap_mm: float = 0.0
  556. @property
  557. def capacity(self) -> int:
  558. return self.cols * self.rows
  559. @property
  560. def page_size(self) -> tuple[float, float]:
  561. """Page size in points, as ReportLab takes it."""
  562. return _PAGE_SIZES[self.page]
  563. def problem(self) -> str | None:
  564. """Why this layout can't be printed, or ``None`` when it can."""
  565. if self.page not in PAGE_SIZES_MM:
  566. return f"Unknown page size: {self.page!r}"
  567. if self.label_w_mm < MIN_LABEL_W_MM or self.label_h_mm < MIN_LABEL_H_MM:
  568. return f"Labels must be at least {MIN_LABEL_W_MM:g} mm wide and {MIN_LABEL_H_MM:g} mm tall"
  569. lengths = (self.label_w_mm, self.label_h_mm, self.top_mm, self.left_mm, self.col_gap_mm, self.row_gap_mm)
  570. if max(lengths) > MAX_LENGTH_MM:
  571. return f"Sizes, margins and gaps can be at most {MAX_LENGTH_MM:g} mm"
  572. if not 1 <= self.cols <= MAX_COLS:
  573. return f"Columns must be between 1 and {MAX_COLS}"
  574. if not 1 <= self.rows <= MAX_ROWS:
  575. return f"Rows must be between 1 and {MAX_ROWS}"
  576. if min(self.top_mm, self.left_mm, self.col_gap_mm, self.row_gap_mm) < 0:
  577. return "Margins and gaps must not be negative"
  578. page_w_mm, page_h_mm = PAGE_SIZES_MM[self.page]
  579. grid_w = self.left_mm + self.cols * self.label_w_mm + (self.cols - 1) * self.col_gap_mm
  580. grid_h = self.top_mm + self.rows * self.label_h_mm + (self.rows - 1) * self.row_gap_mm
  581. if grid_w > page_w_mm + _FIT_TOLERANCE_MM:
  582. return f"The labels are {grid_w:.2f} mm wide with the left margin, but the page is {page_w_mm:.1f} mm"
  583. if grid_h > page_h_mm + _FIT_TOLERANCE_MM:
  584. return f"The labels are {grid_h:.2f} mm tall with the top margin, but the page is {page_h_mm:.1f} mm"
  585. return None
  586. # A built-in template name, or a sheet layout supplied at run time.
  587. Template = TemplateName | SheetLayout
  588. # (label_w_mm, label_h_mm) for single-label-per-page templates.
  589. _SINGLE_LABEL_SIZES_MM: dict[str, tuple[float, float]] = {
  590. "ams_holder_74x33": (74.0, 33.0),
  591. "ams_holder_75x55": (75.0, 55.0),
  592. "box_40x30": (40.0, 30.0),
  593. "box_62x29": (62.0, 29.0),
  594. }
  595. _SHEET_TEMPLATES: dict[str, SheetLayout] = {
  596. "avery_5160": SheetLayout("letter", 66.675, 25.4, 3, 10, top_mm=12.7, left_mm=4.76, col_gap_mm=3.175),
  597. "avery_l7160": SheetLayout("a4", 63.5, 38.1, 3, 7, top_mm=15.15, left_mm=7.0, col_gap_mm=2.5),
  598. }
  599. def _sheet_layout(template: Template) -> SheetLayout | None:
  600. if isinstance(template, SheetLayout):
  601. return template
  602. return _SHEET_TEMPLATES.get(template)
  603. def _template_title(template: Template) -> str:
  604. return "custom sheet" if isinstance(template, SheetLayout) else template
  605. def _render_single_label_pdf(
  606. template: TemplateName,
  607. data_list: list[LabelData],
  608. monochrome: bool = False,
  609. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  610. ) -> bytes:
  611. w_mm, h_mm = label_size_mm(template)
  612. page_w, page_h = w_mm * mm, h_mm * mm
  613. buf = io.BytesIO()
  614. c = _new_canvas(buf, (page_w, page_h))
  615. c.setTitle(f"Bambuddy spool labels ({template})")
  616. for data in data_list:
  617. _draw_label(c, 0, 0, page_w, page_h, data, monochrome, fields)
  618. c.showPage()
  619. c.save()
  620. return buf.getvalue()
  621. def label_size_mm(template: Template) -> tuple[float, float]:
  622. """(width, height) of one label of ``template`` — a sheet's cell size."""
  623. if isinstance(template, SheetLayout):
  624. return template.label_w_mm, template.label_h_mm
  625. if template in _SHEET_TEMPLATES:
  626. layout = _SHEET_TEMPLATES[template]
  627. return layout.label_w_mm, layout.label_h_mm
  628. if template in _SINGLE_LABEL_SIZES_MM:
  629. return _SINGLE_LABEL_SIZES_MM[template]
  630. raise ValueError(f"Unknown label template: {template!r}")
  631. def get_sheet_capacity(template: Template) -> int | None:
  632. """Return the number of slots on a sheet template, or ``None`` for roll labels."""
  633. layout = _sheet_layout(template)
  634. return None if layout is None else layout.capacity
  635. def sheet_page_count(template: Template, label_count: int, starting_position: int = 1) -> int | None:
  636. """Pages a sheet template prints ``label_count`` labels on, or ``None`` for
  637. roll labels (one label-sized page each)."""
  638. capacity = get_sheet_capacity(template)
  639. if capacity is None:
  640. return None
  641. return -(-(starting_position - 1 + label_count) // capacity)
  642. def _render_sheet_pdf(
  643. layout: SheetLayout,
  644. title: str,
  645. data_list: list[LabelData],
  646. monochrome: bool,
  647. starting_position: int,
  648. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  649. ) -> bytes:
  650. problem = layout.problem()
  651. if problem:
  652. raise ValueError(problem)
  653. page_size = layout.page_size
  654. page_w, page_h = page_size
  655. cols = layout.cols
  656. label_w = layout.label_w_mm * mm
  657. label_h = layout.label_h_mm * mm
  658. top_margin = layout.top_mm * mm
  659. left_margin = layout.left_mm * mm
  660. col_gap = layout.col_gap_mm * mm
  661. row_gap = layout.row_gap_mm * mm
  662. buf = io.BytesIO()
  663. c = _new_canvas(buf, page_size)
  664. c.setTitle(f"Bambuddy spool labels ({title})")
  665. per_page = layout.capacity
  666. if starting_position < 1 or starting_position > per_page:
  667. raise ValueError(f"Starting position must be between 1 and {per_page} for {title}")
  668. data_index = 0
  669. page_number = 0
  670. while data_index < len(data_list):
  671. slot_offset = starting_position - 1 if page_number == 0 else 0
  672. page_capacity = per_page - slot_offset
  673. chunk = data_list[data_index : data_index + page_capacity]
  674. for idx, data in enumerate(chunk):
  675. slot_index = slot_offset + idx
  676. row = slot_index // cols
  677. col = slot_index % cols
  678. x = left_margin + col * (label_w + col_gap)
  679. y = page_h - top_margin - (row + 1) * label_h - row * row_gap
  680. _draw_label(c, x, y, label_w, label_h, data, monochrome, fields)
  681. c.showPage()
  682. data_index += len(chunk)
  683. page_number += 1
  684. c.save()
  685. return buf.getvalue()
  686. def render_labels(
  687. template: Template,
  688. data_list: list[LabelData],
  689. *,
  690. monochrome: bool = False,
  691. starting_position: int = 1,
  692. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  693. ) -> bytes:
  694. """Render ``data_list`` to a PDF using ``template``: a built-in template
  695. name, or a ``SheetLayout`` for a custom sheet (#3296). Returns bytes.
  696. Empty ``data_list`` still produces a valid (empty) PDF — callers should
  697. short-circuit beforehand if that's not desired.
  698. ``monochrome`` drops the colour swatch (which prints as a useless grey block
  699. on black-and-white thermal printers) and reclaims the space for text; the
  700. hex-code line still carries the colour. See #1870.
  701. ``starting_position`` is one-based and applies only to the first page of a
  702. sheet template. Later pages always begin at the first slot.
  703. ``fields`` names the lines to print (#2981); see ``ALL_LABEL_FIELDS``.
  704. """
  705. if isinstance(template, SheetLayout):
  706. return _render_sheet_pdf(template, _template_title(template), data_list, monochrome, starting_position, fields)
  707. if template in _SHEET_TEMPLATES:
  708. return _render_sheet_pdf(_SHEET_TEMPLATES[template], template, data_list, monochrome, starting_position, fields)
  709. if template in _SINGLE_LABEL_SIZES_MM:
  710. if starting_position != 1:
  711. raise ValueError("Starting position is only supported for sheet label templates")
  712. return _render_single_label_pdf(template, data_list, monochrome, fields)
  713. raise ValueError(f"Unknown label template: {template!r}")
  714. def render_label_preview_pdf(
  715. template: Template,
  716. data: LabelData,
  717. *,
  718. monochrome: bool = False,
  719. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  720. ) -> bytes:
  721. """One label of ``template`` on a page of its own size.
  722. For a roll template that is the label as printed; for a sheet it is one
  723. cell, which is all the preview needs to show.
  724. """
  725. w_mm, h_mm = label_size_mm(template)
  726. page_w, page_h = w_mm * mm, h_mm * mm
  727. buf = io.BytesIO()
  728. c = _new_canvas(buf, (page_w, page_h))
  729. _draw_label(c, 0, 0, page_w, page_h, data, monochrome, fields)
  730. c.showPage()
  731. c.save()
  732. return buf.getvalue()
  733. def pdf_to_pngs(pdf: bytes, dpi: int) -> list[bytes]:
  734. """Rasterise every page of ``pdf`` to a PNG at ``dpi``.
  735. Images are drawn without smoothing: the QR is embedded as a bitmap, and
  736. resampling it with interpolation greys the module edges, which is what
  737. makes a small code unreadable on a 203 dpi thermal printer (#1870). The
  738. PNG carries its dpi so label software prints it at the right size.
  739. """
  740. import pypdfium2 as pdfium
  741. from backend.app.services.pdf_thumbnail import _PDFIUM_LOCK
  742. pages: list[bytes] = []
  743. with _PDFIUM_LOCK:
  744. doc = pdfium.PdfDocument(pdf)
  745. try:
  746. for index in range(len(doc)):
  747. page = doc[index]
  748. try:
  749. image = page.render(scale=dpi / 72, no_smoothimage=True).to_pil()
  750. finally:
  751. page.close()
  752. out = io.BytesIO()
  753. image.convert("RGB").save(out, "PNG", dpi=(dpi, dpi), optimize=True)
  754. pages.append(out.getvalue())
  755. finally:
  756. doc.close()
  757. return pages
  758. __all__ = [
  759. "ALL_LABEL_FIELDS",
  760. "DEFAULT_LABEL_FIELDS",
  761. "LabelData",
  762. "LabelField",
  763. "PageSize",
  764. "sheet_page_count",
  765. "SheetLayout",
  766. "Template",
  767. "TemplateName",
  768. "get_sheet_capacity",
  769. "label_size_mm",
  770. "pdf_to_pngs",
  771. "render_label_preview_pdf",
  772. "render_labels",
  773. ]
  774. # white re-exported for completeness; future templates may need a paper-tone variant.
  775. _ = white