๐ฟ papermint
A fast, multi-vendor, type-safe thermal receipt printing library for Rust.
Design Principles
papermint is engineered around four core architectural pillars:
- Decoupled Layout Architecture: Formatting produces an intermediate command representation, keeping receipt structure completely independent of vendor wire bytes.
- Rich Error Semantics: Matchable, typed error variants providing actionable hardware and network diagnostics.
- Resilient Async Networking: Built-in connection timeouts, socket reconnect resilience, and non-blocking I/O.
- Unicode-Aware Layout: Precise column balancing that properly calculates multi-byte UTF-8 character widths.
Built on a clean three-layer architecture:
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Layer 3: Layout Engine (Receipt Builder) โ
โ - Fluent API, multi-column tables, dividers, barcodes โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ produces Vec<Command> (Command IR)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Layer 2: Dialect Encoders โ
โ - ESC/POS (Epson, Bixolon, Citizen, Xprinter, Rongta) โ
โ - StarPRNT (Star Micronics TSP100, TSP650, mC-Print) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ emits wire bytes (Vec<u8>)
โโโโโโโโโโโโโโโโโโโโโโโโโโโโผโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Layer 1: Transports โ
โ - Async TCP (RAW network POS printers on Port 9100) โ
โ - Driverless USB (`nusb` OS-independent Class 7) โ
โ - Serial / RS-232 & Bluetooth SPP (`tokio-serial`) โ
โ - VecSink (In-memory testing, mock execution) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The central innovation is the Command Intermediate Representation (IR): you build receipts once, test them in-memory, replay them, store them as commands, or encode them for any vendor.
Features
- โก Zero-cost, low-allocation encoding: Encodes directly into reusable buffers.
- ๐ Unicode-aware layout engine: Precise 80mm (48 cols) and 58mm (32 cols) column balancing.
- ๐จ๏ธ Multi-Vendor Dialect Support:
- Epson ESC/POS: Full support for TM-T88, TM-m30, TM-T20, Bixolon, Citizen, and compatibles.
- StarPRNT / Line Mode: Native support for TSP100, TSP650II, TSP700, and mC-Print series.
- Text Styling: Bold, Underline, Inverse, Font A/B, Double Width/Height.
- Advanced Formatting: Upside-down 180ยฐ rotation (for kitchen order clips), custom line spacing, and code table selection.
- Barcodes (1D): Code128 (with auto-subset
{B), EAN13, EAN8, UPC-A, UPC-E, ITF, Codabar, Code39, Code93. - 2D QR Codes: Hardware-accelerated Model 2 generation with configurable cell size and error correction.
- Graphics: 1-bit monochrome raster bitmap printing.
- Hardware I/O: Full & partial paper cutting, RJ12 Pin 2 / Pin 5 cash drawer kicks, and audio buzzer alerts.
- ๐ Resilient Async TCP Transport: Configurable connect and write timeouts with automatic reconnection on stream errors.
- ๐งช First-Class Testing: Built-in
VecSinkfor zero-hardware unit and integration testing. - ๐ก๏ธ Safe & reliable: 100% safe Rust, structured error types, and clean lifetimes.
Quickstart
Add papermint to your Cargo.toml:
[]
= "0.2"
= { = "1", = ["full"] }
1. Print a receipt over TCP network
use SocketAddr;
use ;
async
2. Testing without physical printers (VecSink)
use ;
async
Feature Flags
| Feature | Default | Description |
|---|---|---|
std |
Yes | Standard library support and std::io::Error wrapping |
escpos |
Yes | Epson ESC/POS dialect encoder |
star |
Yes | StarPRNT / Star Line Mode dialect encoder |
label |
Yes | 2D label printing engine (TSPL & ZPL II) via papermint-label |
async |
Yes | Asynchronous traits and Printer orchestrator |
tcp |
Yes | Tokio async TCP transport (TcpTransport) |
serial |
No | Asynchronous serial RS-232 / COM port transport (SerialTransport) |
usb |
No | Pure-Rust async USB Printer Class 07 transport (UsbTransport) |
image |
No | PNG/JPEG decoding, aspect-ratio auto-scaling, and Floyd-Steinberg dithering |
3. Multi-Column Tables with Word-Wrapping
Print tabular receipts where long item names automatically wrap at word boundaries without breaking columnar alignment:
use ;
let columns = ;
let receipt = new
.init
.table_header
.divider
.row
.row
.divider
.two_column
.cut_full;
4. Image Printing & Floyd-Steinberg Dithering
Enable the image feature to print logos, graphics, and coupons directly from PNG or JPEG files:
[]
= { = "0.2", = ["image"] }
use ;
let receipt = new
.init
.center
// Auto-scales to fit paper width and applies Floyd-Steinberg error diffusion:
.image_from_path?
// Or load from in-memory bytes with custom threshold cutoff for crisp vector art:
.image_from_bytes_with_options?
.feed
.cut_full;
5. Real-Time Hardware Status & Sensor Telemetry
Query printer readiness, paper low warnings, cover open, cutter jams, and cash drawer state in real time:
use ;
// Query real-time telemetry (ESC/POS or StarPRNT)
let status = printer.query_status.await?;
if !status.is_ready
if status.paper == NearEnd
if status.drawer == Open
6. International Character Sets & Extended Code Pages
Thermal receipt printers are 8-bit devices that cannot natively parse multi-byte UTF-8 without garbled output. papermint provides automatic single-byte transcoding and standard ESC R n national character set switching:
use ;
let receipt = new
.init
// Select national currency/symbol set (e.g. UK replaces '#' with 'ยฃ'):
.charset_uk
// Select 8-bit extended code table (e.g. Windows-1252 for Western Europe):
.code_page
.text_ln
// Euro (โฌ) is automatically transcoded to 0x80 (no UTF-8 mojibake!):
.two_column
.feed
.cut_full;
7. Thermal Printhead Energy & Density Calibration
Calibrate printhead strobe pulses and burn darkness to match specific thermal paper sensitivities or cold/hot operating environments:
use ;
let receipt = new
.init
// Increase density for high optical contrast on 2D barcodes or low-sensitivity paper:
.density_dark // or .density_light(), .density_normal(), .density_high_contrast()
// Configure low-level thermal strobe timings: max dots, heat time (x10ยตs), interval (x10ยตs)
.heating_parameters
.text_ln
.feed
.cut_full;
8. Direct USB & Serial Hardware Transports
Communicate with physical thermal receipt printers connected via USB or Serial RS-232 / Virtual COM ports:
Serial / RS-232 Counter POS
use ;
async
USB Printer Class (Class 07)
use ;
async
Hardware Device Discovery & Port Enumeration
use ;
// Discover available serial COM ports (e.g. /dev/ttyUSB0, COM3):
let serial_ports = available_ports?;
for port in serial_ports
// Discover attached USB printers (Vendor ID, Product ID, Serial, Manufacturer):
let usb_printers = list_printers?;
for printer in usb_printers
9. Node.js & TypeScript Bindings (papermint)
High-performance native N-API bindings allow your TypeScript POS and backend services to format receipts and stream to hardware with zero runtime serialization lag:
import { Receipt, Printer } from 'papermint';
const receipt = new Receipt('80mm')
.init()
.center()
.bold(true)
.textLn('MINT BISTRO')
.bold(false)
.divider('=')
.tableHeader(
['QTY', 'DESCRIPTION', 'PRICE', 'TOTAL'],
[
{ widthFixed: 4, align: 'left' },
{ widthFraction: 0.50, align: 'left' },
{ widthFraction: 0.22, align: 'right' },
{ widthFraction: 0.24, align: 'right' },
]
)
.row(['2x', 'Truffle Wagyu Burger with Caramelized Onions', '$14.50', '$29.00'])
.row(['1x', 'Wood-Fired Margherita Pizza', '$18.00', '$18.00'])
.divider('-')
.twoColumn('TOTAL DUE:', '$47.00')
.qr('https://pay.mintbistro.com/bill/1042')
.cutFull();
// Print over TCP network to thermal printer:
const printer = Printer.tcp('192.168.1.100:9100', 'escpos');
await printer.print(receipt);
// Or encode directly to a Node Buffer:
const rawBuffer = receipt.encode('escpos');
10. Mobile & Expo Module (expo-papermint)
High-performance native receipt compilation engine for Expo SDK 56+ and React Native (iOS & Android). Formats complex CJK/Arabic Unicode tables, ZATCA tax QR codes, and Floyd-Steinberg dithered raster graphics in microseconds, returning zero-copy raw byte buffers (Uint8Array) ready to stream to portable Bluetooth or Wi-Fi printers:
# In Expo projects:
# In Bare React Native projects:
import { Receipt } from 'expo-papermint';
// Build and compile ticket in ~10 microseconds
const wireBytes: Uint8Array = Receipt.create('80mm')
.title('MINT BISTRO')
.subtitle('Order #1042')
.divider('=')
.item('Truffle Smash Burger', '$14.50', 2, '$29.00')
.item('Wood-Fired Margherita Pizza', '$18.00', 1)
.divider('-')
.total('TOTAL DUE:', '$47.00')
.qr('https://pay.mintbistro.com/bill/1042')
.cut()
.compile('escpos'); // or 'star'
// Stream wireBytes directly over Bluetooth Classic (RFCOMM) or BLE!
11. Native Print Daemon (papermintd)
papermintd is a standalone, high-concurrency HTTP sidecar service powered by Axum and Tokio for local POS ticket streaming:
Send print jobs via simple HTTP POST:
Cloud WebSocket Gateway Mode:
papermintd also features an outbound persistent WebSocket client that connects out through retail store NAT routers to your cloud API with automatic exponential backoff:
12. 2D Adhesive Label Printing (papermint-label)
High-speed 2D coordinate canvas label printing for barcode stickers, coffee cup tags, shipping labels, and shelf tags supporting TSPL / TSPL-II (TSC, Xprinter, Rongta, Munbyn) and ZPL II (Zebra, Citizen, Godex):
use ;
let label = new // 50mm x 30mm sticker
.gap
.direction
.text
.barcode
.qr
.box_outline
.copies;
// Compile to vendor wire bytes:
let tspl_bytes = label.encode_tspl; // Xprinter / TSC
let zpl_bytes = label.encode_zpl; // Zebra ZD420 / ZT411
// Or render an instant SVG vector preview with die-cut rounded corners:
let svg_preview = label.render_svg;
Documentation & Guides
- Architecture & Multi-Crate Workspace โ 3-layer architecture, atomic state tracking, and Unicode column mathematics.
- Mobile POS & React Native Guide โ Expo SDK 56+ Inline Modules, C-ABI FFI, and Bluetooth Classic/BLE streaming.
- Print Daemon HTTP REST API & Cloud Gateway โ
papermintdendpoints, JSON ticket schemas, and WebSocket gateway. - Hardware & Protocol Specification โ Wire byte sequences, electrical drawer pulses, and QR symbology.
- Supported Hardware & Connection Guide โ Tested printer models, driverless USB (
udevrules), RS-232, and cash drawer pins.