label_renderer.py 30 KB

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