label_renderer.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  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. The legacy ``ams_30x15`` preset (#809) was incorrect — the original 30×15 mm
  16. dimension didn't fit any documented variant of model 752566. Replaced by the
  17. two ``ams_holder_*`` presets above (#1426).
  18. The renderer is decoupled from the Spool model: callers build a ``LabelData``
  19. list from whatever source (local DB, Spoolman, future) so the same code path
  20. works in both modes.
  21. Layout principle, taken from the issue's user need (`#809`): the **spool ID**
  22. is the most-recognisable field at arm's length and dominates the layout. Other
  23. fields (brand, material, name, storage location) fill remaining space; the QR
  24. code provides the round-trip back to ``/inventory?spool=<id>``.
  25. Which of those appear is the caller's choice (#2981): ``fields`` names the
  26. lines to print, and ``DEFAULT_LABEL_FIELDS`` is the set every label carried
  27. before the choice existed. The label text is data only (numbers, units,
  28. dates), never words, because the PDF is not translated.
  29. ``render_labels`` returns a PDF; ``pdf_to_pngs`` rasterises it page by page
  30. for label-printer software that takes images.
  31. """
  32. from __future__ import annotations
  33. import io
  34. from dataclasses import dataclass
  35. from datetime import date
  36. from typing import Literal
  37. import qrcode
  38. from reportlab.lib.colors import Color, HexColor, black, white
  39. from reportlab.lib.pagesizes import A4, letter
  40. from reportlab.lib.units import mm
  41. from reportlab.pdfgen import canvas as rl_canvas
  42. TemplateName = Literal[
  43. "ams_holder_74x33",
  44. "ams_holder_75x55",
  45. "box_40x30",
  46. "box_62x29",
  47. "avery_5160",
  48. "avery_l7160",
  49. ]
  50. LabelField = Literal[
  51. "brand",
  52. "material",
  53. "hex",
  54. "name",
  55. "location",
  56. "material_number",
  57. "temps",
  58. "weight",
  59. "note",
  60. "added",
  61. "qr",
  62. "spool_id",
  63. ]
  64. # Top-to-bottom order of the text lines, and the order the picker lists them.
  65. ALL_LABEL_FIELDS: tuple[LabelField, ...] = (
  66. "brand",
  67. "material",
  68. "hex",
  69. "name",
  70. "location",
  71. "material_number",
  72. "temps",
  73. "weight",
  74. "note",
  75. "added",
  76. "qr",
  77. "spool_id",
  78. )
  79. # What a label carried before the fields were selectable, so a request that
  80. # names none prints exactly what it always did.
  81. DEFAULT_LABEL_FIELDS: frozenset[LabelField] = frozenset(
  82. {"brand", "material", "hex", "name", "location", "qr", "spool_id"}
  83. )
  84. @dataclass
  85. class LabelData:
  86. """Per-spool data needed to render a label.
  87. Decoupled from the SQLAlchemy model so the same renderer serves the local
  88. inventory and the Spoolman-backed inventory.
  89. """
  90. spool_id: int
  91. name: str
  92. material: str
  93. brand: str | None = None
  94. subtype: str | None = None
  95. rgba: str | None = None # "RRGGBB" or "RRGGBBAA"; None → neutral grey
  96. extra_colors: list[str] | None = None # additional hex colours (no '#')
  97. storage_location: str | None = None
  98. deeplink_url: str = "" # what the QR encodes; caller composes it
  99. material_number: str | None = None
  100. nozzle_temp_min: int | None = None
  101. nozzle_temp_max: int | None = None
  102. label_weight: int | None = None # advertised net weight, grams
  103. note: str | None = None
  104. added: date | None = None
  105. def _temps_text(data: LabelData) -> str:
  106. """``220–240 °C``, or the one bound that is set."""
  107. lo, hi = data.nozzle_temp_min, data.nozzle_temp_max
  108. if lo and hi and lo != hi:
  109. return f"{lo}–{hi} °C"
  110. if lo or hi:
  111. return f"{lo or hi} °C"
  112. return ""
  113. def _weight_text(data: LabelData) -> str:
  114. return f"{data.label_weight} g" if data.label_weight else ""
  115. # ── Colour helpers ───────────────────────────────────────────────────────────
  116. def _color_from_hex(hex_str: str | None, fallback: Color = HexColor(0x808080)) -> Color:
  117. """Parse an RRGGBB or RRGGBBAA string (no '#') into a ReportLab Color.
  118. Alpha is honoured so multi-colour spools with translucent overlays render
  119. correctly. Falls back to ``fallback`` for None / malformed input rather
  120. than raising — labels should always print.
  121. """
  122. if not hex_str:
  123. return fallback
  124. h = hex_str.lstrip("#").strip()
  125. if len(h) not in (6, 8):
  126. return fallback
  127. try:
  128. r = int(h[0:2], 16) / 255.0
  129. g = int(h[2:4], 16) / 255.0
  130. b = int(h[4:6], 16) / 255.0
  131. a = int(h[6:8], 16) / 255.0 if len(h) == 8 else 1.0
  132. return Color(r, g, b, alpha=a)
  133. except ValueError:
  134. return fallback
  135. def _hex_code_label(rgba: str | None) -> str:
  136. """Format ``data.rgba`` as a printable ``#RRGGBB`` string for the label.
  137. Drops the alpha channel (printed labels can't show transparency) and
  138. upper-cases the hex digits to match the colour-picker convention used in
  139. the inventory UI. Returns an empty string for None / malformed input so
  140. the caller can ``if hex_code:`` skip drawing without an exception.
  141. """
  142. if not rgba:
  143. return ""
  144. h = rgba.lstrip("#").strip()
  145. if len(h) not in (6, 8):
  146. return ""
  147. rgb = h[:6]
  148. if not all(c in "0123456789abcdefABCDEF" for c in rgb):
  149. return ""
  150. return f"#{rgb.upper()}"
  151. # ── QR generation ────────────────────────────────────────────────────────────
  152. def _qr_png_bytes(payload: str, *, box_size: int = 4, border: int = 2) -> bytes:
  153. """Render ``payload`` as a tight QR PNG. Empty payload returns empty bytes
  154. so callers can skip drawing without checking ahead of time.
  155. """
  156. if not payload:
  157. return b""
  158. qr = qrcode.QRCode(
  159. version=None,
  160. # ERROR_CORRECT_L (7% recovery) rather than M (15%): a label QR only
  161. # needs to survive being scanned off clean stock, not physical damage,
  162. # and L encodes the same payload in a lower version (fewer, chunkier
  163. # modules). That extra module size is what makes the code printable on
  164. # low-resolution 203 dpi thermal printers, where M-level density bled
  165. # the modules together on small labels (#1870).
  166. error_correction=qrcode.constants.ERROR_CORRECT_L,
  167. box_size=box_size,
  168. border=border,
  169. )
  170. qr.add_data(payload)
  171. qr.make(fit=True)
  172. img = qr.make_image(fill_color="black", back_color="white")
  173. buf = io.BytesIO()
  174. img.save(buf, format="PNG")
  175. return buf.getvalue()
  176. # ── Single-label drawing ─────────────────────────────────────────────────────
  177. def _draw_swatch(c: rl_canvas.Canvas, x: float, y: float, w: float, h: float, data: LabelData) -> None:
  178. """Draw the colour swatch. Multi-colour spools use vertical stripes
  179. (matching the FilamentSwatch convention in the frontend)."""
  180. c.saveState()
  181. try:
  182. primary = _color_from_hex(data.rgba)
  183. extras = [_color_from_hex(h) for h in (data.extra_colors or []) if h]
  184. colors = [primary, *extras]
  185. if not colors:
  186. c.setFillColor(HexColor(0x808080))
  187. c.rect(x, y, w, h, stroke=0, fill=1)
  188. return
  189. stripe_w = w / len(colors)
  190. for i, col in enumerate(colors):
  191. c.setFillColor(col)
  192. c.rect(x + i * stripe_w, y, stripe_w, h, stroke=0, fill=1)
  193. # Thin black border so light-colour swatches stay visible on white labels.
  194. c.setStrokeColor(black)
  195. c.setLineWidth(0.3)
  196. c.rect(x, y, w, h, stroke=1, fill=0)
  197. finally:
  198. c.restoreState()
  199. def _roomy_qr_size(inner_w: float, inner_h: float) -> float:
  200. """QR edge length (points) for the roomy layout.
  201. Historically a flat 20% of inner width, which on the narrowest label
  202. (box_40x30, ~37.6 mm inner) rendered a ~7.5 mm QR — at 203 dpi each module
  203. fell below ~2 dots and the code bled into itself on thermal printers
  204. (#1870). A 12 mm floor keeps small labels scannable; the code is still
  205. capped by the inner height, an 18 mm absolute max, and ~45% of inner width
  206. so it can't crowd out the text column on an ultra-narrow label.
  207. """
  208. return min(max(inner_w * 0.20, 12 * mm), inner_h, 18 * mm, inner_w * 0.45)
  209. def _draw_qr(c: rl_canvas.Canvas, x: float, y: float, size: float, payload: str) -> None:
  210. """Embed a square QR at (x, y) with edge length ``size`` (in points)."""
  211. png = _qr_png_bytes(payload)
  212. if not png:
  213. return
  214. from reportlab.lib.utils import ImageReader
  215. img = ImageReader(io.BytesIO(png))
  216. c.drawImage(img, x, y, width=size, height=size, mask="auto")
  217. def _truncate_to_width(c: rl_canvas.Canvas, text: str, font: str, size: float, max_w: float) -> str:
  218. """Truncate ``text`` with an ellipsis so it fits within ``max_w`` points."""
  219. if c.stringWidth(text, font, size) <= max_w:
  220. return text
  221. ell = "…"
  222. while text and c.stringWidth(text + ell, font, size) > max_w:
  223. text = text[:-1]
  224. return text + ell if text else ell
  225. def _draw_label(
  226. c: rl_canvas.Canvas,
  227. x: float,
  228. y: float,
  229. w: float,
  230. h: float,
  231. data: LabelData,
  232. monochrome: bool = False,
  233. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  234. ) -> None:
  235. """Render one label inside the box (x, y, w, h). Origin is bottom-left.
  236. Two layouts, picked by available height:
  237. - **Tight** (h < 20 mm): swatch on the left, three lines of text on the
  238. right (brand, material+subtype, big spool ID). No QR — at very small
  239. heights there is not enough horizontal room for swatch + text + QR
  240. without truncating away the user-need fields. Kept as the safety
  241. branch for any future ultra-small preset; the shipped templates all
  242. land in the roomy layout below.
  243. - **Roomy** (h >= 20 mm — AMS holder, box label, Avery sheets): swatch
  244. on the left, QR on the right, multi-line text in the middle column.
  245. Large spool ID anchored at bottom-left under the swatch so it stays
  246. readable at arm's length.
  247. """
  248. pad = 1.2 * mm
  249. inner_x, inner_y = x + pad, y + pad
  250. inner_w = w - 2 * pad
  251. inner_h = h - 2 * pad
  252. # Outer hairline border so labels are easy to cut out from blank stock.
  253. c.setStrokeColor(HexColor(0xCCCCCC))
  254. c.setLineWidth(0.4)
  255. c.rect(x, y, w, h, stroke=1, fill=0)
  256. is_tight = h < 20 * mm
  257. if is_tight:
  258. _draw_label_tight(c, x, y, w, h, inner_x, inner_y, inner_w, inner_h, pad, data, monochrome, fields)
  259. else:
  260. _draw_label_roomy(c, x, y, w, h, inner_x, inner_y, inner_w, inner_h, pad, data, monochrome, fields)
  261. def _draw_label_tight(
  262. c: rl_canvas.Canvas,
  263. x: float,
  264. y: float,
  265. w: float,
  266. h: float,
  267. inner_x: float,
  268. inner_y: float,
  269. inner_w: float,
  270. inner_h: float,
  271. pad: float,
  272. data: LabelData,
  273. monochrome: bool = False,
  274. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  275. ) -> None:
  276. """Tight layout (h < 20 mm). Swatch + brand/material/hex/ID, no QR.
  277. Only those four lines fit, so they are the only ``fields`` it honours.
  278. """
  279. # Monochrome: drop the colour swatch (see _draw_label_roomy) and give the
  280. # width to the text column (#1870).
  281. if monochrome:
  282. swatch_w = 0.0
  283. else:
  284. swatch_w = min(inner_h, inner_w * 0.35)
  285. swatch_y = inner_y + (inner_h - swatch_w) / 2
  286. _draw_swatch(c, inner_x, swatch_y, swatch_w, swatch_w, data)
  287. text_x = inner_x + swatch_w + pad
  288. text_w = inner_w - swatch_w - pad
  289. if text_w < 5 * mm:
  290. return # Pathological — even the swatch barely fits.
  291. c.setFillColor(black)
  292. # Top: brand — bumped to bold + larger per the #809 follow-up so it's the
  293. # easiest thing to read on a small AMS holder at arm's length.
  294. brand_size = 6.5
  295. if data.brand and "brand" in fields:
  296. c.setFont("Helvetica-Bold", brand_size)
  297. brand = _truncate_to_width(c, data.brand, "Helvetica-Bold", brand_size, text_w)
  298. c.drawString(text_x, y + h - pad - brand_size, brand)
  299. # Second line: material + subtype, small
  300. sub_size = 5
  301. sub_line = " ".join(filter(None, [data.material, data.subtype])) if "material" in fields else ""
  302. sub_y_baseline = y + h - pad - brand_size - 0.6 - sub_size
  303. if sub_line:
  304. c.setFont("Helvetica", sub_size)
  305. sub_line = _truncate_to_width(c, sub_line, "Helvetica", sub_size, text_w)
  306. c.drawString(text_x, sub_y_baseline, sub_line)
  307. # Third line (when there's room): hex code, tiny — useful when the user
  308. # has multiple near-identical colours in the same material family.
  309. hex_code = _hex_code_label(data.rgba) if "hex" in fields else ""
  310. if hex_code:
  311. hex_size = 4.5
  312. hex_y = sub_y_baseline - 0.4 - hex_size
  313. # Don't render if it'd collide with the spool ID at the bottom.
  314. if hex_y > inner_y + 13:
  315. c.setFont("Helvetica", hex_size)
  316. c.drawString(text_x, hex_y, hex_code)
  317. # Bottom: BIG spool ID — the killer field at-a-glance.
  318. if "spool_id" not in fields:
  319. return
  320. id_size = 13
  321. c.setFont("Helvetica-Bold", id_size)
  322. id_text = _truncate_to_width(c, f"#{data.spool_id}", "Helvetica-Bold", id_size, text_w)
  323. c.drawString(text_x, inner_y + 0.5, id_text)
  324. def _draw_label_roomy(
  325. c: rl_canvas.Canvas,
  326. x: float,
  327. y: float,
  328. w: float,
  329. h: float,
  330. inner_x: float,
  331. inner_y: float,
  332. inner_w: float,
  333. inner_h: float,
  334. pad: float,
  335. data: LabelData,
  336. monochrome: bool = False,
  337. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  338. ) -> None:
  339. """Box-label / Avery layout. Swatch left, QR right, text middle."""
  340. # Swatch: full inner height, ~18% of inner width but capped so we never
  341. # eat the text column on extreme aspect ratios. Omitted entirely in
  342. # monochrome mode — on a B&W thermal printer a colour block prints as a
  343. # muddy grey that conveys nothing, so we reclaim the space for text and
  344. # rely on the hex-code line to carry the colour (#1870, requested by
  345. # @Geoff-S). The hex code already renders below whenever rgba is set.
  346. if monochrome:
  347. swatch_w = 0.0
  348. else:
  349. swatch_w = min(inner_w * 0.18, inner_h, 16 * mm)
  350. _draw_swatch(c, inner_x, inner_y, swatch_w, inner_h, data)
  351. # Without the QR the text column runs to the right-hand padding.
  352. if "qr" in fields:
  353. qr_size = _roomy_qr_size(inner_w, inner_h)
  354. qr_x = x + w - pad - qr_size
  355. qr_y = inner_y + (inner_h - qr_size) / 2
  356. _draw_qr(c, qr_x, qr_y, qr_size, data.deeplink_url)
  357. text_right = qr_x - 1.5 * mm
  358. else:
  359. text_right = inner_x + inner_w
  360. text_x = inner_x + swatch_w + 1.5 * mm
  361. text_w = text_right - text_x
  362. if text_w < 8 * mm:
  363. return
  364. c.setFillColor(black)
  365. # Spool ID — anchored at the bottom of the text column, big and bold. The
  366. # lines above stop short of it rather than print over it.
  367. id_size = 16
  368. show_id = "spool_id" in fields
  369. floor_y = inner_y + 0.5 + id_size if show_id else inner_y
  370. name = data.name or ""
  371. # The name line is dropped when it only repeats the brand, or the subtype
  372. # already printed beside the material (a Spoolman filament named after
  373. # its colour yields both).
  374. repeats = {data.brand or ""}
  375. if "material" in fields and data.subtype:
  376. repeats.add(data.subtype)
  377. # (field, text, font, size, gap below). Sizes and gaps of the first five
  378. # are what the label has always used; the rest share the location's.
  379. rows: list[tuple[LabelField, str, str, float, float]] = [
  380. # Brand — bumped to bold + larger per the #809 follow-up.
  381. ("brand", data.brand or "", "Helvetica-Bold", 8, 1.2),
  382. ("material", " · ".join(filter(None, [data.material, data.subtype])), "Helvetica", 7, 1.5),
  383. # Hex colour code — useful for telling near-identical material+colour
  384. # spools apart when the swatch is small or the user is colour-blind.
  385. ("hex", _hex_code_label(data.rgba), "Helvetica", 6.5, 1.2),
  386. ("name", name if name not in repeats else "", "Helvetica-Bold", 9, 1.2),
  387. ("location", data.storage_location or "", "Helvetica-Oblique", 6.5, 1.2),
  388. ("material_number", data.material_number or "", "Helvetica", 6.5, 1.2),
  389. ("temps", _temps_text(data), "Helvetica", 6.5, 1.2),
  390. ("weight", _weight_text(data), "Helvetica", 6.5, 1.2),
  391. ("note", data.note or "", "Helvetica-Oblique", 6.5, 1.2),
  392. ("added", data.added.isoformat() if data.added else "", "Helvetica", 6.5, 1.2),
  393. ]
  394. cursor_y = y + h - pad
  395. for field, text, font, size, gap in rows:
  396. if field not in fields or not text:
  397. continue
  398. if cursor_y - size < floor_y:
  399. break
  400. c.setFont(font, size)
  401. cursor_y -= size
  402. c.drawString(text_x, cursor_y, _truncate_to_width(c, text, font, size, text_w))
  403. cursor_y -= gap
  404. if show_id:
  405. c.setFont("Helvetica-Bold", id_size)
  406. id_text = _truncate_to_width(c, f"#{data.spool_id}", "Helvetica-Bold", id_size, text_w)
  407. c.drawString(text_x, inner_y + 0.5, id_text)
  408. # ── Template entry points ────────────────────────────────────────────────────
  409. # (label_w_mm, label_h_mm) for single-label-per-page templates.
  410. _SINGLE_LABEL_SIZES_MM: dict[str, tuple[float, float]] = {
  411. "ams_holder_74x33": (74.0, 33.0),
  412. "ams_holder_75x55": (75.0, 55.0),
  413. "box_40x30": (40.0, 30.0),
  414. "box_62x29": (62.0, 29.0),
  415. }
  416. # Sheet template parameters: (page_size, label_w_mm, label_h_mm,
  417. # cols, rows, top_margin_mm, left_margin_mm,
  418. # col_gap_mm, row_gap_mm)
  419. _SHEET_TEMPLATES: dict[str, tuple] = {
  420. "avery_5160": (letter, 66.675, 25.4, 3, 10, 12.7, 4.76, 3.175, 0.0),
  421. "avery_l7160": (A4, 63.5, 38.1, 3, 7, 15.15, 7.0, 2.5, 0.0),
  422. }
  423. def _render_single_label_pdf(
  424. template: TemplateName,
  425. data_list: list[LabelData],
  426. monochrome: bool = False,
  427. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  428. ) -> bytes:
  429. w_mm, h_mm = label_size_mm(template)
  430. page_w, page_h = w_mm * mm, h_mm * mm
  431. buf = io.BytesIO()
  432. c = rl_canvas.Canvas(buf, pagesize=(page_w, page_h))
  433. c.setTitle(f"Bambuddy spool labels ({template})")
  434. for data in data_list:
  435. _draw_label(c, 0, 0, page_w, page_h, data, monochrome, fields)
  436. c.showPage()
  437. c.save()
  438. return buf.getvalue()
  439. def label_size_mm(template: TemplateName) -> tuple[float, float]:
  440. """(width, height) of one label of ``template`` — a sheet's cell size."""
  441. if template in _SINGLE_LABEL_SIZES_MM:
  442. return _SINGLE_LABEL_SIZES_MM[template]
  443. if template in _SHEET_TEMPLATES:
  444. layout = _SHEET_TEMPLATES[template]
  445. return layout[1], layout[2]
  446. raise ValueError(f"Unknown label template: {template!r}")
  447. def get_sheet_capacity(template: TemplateName) -> int | None:
  448. """Return the number of slots on a sheet template, or ``None`` for roll labels."""
  449. layout = _SHEET_TEMPLATES.get(template)
  450. if layout is None:
  451. return None
  452. return layout[3] * layout[4]
  453. def _render_sheet_pdf(
  454. template: TemplateName,
  455. data_list: list[LabelData],
  456. monochrome: bool,
  457. starting_position: int,
  458. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  459. ) -> bytes:
  460. page_size, w_mm, h_mm, cols, rows, top_mm, left_mm, col_gap_mm, row_gap_mm = _SHEET_TEMPLATES[template]
  461. page_w, page_h = page_size
  462. label_w = w_mm * mm
  463. label_h = h_mm * mm
  464. top_margin = top_mm * mm
  465. left_margin = left_mm * mm
  466. col_gap = col_gap_mm * mm
  467. row_gap = row_gap_mm * mm
  468. buf = io.BytesIO()
  469. c = rl_canvas.Canvas(buf, pagesize=page_size)
  470. c.setTitle(f"Bambuddy spool labels ({template})")
  471. per_page = cols * rows
  472. if starting_position < 1 or starting_position > per_page:
  473. raise ValueError(f"Starting position must be between 1 and {per_page} for {template}")
  474. data_index = 0
  475. page_number = 0
  476. while data_index < len(data_list):
  477. slot_offset = starting_position - 1 if page_number == 0 else 0
  478. page_capacity = per_page - slot_offset
  479. chunk = data_list[data_index : data_index + page_capacity]
  480. for idx, data in enumerate(chunk):
  481. slot_index = slot_offset + idx
  482. row = slot_index // cols
  483. col = slot_index % cols
  484. x = left_margin + col * (label_w + col_gap)
  485. y = page_h - top_margin - (row + 1) * label_h - row * row_gap
  486. _draw_label(c, x, y, label_w, label_h, data, monochrome, fields)
  487. c.showPage()
  488. data_index += len(chunk)
  489. page_number += 1
  490. c.save()
  491. return buf.getvalue()
  492. def render_labels(
  493. template: TemplateName,
  494. data_list: list[LabelData],
  495. *,
  496. monochrome: bool = False,
  497. starting_position: int = 1,
  498. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  499. ) -> bytes:
  500. """Render ``data_list`` to a PDF using the named template. Returns bytes.
  501. Empty ``data_list`` still produces a valid (empty) PDF — callers should
  502. short-circuit beforehand if that's not desired.
  503. ``monochrome`` drops the colour swatch (which prints as a useless grey block
  504. on black-and-white thermal printers) and reclaims the space for text; the
  505. hex-code line still carries the colour. See #1870.
  506. ``starting_position`` is one-based and applies only to the first page of a
  507. sheet template. Later pages always begin at the first slot.
  508. ``fields`` names the lines to print (#2981); see ``ALL_LABEL_FIELDS``.
  509. """
  510. if template in _SINGLE_LABEL_SIZES_MM:
  511. if starting_position != 1:
  512. raise ValueError("Starting position is only supported for sheet label templates")
  513. return _render_single_label_pdf(template, data_list, monochrome, fields)
  514. if template in _SHEET_TEMPLATES:
  515. return _render_sheet_pdf(template, data_list, monochrome, starting_position, fields)
  516. raise ValueError(f"Unknown label template: {template!r}")
  517. def render_label_preview_pdf(
  518. template: TemplateName,
  519. data: LabelData,
  520. *,
  521. monochrome: bool = False,
  522. fields: frozenset[LabelField] = DEFAULT_LABEL_FIELDS,
  523. ) -> bytes:
  524. """One label of ``template`` on a page of its own size.
  525. For a roll template that is the label as printed; for a sheet it is one
  526. cell, which is all the preview needs to show.
  527. """
  528. w_mm, h_mm = label_size_mm(template)
  529. page_w, page_h = w_mm * mm, h_mm * mm
  530. buf = io.BytesIO()
  531. c = rl_canvas.Canvas(buf, pagesize=(page_w, page_h))
  532. _draw_label(c, 0, 0, page_w, page_h, data, monochrome, fields)
  533. c.showPage()
  534. c.save()
  535. return buf.getvalue()
  536. def pdf_to_pngs(pdf: bytes, dpi: int) -> list[bytes]:
  537. """Rasterise every page of ``pdf`` to a PNG at ``dpi``.
  538. Images are drawn without smoothing: the QR is embedded as a bitmap, and
  539. resampling it with interpolation greys the module edges, which is what
  540. makes a small code unreadable on a 203 dpi thermal printer (#1870). The
  541. PNG carries its dpi so label software prints it at the right size.
  542. """
  543. import pypdfium2 as pdfium
  544. from backend.app.services.pdf_thumbnail import _PDFIUM_LOCK
  545. pages: list[bytes] = []
  546. with _PDFIUM_LOCK:
  547. doc = pdfium.PdfDocument(pdf)
  548. try:
  549. for index in range(len(doc)):
  550. page = doc[index]
  551. try:
  552. image = page.render(scale=dpi / 72, no_smoothimage=True).to_pil()
  553. finally:
  554. page.close()
  555. out = io.BytesIO()
  556. image.convert("RGB").save(out, "PNG", dpi=(dpi, dpi), optimize=True)
  557. pages.append(out.getvalue())
  558. finally:
  559. doc.close()
  560. return pages
  561. __all__ = [
  562. "ALL_LABEL_FIELDS",
  563. "DEFAULT_LABEL_FIELDS",
  564. "LabelData",
  565. "LabelField",
  566. "TemplateName",
  567. "get_sheet_capacity",
  568. "label_size_mm",
  569. "pdf_to_pngs",
  570. "render_label_preview_pdf",
  571. "render_labels",
  572. ]
  573. # white re-exported for completeness; future templates may need a paper-tone variant.
  574. _ = white