> Tillcast is live: the API at https://api.tillcast.com/v1 and the dashboard at https://dashboard.tillcast.com. A key prints on real printers, so do not call the API unless asked. A job carries its receipt as "document", an array of blocks (the recommended way), or as "receiptline", ReceiptLine text, exactly one of the two: read https://docs.tillcast.com/create-a-print-job.md and https://docs.tillcast.com/concepts/documents.md before you write a job body. Do not code against what does not exist yet: webhooks, a template language, stored templates (a job has no template field), OAuth connections and connectors for Make, Zapier and n8n, and OAuth sign-in for the MCP server. SDKs for TypeScript (@tillcast/sdk, version 0.2.0 or later for blocks) and Python (tillcast) exist as pre-1.0 versions. To show a receipt in a web page without printing, there are the npm packages @tillcast/preview and @tillcast/html-render (0.x, no API key, no call to Tillcast to draw): read https://docs.tillcast.com/preview-a-receipt.md. The docs are the source of truth: check the index https://docs.tillcast.com/llms.txt and https://docs.tillcast.com/roadmap.md before you code against anything. For clean Markdown of any page, append .md to the page URL. The Tillcast MCP server is live at https://api.tillcast.com/mcp and takes an API key as a bearer token (setup: https://docs.tillcast.com/connect-an-ai-assistant.md). It acts on the live account and its tools print on real paper, so do not connect to it or call its tools unless the owner asked you to. The MCP server at https://docs.tillcast.com/_mcp/server is a different one: it only searches these docs and cannot call the Tillcast API.

# Receipt documents

> How to write a Tillcast receipt document with blocks: text, rows and tables, rules, barcodes, QR codes and images. ReceiptLine text is the advanced way.

A job carries a **document**: the receipt, as an array of **blocks** in the order they print. A block is one visible unit, such as a line of text, a table, a rule or a QR code, and it says what it is in its `type`. You never write printer commands and you never write markup. Tillcast turns the blocks into the commands of the printer's [profile](/printers/profiles) when it accepts the job, so the same document prints on a Star and on an Epson.

The text of a block prints as it is written. A `|`, a `{`, a `_` or a line of dashes in a name is a character and not markup, so there is nothing to escape.

