label_renderer.py 33 KB

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