Add box, rule and kv blocks, text folding and receipt preview
Phase 1 of docs/plans/formatters.md: single and double CP437 boxes from
one /print element, and a way to see a receipt without using paper.
- receipt: box, rule and kv elements, laid out when the job renders from
the printer profile, size and font (never fixed widths). Boxes take a
title (inline or capped), a footer, padding, fit and columns, and a
body of text or children (text, feed, kv, and rules as dividers joined
to the borders). Glyphs a code page lacks fall back per set: double-h
and double-v to double, then single, then ascii; a missing junction
switches line weight first.
- Validation names nested elements (elements[0].children[3] (qr)),
checks fields per block type, allows one level of children and counts
them toward the 500-element limit. Block fields on the older types are
problems, as they were unknown fields before.
- Text is composed to NFC and characters the code page lacks fold to
look-alikes (curly quotes, dashes, ellipsis, arrows, check marks, euro,
trademark), as the owner approved on 2026-11-29. An emoji sequence
prints as one '?'. Encodable text is untouched.
- escpos: CodePage.CanEncode and Decode, and Interpret, which reads a
command stream back as the printer would print it. It takes the
profile so that it can follow the printer's own wrapping and
alignment; raw spans stay opaque.
- POST /api/v1/preview and `uberbringer preview` show the lines a job
prints, as text or JSON with styles, without fetching images.
- Config: [format] max_lines (default 2000), refused with 422
too_many_lines on preview; printer.box_line_spacing (default 0).
Byte compatibility: testdata/compat fixtures were rendered by 9b91109
before the renderer changed, and still match it and the new renderer.
examples/blocks.json was printed on the TM-T88IV; the owner judged the
border gaps at the default spacing fine (2026-11-30), so
box_line_spacing stays 0, and TestPaperReceipts pins its bytes.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
9fdea32b4f
commit
4562f0cebb
109 files changed
+6383
-487
No files matched your search
@@ -7,11 +7,15 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
|
||||
order on a background worker, with retries when the printer is offline.
|
||||
- **Plain-text input**: send UTF-8 text, including accents, `£ ° ±` and
|
||||
box-drawing `┌─┐│└┘░▒▓`. It is transcoded to the printer's code page
|
||||
(CP437 by default).
|
||||
(CP437 by default), and typographic quotes, dashes and the ellipsis
|
||||
print as ASCII look-alikes where the code page lacks them.
|
||||
- **Word wrap**: text wraps at word boundaries for the paper width and
|
||||
character size, so words are never cut in half.
|
||||
- **Rich elements**: bold, underline, inverse, sizes 1–8, two fonts,
|
||||
alignment, QR codes, EAN/UPC/CODE39/CODE128 barcodes, images, raw ESC/POS.
|
||||
- **Boxes, rules and key-value rows**: single or double CP437 borders with
|
||||
titles, dividers and footers, sized to the paper when the job prints.
|
||||
- **Preview**: see the exact lines a job prints, without using paper.
|
||||
- **Images that print well**: PNG, JPEG, GIF or WebP from a URL or base64,
|
||||
scaled to the paper and dithered. Image URLs can't reach internal network
|
||||
addresses unless you allow it.
|
||||
@@ -23,6 +27,7 @@ REST API and prints them on an EPSON ESC/POS network receipt printer.
|
||||
- [Quick start](#quick-start)
|
||||
- [API](#api)
|
||||
- [Elements](#elements)
|
||||
- [Blocks](#blocks)
|
||||
- [Migrating from the old format](#migrating-from-the-old-format)
|
||||
- [Configuration](#configuration)
|
||||
- [Command line](#command-line)
|
||||
@@ -121,6 +126,7 @@ included, carry `Cache-Control: no-store`.
|
||||
| Method | Path | Purpose |
|
||||
|--------|--------------------|------------------------------------------|
|
||||
| POST | `/api/v1/print` | Queue a print job |
|
||||
| POST | `/api/v1/preview` | Show the lines a job prints, without printing it |
|
||||
| GET | `/api/v1/jobs/:id` | Job status |
|
||||
| GET | `/healthz` | Printer and queue health (no auth) |
|
||||
| GET | `/` | Version information (no auth) |
|
||||
@@ -133,8 +139,8 @@ curl -X POST https://printer.example.com/api/v1/print \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"elements": [
|
||||
{"type": "text", "text": "▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓"},
|
||||
{"type": "text", "text": "┌─────────────────────┐\n│ !!! ACHTUNG !!! │\n└─────────────────────┘", "align": "center"},
|
||||
{"type": "rule", "style": "dark"},
|
||||
{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"},
|
||||
{"type": "text", "text": "Überbringer", "size": 2, "bold": true, "align": "center"},
|
||||
{"type": "feed"},
|
||||
{"type": "text", "text": "Long paragraphs wrap at word boundaries for the paper width, so a word is never split across two lines."},
|
||||
@@ -175,6 +181,70 @@ curl -H "Authorization: Bearer $TOKEN" https://printer.example.com/api/v1/jobs/j
|
||||
`status` is `queued`, `printing`, `done` or `failed`. A failed job includes an
|
||||
`error` field. The last `queue.history` finished jobs are kept.
|
||||
|
||||
### Preview a receipt
|
||||
|
||||
`POST /api/v1/preview` takes the same body as `/api/v1/print` and validates
|
||||
it the same way, but prints nothing and fetches no images. It answers `200`
|
||||
with the lines the printer would print, as `text/plain; charset=utf-8`:
|
||||
|
||||
```sh
|
||||
curl -X POST https://printer.example.com/api/v1/preview \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{"elements": [{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"},
|
||||
{"type": "qr", "data": "https://example.com"}]}'
|
||||
```
|
||||
|
||||
```text
|
||||
┌─────────────────────┐
|
||||
│ !!! ACHTUNG !!! │
|
||||
└─────────────────────┘
|
||||
[qr: https://example.com]
|
||||
- - - - - - - partial cut - - - - - - - -
|
||||
```
|
||||
|
||||
- The preview is read back from the bytes the job renders to, so it shows
|
||||
what the printer receives: wrapping, folded characters, `?` for missing
|
||||
ones and the final cut.
|
||||
- Centred and right-aligned text is indented as the printer places it,
|
||||
counted in Font A columns. Text at a larger size shows each character
|
||||
once.
|
||||
- QR codes, barcodes, images, `raw` bytes and cuts print as placeholders
|
||||
such as `[barcode ean13: 4006381333931]`, `[image 384 dots: logo.png]` and
|
||||
`[raw 3 bytes]`.
|
||||
|
||||
With `Accept: application/json` the answer carries the styles too. For
|
||||
`[{"type": "kv", "pairs": [{"key": "Total", "value": "£12.50", "bold": true}]},
|
||||
{"type": "text", "text": "Thanks 🎉", "align": "center"},
|
||||
{"type": "qr", "data": "https://example.com"}]`:
|
||||
|
||||
```json
|
||||
{"columns": 42, "codepage": "cp437", "line_count": 3,
|
||||
"lines": [{"kind": "text", "text": "Total ............................. £12.50",
|
||||
"runs": [{"from": 0, "to": 5, "bold": true}, {"from": 36, "to": 42, "bold": true}]},
|
||||
{"kind": "text", "text": " Thanks ?"},
|
||||
{"kind": "qr", "text": "[qr: https://example.com]", "data": "https://example.com"},
|
||||
{"kind": "cut", "text": " - - - - - - - partial cut - - - - - - - -", "data": "partial"}],
|
||||
"warnings": ["elements[1]: 1 character not in cp437 printed as ?"]}
|
||||
```
|
||||
|
||||
| Field | Meaning |
|
||||
|-------|---------|
|
||||
| `columns` | Font A characters per line |
|
||||
| `codepage` | The code page text is printed in |
|
||||
| `line_count` | Lines the receipt prints, all copies counted: text lines, fed lines, and one for each QR code, barcode and image. [`format.max_lines`](#configuration) limits it |
|
||||
| `lines[].kind` | `text`, `qr`, `barcode`, `image`, `raw` or `cut` |
|
||||
| `lines[].text` | The line as it prints, or the placeholder |
|
||||
| `lines[].runs` | Styled parts of `text`, in characters from `from` up to `to`: `bold`, `underline` (1 or 2), `invert`, `font` (`b`), and `width` and `height` when scaled. Plain Font A text at size 1 has no run |
|
||||
| `lines[].data` | QR code or barcode data, the image URL (or `base64`), the number of raw bytes, or the cut mode |
|
||||
| `warnings` | Elements with characters the code page lacks, and images wider than the paper |
|
||||
|
||||
A job that would print more than `format.max_lines` lines answers `422`
|
||||
`too_many_lines`, for example `receipt would print 2412 lines, limit is
|
||||
2000`. Sent to `/api/v1/print`, the same job is accepted and then fails
|
||||
when the worker renders it, before anything is sent; its `error` reads
|
||||
`rendering: receipt would print 2412 lines, limit is 2000`.
|
||||
|
||||
### Health
|
||||
|
||||
`GET /healthz` returns `200` when the printer is reachable and ready, and
|
||||
@@ -213,7 +283,9 @@ Errors are JSON:
|
||||
- `code` is stable and meant for clients to match on.
|
||||
- `error` is for people and may change. It never repeats the HTTP
|
||||
framework's own text; for example, an unknown route answers `not found`.
|
||||
- `details` appears only when an `invalid_job` fails validation.
|
||||
- `details` appears only when an `invalid_job` fails validation. Each entry
|
||||
names the element by its path, e.g.
|
||||
`elements[0].children[3] (qr): not allowed inside a box; place it after the box`.
|
||||
|
||||
| Status | `code` | Meaning |
|
||||
|--------|--------|---------|
|
||||
@@ -225,6 +297,7 @@ Errors are JSON:
|
||||
| 405 | `method_not_allowed` | Known route, wrong method, e.g. `DELETE /api/v1/print` with a valid token (without one, `/api/v1` answers `401` first). Sent with `Allow` |
|
||||
| 408 | `request_timeout` | The request was not received in time |
|
||||
| 413 | `body_too_large` | Body larger than `webserver.body_limit` |
|
||||
| 422 | `too_many_lines` | From `/api/v1/preview`: the job would print more than `format.max_lines` lines |
|
||||
| 429 | `rate_limited` | Rate limit exceeded. `Retry-After` gives the seconds to wait |
|
||||
| 431 | `headers_too_large` | Request headers too large |
|
||||
| 500 | `internal_error` | Unexpected failure. The cause is logged and reported to Sentry, never sent to the client |
|
||||
@@ -244,7 +317,8 @@ to the printer unless the whole receipt rendered.
|
||||
|
||||
A job is `{"elements": [...], "copies": 1}`. `copies` is 1–5, and each copy is
|
||||
cut separately. A partial cut is added after the last element unless that
|
||||
element is already a `cut`.
|
||||
element is already a `cut`. Boxes, rules and key-value rows are described
|
||||
under [Blocks](#blocks).
|
||||
|
||||
### `text`
|
||||
|
||||
@@ -262,8 +336,21 @@ element is already a `cut`.
|
||||
| `wrap` | `true` | `false` sends the text as-is and lets the printer wrap |
|
||||
|
||||
**Encoding.** Text is transcoded from UTF-8 to `printer.codepage`, CP437 by
|
||||
default. Characters the code page lacks, such as emoji, print as `?`. Control
|
||||
characters are removed so text can never be read as printer commands.
|
||||
default. Control characters are removed so text can never be read as printer
|
||||
commands. Before that, the text is prepared for the code page:
|
||||
|
||||
- It is composed (Unicode NFC), so a decomposed `é` (an `e` and a combining
|
||||
accent) prints as `é`.
|
||||
- Characters the code page lacks fold to look-alikes: `“ ” „` print as `"`,
|
||||
`‘ ’` as `'`, `–` as `-`, `—` as `--`, `…` as `...`, `•` as `·`, `→` as
|
||||
`->`, `←` as `<-`, `✓ ✔` as `√` (or `x` without `√`), `×` as `x`, `€` as
|
||||
`EUR` and `™` as `TM`. Where the code page has the character, as cp1252
|
||||
has curly quotes and cp858 has `€`, it prints as itself.
|
||||
- An emoji prints as one `?`, together with its skin tone, its variation
|
||||
selector and any emoji joined to it, so `👨👩👧` is one `?`. Zero-width
|
||||
spaces and joiners are removed.
|
||||
- Any other character the code page lacks prints as `?`. The
|
||||
[preview](#preview-a-receipt) lists the elements that have one.
|
||||
|
||||
**Word wrap.** The line width comes from the printer model and the character
|
||||
size: on a TM-T88, 42 characters at size 1, 21 at size 2, and so on. Lines break at spaces,
|
||||
@@ -325,6 +412,133 @@ or link-local addresses (including cloud metadata endpoints) are refused unless
|
||||
|--------|-----------|--------|
|
||||
| `mode` | `partial` | `partial`, `full` |
|
||||
|
||||
## Blocks
|
||||
|
||||
`box`, `rule` and `kv` are blocks: they are laid out when the job prints, from
|
||||
the printer model, so one job fits the TM-T88's 42 columns as well as the
|
||||
TM-T20's 48. A block starts on a new line, and what follows it starts at the
|
||||
left margin. These fields work on all three:
|
||||
|
||||
| Field | Default | Values |
|
||||
|-----------|---------|--------|
|
||||
| `size` | `1` | 1–3. Scales the borders and the text together: 42, 21 or 14 columns on a TM-T88 |
|
||||
| `font` | `a` | `a`, or `b` (56 columns at size 1 on a TM-T88) |
|
||||
| `columns` | the line | 1–255. A fixed width in characters of the block's own size and font. It is cut to the line, and a narrower block is centred |
|
||||
|
||||
Borders and fills are never bold, underlined or inverted. On the blocks, a
|
||||
field that does not apply is an error, e.g.
|
||||
`elements[3] (rule): field "pairs" does not apply to rule`. A long title,
|
||||
footer or label is cut with `...` instead of failing.
|
||||
|
||||
### `box`
|
||||
|
||||
```json
|
||||
{"type": "box", "style": "double", "title": "ACHTUNG", "title_style": "capped", "align": "center",
|
||||
"text": "The coffee machine is being descaled.\nDo not use until 10:30."}
|
||||
```
|
||||
|
||||
```text
|
||||
╔═╡ ACHTUNG ╞════════════════════════════╗
|
||||
║ The coffee machine is being descaled. ║
|
||||
║ Do not use until 10:30. ║
|
||||
╚════════════════════════════════════════╝
|
||||
```
|
||||
|
||||
```json
|
||||
{"type": "box", "fit": true, "padding": 3, "text": "!!! ACHTUNG !!!"}
|
||||
```
|
||||
|
||||
```text
|
||||
┌─────────────────────┐
|
||||
│ !!! ACHTUNG !!! │
|
||||
└─────────────────────┘
|
||||
```
|
||||
|
||||
| Field | Default | Values |
|
||||
|---------------|----------|--------|
|
||||
| `text` | | The body. It wraps at word boundaries, and `\n` starts a new paragraph. Set `text` or `children`, not both |
|
||||
| `children` | | The body as elements; see below |
|
||||
| `style` | `single` | `single` ┌─┐, `double` ╔═╗, `double-h` ╒═╕ (double lines across, single down), `double-v` ╓─╖ (single across, double down), `ascii` +-+ |
|
||||
| `title` | | Text set into the top border |
|
||||
| `title_style` | `inline` | `inline` `┌─ Title ───┐`, or `capped` `╔═╡ Title ╞══╗` |
|
||||
| `footer` | | Text set into the bottom border, on the right: `└──── footer ──┘` |
|
||||
| `align` | `left` | Alignment of `text`, and the default for text children |
|
||||
| `bold`, `underline`, `invert` | | Styles of `text`, as on a `text` element |
|
||||
| `padding` | `1` | 0–3 spaces between the side borders and the body |
|
||||
| `fit` | `false` | `true` shrinks the box to its widest line, title and footer included, and centres it. `columns` is then the most it may take |
|
||||
|
||||
**Children.** A box takes one level of these, and each prints inside the
|
||||
borders:
|
||||
|
||||
| Type | Fields | Inside a box |
|
||||
|--------|--------|--------------|
|
||||
| `text` | `text`, `bold`, `underline`, `invert`, `align`, `wrap` | `size` and `font` come from the box. `"newline": false` is not allowed. `"wrap": false` splits lines at the box edge instead of at spaces |
|
||||
| `feed` | `lines` | Empty lines between the borders |
|
||||
| `rule` | `style` (`single` or `double`), `text`, `align`, `bold` | A divider joined to the side borders: `├──┤`, `╞══╡`, `╟──╢` or `╠══╣` to suit the box. A label reads `├── Label ───┤` |
|
||||
| `kv` | `pairs`, `leader` | Key-value rows across the inside of the box |
|
||||
|
||||
`box`, `qr`, `barcode`, `image`, `raw` and `cut` cannot go inside a box;
|
||||
place them after it. Children count toward the 500-element limit.
|
||||
|
||||
### `rule`
|
||||
|
||||
| Field | Default | Values |
|
||||
|---------|----------|--------|
|
||||
| `style` | `single` | `single` ─, `double` ═, `light` ░, `medium` ▒, `dark` ▓, `solid` █, `dashed` `- -`, `dotted` ·, `ascii` - |
|
||||
| `text` | | A label set into the line |
|
||||
| `align` | `center` | Where the label sits: `───── TODAY ─────`, or `── Notes ──────` at the left |
|
||||
| `bold` | `false` | Prints the label bold |
|
||||
|
||||
### `kv`
|
||||
|
||||
```json
|
||||
{"type": "kv", "pairs": [{"key": "Host", "value": "nas01"},
|
||||
{"key": "Note", "value": "The scrub finished with 0 errors. Next scrub Sunday 03:00."},
|
||||
{"key": "Used", "value": "94%", "bold": true}]}
|
||||
```
|
||||
|
||||
```text
|
||||
Host ............................... nas01
|
||||
Note ... The scrub finished with 0 errors.
|
||||
Next scrub Sunday 03:00.
|
||||
Used ................................. 94%
|
||||
```
|
||||
|
||||
| Field | Default | Values |
|
||||
|----------|---------|--------|
|
||||
| `pairs` | | Required. 1–100 rows of `{"key": "...", "value": "...", "bold": false}`. `key` is required; `bold` prints the key and the value bold |
|
||||
| `leader` | `.` | The fill between key and value: `.`, `·`, `" "` (or `"space"`), `_`, `-` or `─` |
|
||||
|
||||
A value too long for its line wraps into the room after the key, and its
|
||||
further lines are right-aligned. A key too long for the line is cut with
|
||||
`...`.
|
||||
|
||||
### Glyphs and code pages
|
||||
|
||||
CP437, the default, has every glyph the blocks draw with. Other code pages
|
||||
fall back, and the [preview](#preview-a-receipt) shows the result:
|
||||
|
||||
| Code page | Boxes | Rules |
|
||||
|-----------|-------|-------|
|
||||
| `cp437` | All styles as listed | All styles |
|
||||
| `cp850`, `cp858` | `double-h` and `double-v` print as `double`. A divider whose junction the page lacks switches to the other line weight, so `╞══╡` prints as `├──┤` and `╟──╢` as `╠══╣`. A capped title on double lines uses `╣ ╠` | All styles |
|
||||
| `cp1252` | Every box is `ascii`, drawn with `+`, `-` and `\|`, with `=` for double dividers | `─ ═` print as `- =`, shades as `#` |
|
||||
|
||||
For your own text on CP437:
|
||||
|
||||
- **Prints:** box drawing `┌─┐│└┘├┤┬┴┼ ╔═╗║╚╝╠╣╦╩╬ ╒╓╕╖╘╙╛╜╞╟╡╢╤╥╧╨╪╫`,
|
||||
shades and blocks `░▒▓█▀▄▌▐■`, and `· ∙ √ ° ± » « £ ¥ ½ ¼` and accented
|
||||
Latin letters.
|
||||
- **Never prints as itself:** `•` and emoji, and `► ◄ → ←` and the other
|
||||
symbols CP437 keeps at byte values below 0x20, which the printer reads as
|
||||
commands. `•` folds to `·` and `→ ←` to `-> <-`; the rest print as `?`. Use
|
||||
`· ∙ ■ » √ °` instead.
|
||||
|
||||
`examples/blocks.json` prints every style, padding, size and junction on one
|
||||
receipt, for checking the borders on paper. Send it as the body of
|
||||
`/api/v1/print`, or look at it first with
|
||||
`uberbringer preview examples/blocks.json`.
|
||||
|
||||
## Migrating from the old format
|
||||
|
||||
The endpoint is still `POST /api/v1/print`, but the body changed from
|
||||
@@ -405,6 +619,14 @@ Settings worth knowing:
|
||||
`columns` (Font A characters per line) override the model.
|
||||
- `printer.codepage`: `cp437` (default), `cp850`, `cp858` (has €) or
|
||||
`cp1252`.
|
||||
- `printer.box_line_spacing` (default `0`): the line spacing, in motion
|
||||
units (ESC 3, 0–255), used while a box prints. Lines of box drawing leave
|
||||
small gaps in the vertical borders at the printer's default spacing; a
|
||||
value checked on paper closes them. `0` keeps the default, which was
|
||||
checked on a TM-T88IV with `examples/blocks.json` and looks fine.
|
||||
- `format.max_lines` (default `2000`): a job that would print more lines,
|
||||
all copies counted, fails instead of printing. It is a backstop against
|
||||
runaway text; `/api/v1/preview` answers such a job with `422`.
|
||||
- `webserver.trusted_proxies` / `proxy_header`: the real client IP for
|
||||
per-client rate limits comes from the `X-Real-IP` header set by nginx on
|
||||
`127.0.0.1`.
|
||||
@@ -433,9 +655,17 @@ Settings worth knowing:
|
||||
uberbringer [--config config.toml] run the daemon (default command)
|
||||
uberbringer secret print a new random API secret
|
||||
uberbringer token [--subject s] [--ttl 720h] print a signed bearer token
|
||||
uberbringer preview [file.json|-] show the lines a job would print
|
||||
uberbringer version print the version
|
||||
```
|
||||
|
||||
`preview` reads a job from the file, or from standard input with `-` or no
|
||||
argument, and lays it out for the printer in the config, as
|
||||
`/api/v1/preview` does. It prints nothing and fetches no images. On a
|
||||
terminal it shows bold, underlined and inverted text as such; warnings go
|
||||
to standard error. It reads the same config as the daemon, so
|
||||
`api.secret` and `printer.address` must be set even though neither is used.
|
||||
|
||||
The daemon shuts down gracefully on SIGINT/SIGTERM. A receipt that is already
|
||||
printing is finished, and jobs still waiting are marked failed.
|
||||
|
||||
@@ -486,13 +716,14 @@ cmd/uberbringer/ main: build info, signals, exit code
|
||||
internal/app/uberbringer/ CLI commands and wiring
|
||||
server/ Fiber HTTP API, auth, health
|
||||
internal/pkg/config/ TOML config: defaults and validation
|
||||
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status
|
||||
internal/pkg/receipt/ Job format, validation, word wrap, rendering
|
||||
internal/pkg/escpos/ ESC/POS command builder, code pages, barcodes, QR, raster, status, interpreter
|
||||
internal/pkg/receipt/ Job format, validation, text folding, word wrap, blocks, rendering, preview
|
||||
internal/pkg/raster/ Image decoding, scaling and dithering
|
||||
internal/pkg/safehttp/ SSRF-guarded image fetching
|
||||
internal/pkg/printer/ TCP printer client (port 9100) and status queries
|
||||
internal/pkg/printqueue/ Job queue, worker and status history
|
||||
configs/ Example configuration
|
||||
examples/ Example jobs, such as the block calibration receipt
|
||||
packaging/ systemd unit
|
||||
docs/ Design notes and feature plans
|
||||
```
|
||||
|
||||
Reference in new issue
Block a user