ReceiptPrinterEncoder

repository·main·Indexed 43 days ago

https://github.com/nielsleenheer/receiptprinterencoder

A utility for generating encoded command sets for thermal receipt printers supporting ESC/POS, StarLine, and StarPRNT protocols. Version 4.0.0 allows developers to define text, images, and barcodes, encoding them into a Uint8Array for transmission to hardware via separate @point-of-sale libraries.

Tokens
16.4K
Snippets
58
Records
71
Agent score
55%

What's inside ReceiptPrinterEncoder

  1. Overview of ReceiptPrinterEncoder

    main

    ReceiptPrinterEncoder (formerly known as EscPosEncoder, StarPrntEncoder, and ThermalPrinterEncoder) is a library used to generate command sets for receipt printers. It allows you to define content such as text, images, and barcodes, and then encodes that content into commands compatible with printers supporting ESC/POS, StarLine, or StarPRNT protocols.

    Note that this library only handles the encoding of commands. To actually print the receipt, you must use a separate library (part of the @point-of-sale collection) to send the resulting encoded data to the physical printer hardware.

  2. Create cells that span multiple columns

    main

    To make a cell cover more than one column, use an object instead of a string or callback for the cell value. This is useful for headers or totals.

    Properties for Spanned Cells:

    • content: The actual content (string or callback).
    • span: The number of columns to cover (default is 1).
    • align: Overrides the column's horizontal alignment.
    • border: Can turn off the table's borders for this specific cell (none or specific sides like { left: 'none' }).
    • marginLeft / marginRight: Overrides the column's margins.

    Constraint: The sum of all span values in a row must exactly equal the total number of columns defined in the table configuration.

    // Example of a cell spanning 2 columns in a 3-column table
    [
        [ 'Beer', '2', '13.00' ],
        [ { span: 2, content: 'Total', align: 'right' }, '185.80' ]
    ]
  3. How code pages and printer support work

    main

    Receipt printers do not support Unicode or UTF-8. Instead, they rely on legacy code pages to represent different character sets.

    To print text correctly, you must ensure the printer supports the specific code page you intend to use. Support varies significantly by manufacturer and model. Always consult your printer's technical manual before selecting a code page. If a printer lacks hardware support for a specific character set, the library cannot force it to print correctly.

  4. Create lists using Markdown syntax

    main

    Lists in markdown() are treated as tables with a marker column and a fill column. This ensures that wrapped lines of an item hang under the text rather than under the marker.

    List Types

    • Unordered Lists: Use -, *, or +. The marker printed is always -.
    • Ordered Lists: Use 1. item or 1) item. The list counts from the number of its first item.
    • Nesting: Indent items by two or more spaces per level to create nested lists. Nested lists maintain their own numbering.

    Layout

    • The marker column width is determined by the widest marker in the list plus one space.
    • If the marker column is too narrow to allow text, items are printed as simple lines of text with the marker and a space.
    - Meals and goods at the reduced tax rate
      - Coffee and tea
    - Paid in cash
    1. Keep this receipt
    2. Visit [our site](https://example.com)
  5. Understand the ReceiptPrinterEncoder lifecycle

    main

    The ReceiptPrinterEncoder works by queuing commands and then encoding them into a Uint8Array of bytes ready for the printer.

    Typical Workflow

    1. Initialize: Call .initialize() to reset the printer and encoder to a clean state. This is required for every new receipt to ensure settings like code pages or styles don't leak from previous prints.
    2. Queue Commands: Use methods like .text(), .line(), .align(), etc., to build your receipt. Commands can be chained.
    3. Encode: Call .encode() to retrieve the Uint8Array containing the bytes.

    Chunked Encoding

    You can call .encode() multiple times to send a receipt in parts. Each call drains the buffer and returns the bytes for the commands queued so far. The encoder maintains its state (e.g., current code page or text style) between calls, so the next chunk continues where the previous one left off. However, these chunks must be sent to the same printer in the correct order.

    Resetting for a New Receipt

    To start a completely new receipt, call .initialize() again. This clears all previous styles, alignments, and code pages.

    let encoder = new ReceiptPrinterEncoder();
    
    let receipt = encoder
        .initialize()
        .text('The quick brown fox jumps over the lazy dog')
        .encode();
  6. Create tables using Markdown pipe syntax

    main

    You can create tables in markdown() using pipe syntax. The delimiter line (the second line) determines the alignment of each column:

    • :-- : Left aligned
    • :-: : Center aligned
    • --: : Right aligned

    Table Rules

    • Header: The first row is automatically printed in bold.
    • Empty Headers: If a header row contains only empty cells, it will not be printed, allowing you to create tables without headers.
    • Width & Wrapping: Columns are one space apart. The width is determined by the longest cell. If a table is too wide for the paper, the widest column loses characters one by one until it fits, causing text to wrap. If the space is extremely narrow, columns are printed as simple lines of text with cells separated by a single space.
    • Borders: This implementation does not print table borders.
    | Item    | Qty | Price |
    |:--------|----:|------:|
    | Beer    |   2 | 13.00 |
    | Chidori |   2 | 172.80 |
  7. Understand the core responsibility of ReceiptPrinterEncoder

    main
    It is important to understand that ReceiptPrinterEncoder is strictly an encoding library. It does not contain any methods to send data to a physical printer. Its sole purpose is to generate the set of commands (ESC/POS, StarLine, or StarPRNT) required by receipt printers. To actually print, you must use a separate library or driver to transmit the encoded data to your hardware.
  8. Setup ReceiptPrinterEncoder for React Native and Expo

    main

    The library requires structuredClone(), which is missing in React Native and the Hermes engine. To prevent the error Property 'structuredClone' doesn't exist, you must install and polyfill it in your application's entry point before importing the encoder.

    1. Install the polyfill:
    npm install @ungap/structured-clone
    1. Apply the polyfill globally:
    import structuredClone from '@ungap/structured-clone';
    
    if (typeof globalThis.structuredClone !== 'function') {
        globalThis.structuredClone = structuredClone;
    }

    Note on Images: The image() function requires a way to read pixels. Ensure you provide the appropriate input types or use the createCanvas option as described in the image command documentation.

  9. Configure ReceiptPrinterEncoder using a printer model

    main

    The easiest way to configure the library is by specifying a printerModel. This automatically sets important options like language, supported code pages, and imageMode.

    If your specific model is not listed, you can try a similar model or use generic models like pos-5890 or pos-8360 for many unbranded printers. For cheap Bluetooth 'cat' or 'meow' printers that only support image printing, use the meow model.

    You can view all supported models via the ReceiptPrinterEncoder.printerModels static property.

    let encoder = new ReceiptPrinterEncoder({
        printerModel: 'epson-tm-t88vi'
    });
  10. Print receipts from Node.js

    main

    When working in a Node.js environment, use one of the following sister libraries to transmit the encoded data to your printer:

    • NetworkReceiptPrinter: Use this to print directly to a printer over a network (e.g., via TCP/IP).
    • SystemReceiptPrinter: Use this to print to a printer that is already installed and managed by your operating system.
  11. Install and use ReceiptPrinterEncoder with Node.js

    main

    First, install the package via npm:

    npm install @point-of-sale/receipt-printer-encoder --save

    Then, you can use it with either ES6 modules or CommonJS:

    ES6 Modules:

    import ReceiptPrinterEncoder from '@point-of-sale/receipt-printer-encoder';
    const encoder = new ReceiptPrinterEncoder();

    CommonJS:

    const ReceiptPrinterEncoder = require('@point-of-sale/receipt-printer-encoder');
    const encoder = new ReceiptPrinterEncoder();