If you already have a document written for other [ReceiptLine](https://www.npmjs.com/package/receiptline) tools, you can send it as text in the field `receiptline` instead. See [Advanced: ReceiptLine text](#advanced-receiptline-text).

Rendering happens when the job is accepted. A mistake in a document is therefore an answer to your request, not a job that fails later. The answer says how large the print is and lists what the renderer noticed, see [Warnings](#warnings). Tillcast does not keep the document: no call returns it and nothing logs it. To print it again, send it again.

## A first document

This document has a title, a line with the table number and a table with two items and a total.

```bash wordWrap
curl https://api.tillcast.com/v1/printers/prn_01M44X7TQ0A9R2H5J8K1M4N7P0/jobs \
  -H "Authorization: Bearer $TILLCAST_API_KEY" \
  -H "Tillcast-Version: 2026-10-01" \
  -H "Idempotency-Key: order-4711-bill" \
  -H "Content-Type: application/json" \
  -d '{
    "document": [
      {"type": "text", "text": "Harbour Cafe", "align": "center", "bold": true, "size": 2},
      {"type": "text", "text": "Table 7", "align": "center"},
      {"type": "table", "columns": ["*", {"width": 9, "align": "right"}],
       "rows": [["Flat white", "3.40"], ["Lemon cake", "4.20"], {"type": "rule"},
                [{"text": "Total", "bold": true}, {"text": "7.60", "bold": true}]]}
    ],
    "client_reference_id": "order-4711"
  }'
```

The examples on this page come with a **text view**, 32 characters wide, as a 58 mm printer would print it. The text view cannot show bold, underline or inverse, and it shows a line of double size with a space after every letter.

```text
    H a r b o u r   C a f e
             Table 7
Flat white                  3.40
Lemon cake                  4.20
--------------------------------
Total                       7.60
```

The paper is cut at the end of every document, unless the printer's `print_options` say `cutting: false`. See [Profiles and print options](/printers/profiles).

A job takes `document` or `receiptline`, exactly one of the two. Both, or neither, is `422 document_invalid`. The SDKs cannot tell you before the call, because both fields are optional in their types.

## Blocks

Every block is an object with a `type`. A field that a block does not have is refused, and so is a `type` that is not one of these nine.

| `type`    | What it prints                   | Fields besides `type`                                             |
| --------- | -------------------------------- | ----------------------------------------------------------------- |
| `text`    | Text on its own line             | `text`, `align`, `wrap` and the style fields                      |
| `table`   | Rows of cells in columns         | `columns`, `rows`, `border`, `align`, `wrap` and the style fields |
| `row`     | One line of cells in columns     | `cells`, `columns`, `align`, `wrap` and the style fields          |
| `rule`    | A rule across the paper          | none                                                              |
| `cut`     | A cut of the paper at that place | none                                                              |
| `feed`    | Blank lines                      | `lines`                                                           |
| `barcode` | A barcode                        | `data`, `symbology`, `hri`, `module_width`, `height`, `align`     |
| `qr`      | A QR code                        | `data`, `cell`, `level`, `align`                                  |
| `image`   | A PNG image                      | `data`, `align`                                                   |

Most fields can be left out. What a field does when it is not said is written below.

### Text and style

`text` is a string, or a list of pieces. A piece is a string or an object with its own style, such as `{"text": "7.60", "bold": true}`. `align` is `left` (the default), `center` or `right`. A line break in the text is a line break on the paper. A text that is longer than the paper wraps at the edge, by characters and not by words, unless `wrap` is `false`: then it is cut at the edge. The renderer counts every character as one column, wide ones such as Chinese, Japanese, Korean and emoji too. A character that the printer's code page lacks prints as `?`, with the warning `character_unmappable`.

`text`, `row` and `table` take four style fields. They are independent, and any of them goes with any other.

| Field       | Meaning                                                                                                                                                                                                                                      |
| ----------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `bold`      | `true` for bold                                                                                                                                                                                                                              |
| `underline` | `true` for underlined                                                                                                                                                                                                                        |
| `invert`    | `true` for white on black                                                                                                                                                                                                                    |
| `size`      | A number from 1 to 6, the factor in both directions: 1 is normal and 2 is twice as wide and twice as high. `{"width": 2}` is twice as wide only and `{"height": 2}` is twice as high only. Other values, such as `{"width": 3}`, are refused |

A piece of a text, and a cell of a row or a table, can say its own style. What it does not say it takes from what is around it. A line is as high as its highest piece.

```json
[
  {"type": "text", "text": "Harbour Cafe", "align": "center", "bold": true, "size": 2},
  {"type": "text", "text": ["Total ", {"text": "7.60", "bold": true, "underline": true}], "align": "right"},
  {"type": "text", "text": "Table {VIP} | Code_A_7", "align": "center"}
]
```

```text
    H a r b o u r   C a f e
                      Total 7.60
     Table {VIP} | Code_A_7
```

The third line shows what the blocks are for: a brace, a bar and underscores print as they are.

### Rows and tables

A `table` declares its `columns` once and then has `rows`. A `row` is one line of cells with its own `columns`. Without `columns`, the cells of a row share the line equally.

A column is one of these:

* A width in characters, such as `9`. A width is 1 to 96.
* `"*"`: what the other columns leave.
* `{"width": 9, "align": "right"}`: a width, an alignment, or both. The text of a column sits on the left unless it says otherwise.

A cell is a string, or an object with its own style and alignment: `{"text": "Total", "bold": true, "align": "right"}`. A row has at most as many cells as there are columns. A shorter row leaves the last columns empty. A table has at most 16 columns.

`border` is `space` (one space between the columns, the default), `none`, or `line` (a ruled frame around every cell). A table with fixed widths only and no `"*"` column is narrower than the paper, and `align` says where it sits. With a `"*"` column it fills the paper.

A `{"type": "rule"}` among the rows is a horizontal rule. In a table with `border: "line"` it is a line between two rows, so it must stand between two rows.

A column counts characters of normal size. A cell of size 2 holds half as many in the same column, and a size whose characters are wider than the column is refused. A long cell wraps inside its column, by characters, unless `wrap` is `false`: then it is cut at the end of its column.

```json
[
  {"type": "table", "border": "line", "columns": ["*", {"width": 4, "align": "right"}, {"width": 8, "align": "right"}],
   "rows": [["Item", "Qty", "Price"], {"type": "rule"}, ["Flat white", "1", "3.40"], ["Lemon cake", "2", "8.40"]]},
  {"type": "row", "columns": [10, "*"], "cells": ["Left", {"text": "Right", "align": "right"}]}
]
```

```text
+----------------+----+--------+
|Item            | Qty|   Price|
+----------------+----+--------+
|Flat white      |   1|    3.40|
|Lemon cake      |   2|    8.40|
+----------------+----+--------+
Left                       Right
```

### Rules, cuts and blank lines

`{"type": "rule"}` is a rule across the paper. `{"type": "cut"}` cuts the paper at that place. `{"type": "feed", "lines": 2}` makes 1 to 20 blank lines, and one if `lines` is left out.

Tillcast cuts at the end of every document anyway, so a `cut` as the last block cuts a second time. Use `cut` between two receipts that you send as one document.

```json
[
  {"type": "text", "text": "Open daily"},
  {"type": "rule"},
  {"type": "text", "text": "See you soon", "align": "center"},
  {"type": "feed", "lines": 2},
  {"type": "text", "text": "Receipt 2", "align": "right"}
]
```

```text
Open daily
--------------------------------
          See you soon


                       Receipt 2
```

### Barcodes, QR codes and images

Each of these is a line of its own, with `align` (`left` by default). They cannot stand next to text. To put a code beside a text, print them one under the other.

```json
[
  {"type": "barcode", "data": "5901234123457", "symbology": "ean", "hri": true, "align": "center"},
  {"type": "qr", "data": "https://example.com/r/4711", "cell": 4, "level": "m", "align": "center"},
  {"type": "image", "data": "<a PNG file, base64>", "align": "center"}
]
```

* **`barcode`.** `symbology` is `code128` (the default), `upc`, `ean` (or JAN), `code39`, `itf`, `codabar` (or NW-7) or `code93`. `hri` prints the data under the bars. `module_width` is the width of the thinnest bar in dots, 2 to 4 (2 by default). `height` is the height of the bars in dots, 24 to 240 (72 by default).
* **The data of a barcode** is held to what the symbology takes, up to 128 characters, and refused if the renderer would print nothing for it. `upc` takes 11 or 12 digits, or 7 or 8 digits that start with 0. `ean` takes 12 or 13 digits, or 7 or 8. `itf` takes an even number of digits. `code39` takes digits, capital letters, the space and `- . $ / + %`. `codabar` takes digits, `- $ : / . +`, and a letter from A to D at the start and at the end. `code93` and `code128` take printable ASCII.
* **`qr`.** `data` is text of 1 to 2,048 characters, with line feeds if you like and no other control character. `cell` is the size of one square in dots, 3 to 8 (3 by default). `level` is the error correction, `l`, `m`, `q` or `h` (`l` by default).
* **`image`.** `data` is the PNG file in base64, up to 200,000 characters. A monochrome PNG gives the best result. An image is never scaled, and an image over the limits is skipped with a warning. The limits are in [Limits and refusals](#limits-and-refusals).

The text view shows nothing for a code or an image, so these have no text view.

## Build a document from your data

Put the text from your own data into a block as it is. Tillcast writes the escapes for you.

#### TypeScript

```ts
import type { Tillcast } from "@tillcast/sdk";

type Item = { name: string; price: string };

function receipt(shop: string, items: Item[], total: string): Tillcast.Block[] {
  return [
    { type: "text", text: shop, align: "center", bold: true, size: 2 },
    {
      type: "table",
      columns: ["*", { width: 9, align: "right" }],
      rows: [
        ...items.map((item) => [item.name, item.price]),
        { type: "rule" },
        [{ text: "Total", bold: true }, { text: total, bold: true }],
      ],
    },
  ];
}
```

#### Python

```python
from tillcast import BlockParams


def receipt(shop: str, items: list[tuple[str, str]], total: str) -> list[BlockParams]:
    return [
        {"type": "text", "text": shop, "align": "center", "bold": True, "size": 2},
        {
            "type": "table",
            "columns": ["*", {"width": 9, "align": "right"}],
            "rows": [
                *[[name, price] for name, price in items],
                {"type": "rule"},
                [{"text": "Total", "bold": True}, {"text": total, "bold": True}],
            ],
        },
    ]
```

Pass the result as `document` of `client.jobs.create`. A name such as `Tom | {Bar} --- ~ _` prints as it is. Give the function a return type, as above: a document that is built in a variable without a type is read as plain strings and dicts, and the type checker refuses it as `document`.

## Errors in a document

A block that cannot be printed as it is said is `422 document_invalid`. `param` is the path of the first problem, in the order of the document. The message holds the path and the names of fields and numbers, and never a piece of your text.

```json wordWrap
{
  "error": {
    "type": "invalid_request_error",
    "code": "document_invalid",
    "message": "document[3].rows[1][0].size must be at most 6.",
    "param": "document[3].rows[1][0].size",
    "request_id": "req_01M466JX008T2V5X7Z9C1E3G5H"
  }
}
```

* **A block that is not an object, or has no `type`, or a `type` that is not one of the nine,** and **a field the block does not have**: for example `document[2].colour is not a field of a text block`.
* **A value out of its range or of the wrong kind:** `document[1].align must be one of left, center, right`, `document[4].columns[1] must be at most 96`.
* **Something the paper cannot show:** a rule in a ruled table at the top, at the bottom or next to another rule, a size that does not fit its column, a row with more cells than columns, barcode data that its symbology does not take, a control character in a text. Each names the path of the thing. Control characters are refused and not removed.
* **Both `document` and `receiptline`, or neither:** `422 document_invalid`, with `document` or `receiptline` in `param`.
* **A document with no block, or one that prints nothing,** such as blocks of only blank lines (`feed`) or a `text` block of nothing (`""`): `422 document_empty`. A `text` block of spaces, or of a no-break space, is a text: it is accepted (`201`) and prints a line that looks blank. A `receiptline` of only white space, a no-break space included, is `422 document_empty`.
* **`document` that is not an array,** or `receiptline` that is not a string: `400 parameter_invalid`. This includes an object such as the earlier `{"type": "receiptline", "content": "..."}`. The message says where the text goes now.

Two things in a text are not exactly as typed. The document is normalized to NFC, so a letter and the combining mark after it become one letter with the accent. A combining mark at the start of a line has nothing to attach to, and is not printed.

## Warnings

The renderer follows the ReceiptLine library, which is lenient and silent. A column that does not fit is narrowed, and a character the printer cannot print becomes `?`, all without a word. Tillcast prints what the library would, and tells you where it fell back.

The job always has a `warnings` list, empty when the renderer had nothing to say. It is kept with the job, so a replay and every later read return the same list.

```json wordWrap
{"code": "column_shrunk", "line": 2, "column": 2, "message": "A column was made narrower to fit on the line."}
```

* `code` is stable and written in snake_case. Branch on it. A new code can be added, so treat one you do not know as a warning in general.
* `line` and `column` count from 1. `column` is `null` where the document was rewritten at that place. For a document of blocks they count the same receipt written in ReceiptLine, and not the blocks, so a warning does not name a block.
* `message` is a fixed sentence for a person. It holds no part of your document, so it is safe to show and to log. Do not parse it.
* A warning never changes what prints. A job has at most 21 warnings: the first 20, and `too_many_warnings` when there were more.

Most of the codes below cannot happen for blocks: a stray brace, an unknown property and an invalid escape are mistakes in ReceiptLine text that a block cannot make. The ones that can are about the paper and the printer: `column_shrunk`, `column_dropped_overflow` and `character_wider_than_column` (the widths of the columns against the width of the paper, which the blocks do not know), `character_unmappable`, and the ones about an image, a barcode and a QR code.

| Code                                 | When                                                                                                      |
| ------------------------------------ | --------------------------------------------------------------------------------------------------------- |
| `line_dropped_stray_brace`           | A `{` or `}` is not part of a property, and the whole line prints nothing. Escape braces in your own text |
| `property_member_invalid`            | A member of a property is not written as `key:value`, and is ignored                                      |
| `property_unknown_key`               | A property key the language does not know, and the property is ignored                                    |
| `property_in_multicolumn_line`       | A property sits in a line with several columns, and the whole line prints nothing                         |
| `option_value_unknown`               | An option value is not known, and the default is used                                                     |
| `escape_invalid`                     | An escape sequence is not valid, and is dropped                                                           |
| `control_character_removed`          | A control character was removed from the text                                                             |
| `column_dropped_overflow`            | A column does not fit on the line, and is dropped                                                         |
| `column_shrunk`                      | A column was made narrower to fit on the line                                                             |
| `character_wider_than_column`        | A character is wider than its column, and is not printed                                                  |
| `character_unmappable`               | A character is not in the printer's character set and prints as `?`. An emoji prints as two               |
| `base64_repaired`                    | The data of an image was repaired before it was decoded                                                   |
| `image_invalid`                      | The image is not a valid PNG, and is skipped                                                              |
| `image_too_large`                    | The image is over the limits, and is skipped                                                              |
| `image_wider_than_paper`             | The image is wider than the paper. It is never scaled and prints at its own size                          |
| `image_too_wide_for_printer`         | The image is wider than the printer can print, and is skipped                                             |
| `barcode_data_invalid`               | The barcode data is not valid for the barcode type                                                        |
| `barcode_control_characters_removed` | Control characters were removed from the barcode data                                                     |
| `qr_empty`                           | The QR code has no data and prints nothing                                                                |
| `qr_over_capacity`                   | The QR code data is more than a QR code can hold, and prints nothing                                      |
| `width_clamped`                      | A width above the limit was reduced to it                                                                 |
| `rule_state_closed_at_end`           | Ruled lines were still open at the end of the document, and were closed                                   |
| `too_many_warnings`                  | There are more warnings than are listed                                                                   |

## Limits and refusals

| What                                                                             | Limit                                                                                                                                                                                                                                                                                   | Above it                                     |
| -------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -------------------------------------------- |
| The text of `receiptline`, and the same receipt of blocks written in ReceiptLine | 256 KB of UTF-8 text, after the JSON is decoded                                                                                                                                                                                                                                         | `413 document_too_large`                     |
| The blocks                                                                       | 1,000 blocks in a document. In a table 1,000 rows, 16 columns of 1 to 96 characters and 20,000 cells in all. 32 pieces in a text. 4,096 characters in a text, a cell or a piece. 128 characters of barcode data, 2,048 of QR data and 200,000 of image data. 20 blank lines in a `feed` | `422 document_invalid`, with the path        |
| What the document renders to                                                     | 256 KB of printer data. 90 KB for the profile `epson-legacy-80mm-42`                                                                                                                                                                                                                    | `413 rendered_too_large`                     |
| An image                                                                         | At most 2,048 dots wide, 4,096 high and 4,000,000 pixels, and 4,000,000 pixels in all in one document. The header of the PNG is read before anything is unpacked                                                                                                                        | The image is skipped, with `image_too_large` |
| The request body                                                                 | 800 KB for creating a job                                                                                                                                                                                                                                                               | `413 request_too_large`                      |
| The work of rendering                                                            | A budget of steps, so that nesting or huge widths cannot make a document run long                                                                                                                                                                                                       | `422 render_timeout`                         |
| Jobs waiting for one printer                                                     | 50                                                                                                                                                                                                                                                                                      | `429 queue_full`                             |

A document that prints nothing is `422 document_empty`: no block, blocks of only blank lines or a text of nothing, or a `receiptline` of only white space. A `text` block of spaces or of a no-break space is not empty: it is accepted and prints a blank-looking line. See [Errors](/api/errors).

The `command` property of ReceiptLine, which would send raw printer commands, is not accepted from anyone, and a block cannot make one. A `receiptline` text that uses `{command:...}` is `422 document_command_not_allowed`, with the line and the column in the message. The same code refuses a text in which a hexadecimal escape would put a control character into the printed text.

## Advanced: ReceiptLine text

`receiptline` takes the document as text in [ReceiptLine](https://www.npmjs.com/package/receiptline), a second format that Tillcast supports next to blocks. It is the form for documents that were written for other ReceiptLine tools, such as the ReceiptLine demo and designer, and for software of yours that already writes the language. Everything a block can say, the text can say. The one thing the text has and a block has not is the `command` property of the language, which sends raw printer commands, and which Tillcast refuses. In text the characters of the language are yours to escape, and a mistake is a line that prints differently, with a warning at best. Blocks are the way to write a receipt.

Send the text in the field `receiptline` of the job, instead of `document`. In JSON a line break is `\n`. A plain line of ReceiptLine is centred, while a `text` block is on the left unless it says `center`.

```bash wordWrap
curl https://api.tillcast.com/v1/printers/prn_01M44X7TQ0A9R2H5J8K1M4N7P0/jobs \
  -H "Authorization: Bearer $TILLCAST_API_KEY" \
  -H "Tillcast-Version: 2026-10-01" \
  -H "Idempotency-Key: order-4712" \
  -H "Content-Type: application/json" \
  -d '{"receiptline": "Harbour Cafe\nTable 7\n{width:*,9}\nFlat white | 3.40\nLemon cake | 4.20\n-\nTotal | 7.60", "client_reference_id": "order-4712"}'
```

Written out as lines, the document is this.

```text
Harbour Cafe
Table 7
{width:*,9}
Flat white | 3.40
Lemon cake | 4.20
-
Total | 7.60
```

```text
          Harbour Cafe
             Table 7
Flat white                  3.40
Lemon cake                  4.20
--------------------------------
Total                       7.60
```

The first document of [A first document](#a-first-document) looks like this in ReceiptLine, with a property line for the columns of the table and the marks of the language for bold and size. For blocks you never write it.

```text
"^^^Harbour Cafe
Table 7
{width:*,9}
|Flat white | 3.40|
|Lemon cake | 4.20|
-
|"Total | "7.60|
```

### Lines, columns and alignment

* A line of plain text is centred.
* A **property line** such as `{width:*,9}` prints nothing. It applies to the lines after it. This one gives them two columns: the first takes what is left (`*`) and the second is 9 characters wide.
* A bar `|` separates columns. How a text sits in its column depends on the spaces beside the bars. A space between the text and the bar on its right pushes it to the left, a space on its left pushes it to the right, and a space on both sides centres it. So `item | price` puts the item on the left and the price on the right.

```text
{width:10,10,10}
left | centred | right
```

```text
left         centred       right
```

A cell that is too long wraps inside its column, by characters and not by words. `\n` starts a new line inside a cell.

```text
{width:*,8}
An item with a long name | 12.00
Short | 1.00
```

```text
An item with a long nam    12.00
e
Short                       1.00
```

### Bold, underline, inverse and size

These characters are marks. A mark switches a style on, and the same mark switches it off again. A mark applies to the column it stands in, and a style left on ends with the column.

| You write    | It prints                                                                                              |
| ------------ | ------------------------------------------------------------------------------------------------------ |
| `"text"`     | Bold                                                                                                   |
| `_text_`     | Underlined                                                                                             |
| `` `text` `` | Inverse: white on black                                                                                |
| `^text`      | Double width                                                                                           |
| `^^text`     | Double height                                                                                          |
| `^^^text`    | Double width and height. More carets make it larger still, up to 7, which is six times the normal size |

So `Pay "now" or _later_` has a bold word and an underlined word. In `^Total | 7.60` the label is in double width and the amount is not, because the mark stays in its own column.

### Rules and cuts

* A line made only of `-` is a rule across the paper, however many dashes it has.
* A line made only of `=` cuts the paper at that place. Tillcast cuts at the end of every document anyway, so use `=` only to split one document into several slips.

```text
Open daily
-----
See you soon
```

```text
           Open daily
--------------------------------
          See you soon
```

### Tables with borders

`{border:line}` draws the columns with lines. A `-` line inside the table draws a line between rows. Turn the border off with `{border:none}` (or `{border:space}`) on its own line when the table ends. Without it the renderer closes the table for you and reports `rule_state_closed_at_end`.

```text
{border:line; width:*,4,8}
Item | Qty | Price
-
Flat white | 1 | 3.40
Lemon cake | 2 | 8.40
{border:none}
```

```text
+----------------+----+--------+
|Item            | Qty|   Price|
+----------------+----+--------+
|Flat white      |  1 |    3.40|
|Lemon cake      |  2 |    8.40|
+----------------+----+--------+
```

Do not end the document with an empty line while a table is open: the empty line becomes an empty row.

### Barcodes and QR codes

A barcode or a QR code is a property line with the data in `code` and the type and size in `option`.

```text
{code:5901234123457;option:ean,hri}
{code:https://example.com/r/4711;option:qrcode,4,m}
```

* Barcode types are `upc`, `ean` (or `jan`), `code39`, `itf`, `codabar` (or `nw7`), `code93` and `code128`. For `upc` and `ean` the check digit can be left out.
* Add `hri` to print the digits under the barcode. Without it only the bars are printed. A number from 2 to 4 is the width of a bar in dots and a number from 24 to 240 is the height.
* `qrcode` makes a QR code. A number from 3 to 8 is the size of a cell in dots, and `l`, `m`, `q` or `h` is the error correction level.
* Inside the `code` value, write `\;` for a semicolon, and `\{`, `\}`, `\|` and `\\` for a brace, a bar and a backslash. Any other backslash sequence is dropped together with its character.
* Data that does not fit the type is `barcode_data_invalid`, and a QR code that cannot hold its data prints nothing, see [Warnings](#warnings). Control characters in barcode data are removed on purpose, because left in they would be commands to the printer.

### Images

`{image:...}` takes a PNG as base64. A monochrome PNG gives the best result. Tillcast sets limits and reports an image it skips with a warning:

* A PNG header is read before anything is unpacked. An image may be at most 2,048 dots wide, 4,096 high and 4,000,000 pixels, and all images in one document together at most 4,000,000 pixels.
* An image is never scaled. One wider than the paper prints at its own size (`image_wider_than_paper`), and one wider than a Star StarPRNT printer can take, 1,024 dots, is skipped (`image_too_wide_for_printer`).

### Your own text: escape it

This part is for `receiptline` text. In `document` the blocks do it for you, and there is nothing to escape.

Plain text is a document, but the characters of the language are special in it: `|`, `{`, `}`, `~`, `_`, `"`, `` ` ``, `^` and `\`, and a line made only of `-` or only of `=`. A name, an item or a note that you did not write can contain any of them, and then it changes the document. This document has a table number in braces and a code with underscores:

```text
Seat {VIP}
Code_A_7
```

```text
             CodeA7
```

The first line is gone, because a stray brace drops the whole line, and the answer lists `line_dropped_stray_brace`. The second lost its underscores, which switched underlining on and off, with no warning at all. Written with escapes, the same text prints as it is.

```text
Seat \{VIP\}
Code\_A\_7
```

```text
           Seat {VIP}
            Code_A_7
```

Escape every string that is not yours before it goes into a document. The rule:

| In your text                                           | Write                                  |
| ------------------------------------------------------ | -------------------------------------- |
| `\` `{` `}` `\|` `~` `_` `"` `` ` `` `^`               | A backslash before the character       |
| A space at the start or at the end                     | `~`. Spaces inside the text are text   |
| A line break                                           | `\n`, a line break inside the column   |
| A control character                                    | Remove it                              |
| A text of only `-`, or of only `=`                     | A backslash before the first character |
| Anything else: accents, other scripts, emoji, `;`, `:` | As it is                               |

These helpers do exactly this. They are for a text column: put the result beside the bars of a row, never inside the value of a property such as `code`. For an empty text they return an empty string, and an empty cell at the start or end of a row is no cell at all, because a bar with nothing beside it at the edge of a row is the language's optional edge bar. `row` writes `~` for an empty cell, so the row keeps its columns.

#### TypeScript

```ts
// True for a combining accent: a character that sorts differently once a mark is put in front of or behind it.
const first = (s: string): string => Array.from(s)[0] ?? "";
const isAccent = (c: string): boolean =>
  first(("\u0345" + c).normalize("NFD")) !== "\u0345" || first((c + "\u0334").normalize("NFD")) !== first(c.normalize("NFD"));

const SPECIAL = "\\{}|_\"`^~";

/** Make your own text safe to put in a column: it prints exactly as it is. */
export function escapeText(text: string): string {
  // Control characters are dropped. Line breaks stay for now.
  const chars = Array.from(text.replace(/[\x00-\x09\x0b\x0c\x0e-\x1f\x7f]/g, "").normalize("NFC"));
  const start = chars.findIndex((c) => c !== " ");
  let last = chars.length - 1;
  while (last >= 0 && chars[last] === " ") last--;
  let out = "";
  let afterBreak = false;
  for (let i = 0; i < chars.length; i++) {
    const c = chars[i] as string;
    if (c === "\r" && chars[i + 1] === "\n") continue; // the \n that follows is the break
    if (c === "\n" || c === "\r" || c === "\u2028" || c === "\u2029") {
      out += "\\n";
      afterBreak = true;
      continue;
    }
    if (afterBreak && isAccent(c)) continue; // an accent after a break has nothing to sit on
    afterBreak = false;
    if (SPECIAL.includes(c)) out += "\\" + c;
    else if (c === " " && (i < start || i > last)) out += "~";
    else out += c;
  }
  // A cell made only of - or only of = would be a rule or a cut.
  return /^-+$|^=+$/.test(out) ? "\\" + out : out;
}

/** One table row: every cell escaped, an empty cell written as ~. */
export const row = (...cells: string[]): string => cells.map((cell) => escapeText(cell) || "~").join(" | ");
```

#### Python

```python
import unicodedata

SPECIAL = '\\{}|_"`^~'


def escape_text(text: str) -> str:
    """Make your own text safe to put in a column: it prints exactly as it is."""
    # Control characters are dropped. Line breaks stay for now.
    kept = "".join(c for c in text if c in "\n\r" or not (c < " " or c == "\x7f"))
    chars = list(unicodedata.normalize("NFC", kept))
    start = next((i for i, c in enumerate(chars) if c != " "), len(chars))
    last = len(chars) - 1
    while last >= 0 and chars[last] == " ":
        last -= 1
    out = []
    after_break = False
    i = 0
    while i < len(chars):
        c = chars[i]
        if c == "\r" and i + 1 < len(chars) and chars[i + 1] == "\n":
            i += 1
            continue  # the \n that follows is the break
        if c in "\n\r\u2028\u2029":
            out.append("\\n")
            after_break = True
            i += 1
            continue
        if after_break and unicodedata.combining(c):
            i += 1
            continue  # an accent after a break has nothing to sit on
        after_break = False
        if c in SPECIAL:
            out.append("\\" + c)
        elif c == " " and (i < start or i > last):
            out.append("~")
        else:
            out.append(c)
        i += 1
    text_out = "".join(out)
    # A cell made only of - or only of = would be a rule or a cut.
    if text_out and (set(text_out) == {"-"} or set(text_out) == {"="}):
        text_out = "\\" + text_out
    return text_out


def row(*cells: str) -> str:
    """One table row: every cell escaped, an empty cell written as ~."""
    return " | ".join(escape_text(cell) or "~" for cell in cells)
```

A table of items is then built like this, and `JSON.stringify` or your JSON library writes the quotes, backslashes and line breaks of the string for you.

```ts
const lines = ["^Harbour Cafe", "{width:*,9}", ...items.map((item) => row(item.name, item.price))];
const body = { receiptline: lines.join("\n") };
```

## Show a receipt in your own page

To see a document without a printer, draw it in a web page. The npm package `@tillcast/preview` takes the same blocks and draws the receipt in the browser, with no call to Tillcast and no key. See [Preview a receipt in your app](/preview-a-receipt).

## What is not available yet

* **Templates.** A template language and stored templates (ready-made documents with places for your data) are in development and not available. A job has no `template` or `data` field: a request that sends one is refused with `400 parameter_unknown`. Blocks are plain objects, so build the document in your code, with a loop over your own data.
* **Other kinds of document.** HTML, Markdown and converted plain text are not built.
* **A cash drawer option and an image converter.** A PNG goes inside the document as base64.
* **Printer commands inside a document.** Not offered to anyone.