Giter Club home page Giter Club logo

receiptline's Introduction

ReceiptLine

Markdown for receipts. Printable digital receipts. 🧾
Generate receipt printer commands and images.

Package Type For Description
ReceiptLine SDK for Node.js Developers Receipt description language processor
ReceiptIO Node.js Console App Users Print, Convert, Printer status
Designer Tool All Edit, Preview
Receipt Markdown VS Code Extension All Edit, Preview
Receipt.js SDK for JavaScript Developers Receipt description language processor
Print, Convert, Printer status
Receipt.js Designer Tool All Edit, Preview, Print

"ReceiptLine" is a coined word from "Receipt" and "Streamline".
Make it more efficient by making it simpler!

English
Japanese
German

Features

The reference implementation of the OFSC ReceiptLine Specification.
http://www.ofsc.or.jp/receiptline/en/

ReceiptLine is the receipt description language that expresses the output image of small roll paper.
It supports printing paper receipts using a receipt printer and displaying electronic receipts on a POS system or smartphone.
It can be described simply with receipt markdown text data that does not depend on the paper width.

This reference implementation also provides the development tool "ReceiptLine Designer" for editing, previewing, hex dumps with a virtual printer, and test printing on receipt printers.

Receipt Printers

  • Epson TM series
  • Seiko Instruments RP series
  • Star MC series
  • Citizen CT series
  • Fujitsu FP series

Epson TM series (South Asia model) and Star MC series (StarPRNT model) can print with device font of Thai characters.

Printers

Installation

$ npm install receiptline

Usage

receiptline.transform() method transforms ReceiptLine document to printer commands or SVG images.

const receiptline = require('receiptline');

const doc = '{code:2012345678903;option:ean,hri}';

// printer example
const printer = {
    cpl: 42,
    encoding: 'multilingual',
    upsideDown: false,
    gamma: 1.8,
    command: 'escpos'
};
const command = receiptline.transform(doc, printer);

// display example
const display = {
    cpl: 42,
    encoding: 'multilingual'
};
const svg = receiptline.transform(doc, display);

Method

receiptline.transform(doc[, printer])

Parameters

  • doc
    • a string of ReceiptLine document
  • printer
    • an object of printer configuration

Return value

  • printer commands or SVG images

Printer configuration

  • cpl
    • characters per line (default: 48)
  • encoding
    • multilingual: Multilingual (including cp437, cp852, cp858, cp866, cp1252)
    • cp437: United States (default)
    • cp852: Central European
    • cp858: Western European
    • cp860: Portuguese
    • cp863: French Canadian
    • cp865: Nordic
    • cp866: Cyrillic
    • cp1252: Western European
    • cp932: Japanese
    • shiftjis: Japanese
    • cp936: Simplified Chinese
    • gb18030: Simplified Chinese
    • cp949: Korean
    • ksc5601: Korean
    • cp950: Traditional Chinese
    • big5: Traditional Chinese
    • tis620: Thai
  • gradient (for printer)
    • false: image processing for text, barcodes, and 2D codes
    • true: image processing for photos (default)
  • gamma (for printer)
    • image gamma correction (range: 0.1 - 10.0, default: 1.8)
  • threshold (for printer)
    • image thresholding (range: 0 - 255, default: 128)
  • upsideDown (for printer)
    • false: normal (default)
    • true: upside down
  • spacing
    • false: no line spacing (default)
    • true: line spacing
  • cutting (for printer)
    • false: no paper cutting
    • true: paper cutting (default)
  • margin (for printer)
    • print margin (left) (range: 0 - 24, default: 0)
  • marginRight (for printer)
    • print margin (right) (range: 0 - 24, default: 0)
  • command
    • svg: SVG (default)
    • text: plain text
    • escpos: ESC/POS
    • epson: ESC/POS (Epson)
    • sii: ESC/POS (Seiko Instruments)
    • citizen: ESC/POS (Citizen)
    • fit: ESC/POS (Fujitsu)
    • impact: ESC/POS (TM-U220)
    • impactb: ESC/POS (TM-U220 Font B)
    • generic: ESC/POS (Generic) Experimental
    • starsbcs: StarPRNT (SBCS, Thai)
    • starmbcs: StarPRNT (Japanese)
    • starmbcs2: StarPRNT (Chinese, Korean)
    • starlinesbcs: Star Line Mode (SBCS)
    • starlinembcs: Star Line Mode (Japanese)
    • starlinembcs2: Star Line Mode (Chinsese, Korean)
    • emustarlinesbcs: Command Emulator Star Line Mode (SBCS)
    • emustarlinembcs: Command Emulator Star Line Mode (Japanese)
    • emustarlinembcs2: Command Emulator Star Line Mode (Chinsese, Korean)
    • stargraphic: Star Graphic Mode (TSP100LAN)
    • starimpact: Star Mode on dot impact printers Experimental
    • starimpact2: Star Mode on dot impact printers (Font 5x9 2P-1) Experimental
    • starimpact3: Star Mode on dot impact printers (Font 5x9 3P-1) Experimental

Transform stream API

receiptline.createTransform() method is the stream version of the receiptline.transform().

const fs = require('fs');
const receiptline = require('receiptline');

const source = fs.createReadStream('example.receipt');
const transform = receiptline.createTransform({ command: 'svg' });
const destination = fs.createWriteStream('example.svg');

source.pipe(transform).pipe(destination);

Method

receiptline.createTransform([printer])

Parameters

  • printer
    • an object of printer configuration

Return value

  • Transform stream <stream.Transform>

Examples

example/receipt/*

Display digital receipts in the web browser and print paper receipts on the printer as needed.

example/cloud/*

Print order slips from cloud server using Epson Server Direct Print or Star CloudPRNT.

example/nodejs/*

Enter receipt markdown text from the web form, transform it to printer commands on the server, and print it out.

example/js/*

Enter receipt markdown text from the web form, transform it to SVG images on the web browser, and display it.

example/data/*

The documents (receipt markdown text) are the same as the examples in the OFSC ReceiptLine Specification.

example/command/*

Customize the command object to output your own commands.

Libraries

lib/receiptline.js

JavaScript ES2015(ES6) version. It works on both web browser and Node.js.
To output printer commands on a web browser, use Receipt.js or Browserify.

$ browserify -o receiptline-full.js receiptline.js

lib/qrcode-generator/qrcode.js

Generate the QR Code for display. Optional.

ReceiptLine Designer

Online version is available.
https://receiptline.github.io/designer/

The ReceiptLine Designer provides more features.

  • Edit and preview
  • Data transmission via TCP socket
  • Hex dump view by listening TCP 19100 port

Designer

Setup

  1. Copy the following files to your working directory

    • designer/*
    • designer.js
    • printers.json
    • servers.json
  2. Start the server

    $ node designer.js
  3. Open http://localhost:8080

    Use a modern browser.

  4. Configure printers.json

    "printer_id": {
        "host": "127.0.0.1",
        "port": 19100,
        "asImage": false,
        "cpl": 48,
        "encoding": "shiftjis",
        "gradient": true,
        "gamma": 1.8,
        "threshold": 128,
        "upsideDown": false,
        "spacing": true,
        "cutting": true,
        "command": "escpos"
    }
    • printer_id
      • printer identifier (alphanumeric or underscore characters)
    • host
      • printer address
    • port
      • printer port (will be 9100)
    • asImage
      • false: print with device font (default)
      • true: print as image (Requires puppeteer or sharp)
    • landscape
      • false: normal (default)
      • true: landscape orientation (for escpos, epson, sii, citizen, starsbcs, starmbcs, starmbcs2)
    • resolution
      • print resolution for landscape (values: 180, 203, default: 203)
    • cpl
    • encoding
    • gradient
    • gamma
    • threshold
    • upsideDown
    • spacing
    • cutting
    • margin
    • marginRight
      • see the printer configuration above
    • command
      • see the printer configuration above
      • png: PNG (Requires puppeteer or sharp)

URL query string

The designer can set initial values in the URL query string.

Parameters

  • z: zoom (range: -5-5, default: 0)
  • l: language (en, ja, ko, zh-hans, zh-hant, th, ...)
  • c: characters per line (range: 24-96, default: 48)
  • v: landscape (values: 0, 1, default: 0)
  • s: line spacing (values: 0, 1, default: 0)
  • p: printer identifier (alphanumeric or underscore characters)
  • d: ReceiptLine document

Examples

Serial-LAN Converter

The serial-LAN converter enables test printing to USB / Bluetooth printers that support virtual serial ports.

Setup

  1. Install the virtual serial port driver for the printer and Node Serialport

    $ npm install serialport
  2. Configure servers.json

    "serial": {
        "host": "127.0.0.1",
        "port": 9100,
        "device": "COM9"
    }
    • serial
      • to enable it, change from _serial
    • host
      • local address
    • port
      • local port
    • device
      • the system path of the serial port
      • <system path>[:<options>]

    Serial port options

        "device": "COM9:9600,N,8,1"
    • <options>
      • <baud rate>,<parity>,<data bits>,<stop bits>[,<flow control>]
      • default: 9600,N,8,1,N
      • commas can be omitted
    • <baud rate>
      • 2400, 4800, 9600, 19200, 38400, 57600, 115200
    • <parity>
      • N: none, E: even, O: odd
    • <data bits>
      • 8, 7
    • <stop bits>
      • 1, 2
    • <flow control>
      • N: none, R: rts/cts, X: xon/xoff
  3. Restart the server

    $ node designer.js

Syntax

Railroad diagram

document
document

line
line

columns
columns

column
column

text
text

char
char

escape
escape

ws (whitespace)
ws

property
property

member
member

key
key

value
value

Grammar

Structure

The receipt is made of a table, which separates each column with a pipe |.

Line Content Description
column
| column |
| column
column |
Text
Property
Single column
column | column
| column | column |
| column | column
column | column |
Text Double column
column | ... | column
| column | ... | column |
| column | ... | column
column | ... | column |
Text Multiple columns

Alignment

The column is attracted to the pipe | like a magnet.
means one or more whitespaces.

Column Description
column
|column|
|␣column␣|
Center
|column
|column␣|
column␣|
Left
column|
|␣column|
|␣column
Right

Text

The text is valid for any column.

Asparagus | 0.99
Broccoli | 1.99
Carrot | 2.99
---
^TOTAL | ^5.97

Characters are printed in a monospace font (12 x 24 px).
Wide characters are twice as wide as Latin characters (24 x 24 px).
Control characters are ignored.

Special characters in text

Special characters are assigned to characters that are rarely used in the receipt.

Special character Description
\ Character escape
| Column delimiter
{ Property delimiter (Start)
} Property delimiter (End)
- (1 or more, exclusive) Horizontal rule
= (1 or more, exclusive) Paper cut
~ Space
_ Underline
" Emphasis
` Invert
^ Double width
^^ Double height
^^^ 2x size
^^^^ 3x size
^^^^^ 4x size
^^^^^^ 5x size
^^^^^^^ (7 or more) 6x size

Escape sequences in text

Escape special characters.

Escape sequence Description
\\ \
\| |
\{ {
\} }
\- - (Cancel horizontal rule)
\= = (Cancel paper cut)
\~ ~
\_ _
\" _
\` `
\^ ^
\n Wrap text manually
\xnn Hexadecimal character code
\char (Others) Ignore

Properties

The property is valid for lines with a single column.

{ width: * 10; comment: the column width is specified in characters }
Key Abbreviation Value Case-sensitive Default Saved Description
image i base64 png format - - Image
(Recommended: monochrome, critical chunks only)
code c textdata - - Barcode / 2D code
option o see below - code128 2 72 nohri 3 l Barcode / 2D code options
(Options are separated by commas or one or more whitespaces)
align a left
center
right
- center Line alignment
(Valid when line width < CPL)
width w auto
*
0 -
- auto
(* for all columns)
Column widths (chars)
(Widths are separated by commas or one or more whitespaces)
border b line
space
none
0 - 2
- space Column border (chars)
(Border width: line=1, space=1, none=0)
text t wrap
nowrap
- wrap Text wrapping
command x textdata - - Device-specific commands
comment _ textdata - - Comment

Barcode options

Barcode options are separated by commas or one or more whitespaces.

Barcode option Description
upc UPC-A, UPC-E
(Check digit can be omitted)
ean
jan
EAN-13, EAN-8
(Check digit can be omitted)
code39 CODE39
itf Interleaved 2 of 5
codabar
nw7
Codabar (NW-7)
code93 CODE93
code128 CODE128
2 - 4 Barcode module width (px)
24 - 240 Barcode module height (px)
hri With human readable interpretation
nohri Without human readable interpretation

2D code options

2D code options are separated by commas or one or more whitespaces.

2D code option Description
qrcode QR Code
3 - 8 Cell size (px)
l
m
q
h
Error correction level

Special characters in property values

Special characters in property values are different from special characters in text.

Special character Description
\ Character escape
| Column delimiter
{ Property delimiter (Start)
} Property delimiter (End)
: Key-value separator
; Key-value delimiter

Escape sequences in property values

Escape special characters.

Escape sequence Description
\\ \
\| |
\{ {
\} }
\; ;
\n New line
\xnn Hexadecimal character code
\char (Others) Ignore

Restrictions

  • Communication with the printer, status event processing, and error handling are out of scope.
  • SVG images depend on the font family installed on the computer and may not display properly.
  • Impact printer has some limitations for printing.
    • Characters larger than 2x size
    • Inverted characters (will be printed in red)
    • Double height characters in different colors on the same line
    • Multibyte characters
    • Image position and size ratio
    • Barcodes and 2D codes
  • Star Graphic Mode printing only supports images, line feeds, and paper cuts.
  • sharp is not support web fonts and minimizes the area of "invert" character decoration.

Author

Open Foodservice System Consortium
http://www.ofsc.or.jp/

License

  • ReceiptLine
    • Apache License, Version 2.0
  • QR Code Generator for JavaScript with UTF8 Support
    • MIT License

receiptline's People

Contributors

receiptline avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

receiptline's Issues

Template Fields Question

Greetings and thank you very much for the amazing Receiptline!

We are building an F&B POS and hope to incorporate ReceiptLine. I have a general question. We wish to provide receipt templates for customization. This requires that, at runtime, we merge data fields into the ReceiptLine markdown. Visually:

image

We can do this now with the:

{ OURFIELDID }

Is that the intended use? Do you have any other suggestions for this general process?

Open cash drawer on TSP143III

Good morning, I love your package however I can't seem to get the cash drawer to open? Printing however works fine*

I know the Star TSP143III only supports raster images without a driver hence the following workflow:

  • Connect to printer using WebUSB -> Create receiptline SVG -> Convert SVG to png -> Send png to printer

Example repo: https://github.com/selenecodes/webusb-printer
Example website running said repo: https://webusb-printer.vercel.app/

This is my input string:

{image:iVBORw0KGgoAAAANSUhEUgAAAQAAAAA8AgMAAAD004yXAAAACVBMVEVwAJsAAAD///+esS7BAAAAAXRSTlMAQObYZgAAAZtJREFUSMftlkGOwyAMRW0J76kE97GlZu9KcP+rzCekKak6bWdGmrZS6KIG/7yAbQhEe+tN6qUpDZ1KPHT8SnhpeaP6FlA2wicBsgOeBpTF6gDfZHgj9Jt1sAMeAYYE/RFQngYMuX49gD8fMObjkwB+++h+DeB3x/qdvfD/AP4QwPXX+ceAUdV6Y7K/3Vr7rWhv73ZN9XVHzOUdlm6v9ay3pM1eLT+Ppv63BWjz8jJU0vpUWgGs5yfihrN451G+lq7i2bkF8Bagw3Qv0hEQKGTPPjnGxJtZrSIcJy5ciJ3JStbarjrgwOtVK7Z1iLFOOgOSR3WstTqMqCcVFlITDnhhNhMKzJNIA3iEBr1uaAfArA7bSWdAkRrIsJSMrwXbJBowEhogwe9F+NilC8D1oIyg43fA+1WwKpoktXUmsiOCjxFMR+gEBfwcaJ7qDBBWNTVSxKsZZhwkUgkppEiJ1VOIQdCFtAmNBQg9QWj9POQWFW4Bh0HVipRIHlpEUVzUAmslpgQpVcS0SklcrBqf03u/UvVhLd8H5Hffil/ia4Io3warBgAAAABJRU5ErkJggg==}

Ichigaya Terminal
1-Y-X Kudan, Chiyoda-ku
02-07-2021 21:00
{border:line; width:30}
^RECEIPT
{border:space; width:*,2,10}
BEER                   | 2|     13.00
CHIDORI                | 2|    172.80
-------------------------------------
{width:*,20}
^TOTAL             |          ^185.80
CASH               |           200.00
CHANGE             |            14.20
{code:20210207210001; option:48,hri}
{command:\x07}
{command:\x1b\x07\x0b\x37\07}

Possible to print more font sizes between 1x and 2x

Hi, I was wondering if it is possible to print more text sizes between 1x and 2x with the correct aspect ratio.

The font size steps are extremely big.
2x font size (^^^) is about as big as I will ever print. Therefore it would be really nice to be able to print 1.5x

Could I achieve this by setting the default text size to 0.5x?

Then I would have the following result:
(none) = 0.5x
^^^ = 1x
^^^^ = 1.5x
^^^^^ = 2x
^^^^^^ = 2.5x
^^^^^^^ = 3x

Where in the code can I change this? I tried setting "textScale" to 0.5x but with no luck

Optimally I would want the following font sizes:
1x
1.25x
1.5x
1.75x
2x
2.5x
3x

Do you have support for this, or any tips?

Thanks

Printing HTML code

Some of my Menu Item Modifiers contain sizing information such as 12" or 14". But when printing with Star CloudPRNT in TastyIgniter it prints as 12&quot; or 14&quot;. Is there anyway to print this as intended?

Print

Cannot line up images and something

I can't put images and "images and text" side by side in designer:

|1
|{c:test;o:qrcode}
|2
|{c:test;o:qrcode}|
|3
{c:test;o:qrcode}|
|4
{c:test;o:qrcode}|{c:test;o:qrcode}
|5
{c:test;o:qrcode} | {c:test;o:qrcode}
|6
 a | {c:test;o:qrcode}
|7
 {c:test;o:qrcode} | a

image

Is this a specification?

リモートで店舗側のプリンタを印刷させるか

お世話になっております。
receiptlineを使って、店舗タッチパネル発券機能を開発したいと考えております。
一点確認させてください。
店舗タッチパネルで発券すると、情報をリモートnode.jsサーバに送って、そこで処理したデータを店舗側のレシートプリンタに印刷させるということを実現できますでしょうか。サンプルを確認したところ、プリンタ情報はnode.jsサーバに存在し、リモートネットワークに存在しているプリンタを印刷させることは無理ではないかと思います。
また、receiptlineにプリンタコマンドを生成する機能があり、上記の場合、この機能を使って、店舗側のプリンタのプリンタコマンドを生成し、店舗タッチパネルに返して、そのコマンドでプリンタに印刷させるという手段があるかと思いますが、認識があってますでしょうか。
長々と失礼しました、ご確認を宜しくお願い致します。

Support for word wrap

Hi,

It would be super helpful if you would implement word wrap functionality, is that something you will implement?

Thanks

[enhancement] transform Commands Buffer to generate SVG/Text

Would it be possible to send back commands buffer to the library and reverse the process to generate an SVG ?
It would be awesome if we can save some paper (♻️)

I want to generate a Test case for the library and would like to send commands back to the library and see what the print would look like if i sent the commands to the printer

for E.G,
The general use-case is like this,
[Client] -> [receiptline] -> [Commands] -> [Printer]

I would like to achieve the following,
[Client] -> [receiptline] -> [Commands] -> [receiptline] -> [SVG / Text]

This would allow me to run test cases to check the client properly,
I also append some other commands present here that are not present in the receiptline library

Baud rate with the Serial-LAN Converter

Could you please help me to be able to specify the baud rate with the Serial-LAN Converter?

I am using the Fujitsu FP-510 serial port model.
The default baud rate for this model is 115200 BPS.
On the other hand, the baud rate in the Serial-LAN Converter seems to be hard coded at 9600 BPS.

https://github.com/receiptline/receiptline/blob/e9da70931442d771db01a94384ba57bb66eda0ca/designer.js#L49C63-L49C63

I am now using my FP-510 with the setting changed to 9600BPS.

Additionally, the ReceiptIO project seems to be hard coded at 115200BPS.
https://github.com/receiptline/receiptio/blob/371fed0c9215f7c20275f77ee97a3827242facc5/lib/receiptio.js#L505C41-L505C41

I am now using my FP-510 settings switched.

It would be useful if the baud rate could be set in servers.json.

Thank you.

invisible image

Hi! Thanks for this amazing open source project!
I use https://receiptline.github.io/designer/ to design my bill. When I downloaded the receiptline.txt and i checked it with a text editor, It' was just fine!

But!

When i used it with node.js like that:

  const doc = fs
    .readFileSync("/home/zaki/Downloads/receiptline.txt", { encoding: "utf-8" })
    .toString();

  const display = {
    cpl: 48,
    encoding: "cp437",
  };

  const svg = receiptline.transform(doc, display);
  fs.writeFileSync("/home/zaki/Documents/receiptline.svg", svg);

The image logo included in my bill is was disappeared!

I opened the SVG file with a text editor, It doesn't have the image (base64)!
It seems Like the receiptline.transform parser ignore it!
Why?

Support for Star TSP143IIILAN

Hi @receiptline,

Things worked pretty well with Star-MC printers and the receiptline works perfect.

I tried to test on Star TSP100IIILAN or TSP143IIILAN and it did not work and it may be due to no support for ESC commands for Star 100/143 printers.

Is it possible that you could please add support for Star TSP100IIILAN? Like Epson TM-220, the Start TSP100 is also widely used by restaurants.

Could there be a work-around so that I could still use receiptline and send the print to Star-100/143? I looked at other libraries but I am very reluctant to use other library as we have already invested on reciptline for the printing.

It will be very helpful to us as we have developed everything using receiptline for local and web printing.

I really appreciate your help on this the way you helped on Epson Impact Printers.

Add TypeScript typings

Looks like a great library, but missing TypeScript typings.

Would be great to have them, and they can be easily maintained in a .d.ts file.

Question: How to send kick cash drawer command to printer?

Hi @receiptline again!

Previously I would send the following command as bytes directly to kick the cash drawer:
[0x1b, 0x70, 0x00, 0x19, 0xfa]

According to the receiptline docs, the equivalent receiptine doc would be like this:
{command:\x1b\x70\x00\x19\xfa}

However, this doesn't successfully kick the cash drawer.
Am I missing something? Is there a better recommended way to do this?

PS: I'm testing on an Epson TM-T82X printer, using the following receiptline printer configuration

{
      encoding: 'gb18030', // Chinese
      command: 'escpos',
};

more documentation

Dear receiptline / receiptio:

This project looks great. But as a non-node.js developer, it is difficult to get things running. A step-by-step example would be great.

I have a Epson TM-T88IV and a Star TSP100(USB version, not network version) here. I try to print on it with receiptline, but no success. I am using Ubuntu 20.04 on x86-64, the printers are on /dev/lp0 and /dev/lp1.

Could you guide me, how I can print on the Epson or Star with receiptline or receiptio? I have the designer running on localhost:8080, but I dont know where to enter the /dev/lp0 or lp1. Or even better, printing from the command line.

Thanks and Merry Christmas,

Star MC-Print3 CloudPRNT Opening Cash Register

Good evening,

Is there an example on how to open the cash register via receiptline command for starsbcs?
I tried Star's built in header for opening register, but it will only work if the specified content type is "text/plain". Even so, it will print a piece of blank paper that does effectively nothing.

Code:
const starPrinterRouter = express.Router(); const printer: Printer = { cpl: 48, encoding: 'cp437', upsideDown: true, spacing: true, command: 'starsbcs', }; const order = () => {width:}
^^^Online Order
${new Date().toLocaleString('en')}
{width:4,
}

|^^^2|^^Hamburger
| |Tomato, Onion, Meat sauce, Mayonnaise
| |`"Mustard
|^^^2|^^Clam chowder
| |Oyster cracker

{code:1234567890; option:code128,2,72,hri}`;

let data = order();
console.log(data);

const command = receiptline.transform(data, printer);
// remove ESC @ (command initialization) ESC GS a 0 (disable status transmission)
const bin = Buffer.from(command.slice(6), 'binary');
// const bin = Buffer.from(command, 'binary');
console.log(bin);

// res.end();
res
  .set({
    'Content-Type': 'text/plain',
    'X-Star-CashDrawer': 'start',
  })
  .status(200)
  .send(bin);`

Thanks!

Alignment Problem

Hi,

I am creating a design using the receiverline designer. However, alignment does not work properly. I am using Epson tm-t88vi thermal printer. I'm using "escpos" command.

This is my design.

`^^^^^^^^100

|"SHOP-NAME"|
|SHOP-ADDRESS-SHOULD-BE-HERE|
|SHOP-CITY|
|SHOP-COUNTRY|

|"ID | ORDER-ID|
|"DATE | ORDER-DATE|
|"TABLE | ORDER-TABLE|
|"SERVER | ORDER-SERVER|
|"TYPE | ORDER-TYPE|


|"CUSTOMER
|CUSTOMER-NAME


|X |NAME | AMOUNT|
|1 |Gazpacho (Medium Portion) | 15.65|


|"Notes
|The quick brown fox jumps over the lazy dog.


|SUBTOTAL | 30.50|
|TAX | 2.50|
|TOTAL | 33.00|`

and this is the result.

WhatsApp Image 2022-08-15 at 12 08 11 PM (1)

note: also divider not working properly. If I use the receiptline's own divider, emoji-like characters appear in the line.

Helper function to escape text

Imagine I have this template:

const doc = `
Item | Qty | Amount
${item} | ${qty} | ${amount}
`

Now what if item has | or any other special symbol inside? The whole document is broken.

I imagined there would be a helper function like receiptline.escape(mytext) but there isn't one.

It's not working at gb18030

Hi

I have tested encoding with gb18030, cp936, cp949, ksc5601, cp950, big5.
It's not working,but working at cp866,cp863,cp860.
Please tell me how to fix it

"printer1": {
    "host": "127.0.0.1",
    "port": 9100,
    "asImage": false,
    "cpl": 48,
    "encoding": "gb18030", //  cp936, cp949, ksc5601, cp950, big5
    "gradient": true,
    "gamma": 0.1,
    "threshold": 1,
    "upsideDown": false,
    "spacing": true,
    "cutting": true,
    "command": "escpos"
},

Thanks!

Small font with ESC/POS - CPL: 32 -> CPL:42

Hello Receiptline,

I would like to use the ESC/POS printers integrated small-font.
With the small font I get 42 characters per line instead of 32 characters.
However, I would only use this small font for a certain part, the rest should remain CPL: 32 with the normal font.

With {command:\x1b\x4d\x01} I can activate the small font
when I'm done I switch back to normal font with {command:\x1b\x4d\x00}.

Now I have the problem that the text in the line is cut off after 32 characters.

Do you see a simple solution to change the CPL in between?

Thank you!

Better image processing support

I have issues using svg-to-png and the underlying pupperteer modules due to a proxy issue. I also did not like the size and overhead that these modules bring with them.

As a result of this, I started to investigate processing the generated SVG with regular image processing tools like imagemagick, or the npm package sharp, but found these had subtle issues with processing the SVG.

I was able to resolve these issues with the following custom command, which allowed me to use sharp in the following manner:

import sharp from 'sharp'
const svg = receiptline.transform(...)
const png = await sharp(svg).png().toBuffer()

Not only is this significantly quicker than puppeteer, it is also comes with a much smaller dependency size.

My custom command is as below:

const custom = {
  ...receiptline.commands.svg,
  ...{
    close: function() {
      return receiptline.commands.svg.close.bind(this)()
        .replace('>', '><rect width="100%" height="100%" fill="white"/>')
        .replace('<filter id="receiptlineinvert" x="0" y="0" width="100%" height="100%">', '<filter id="receiptlineinvert" x="-1%" y="-15%" width="102%" height="150%">')
    },
    text: function (text, encoding) {
      let p = this.textPosition;
      const attr = Object.keys(this.textAttributes).reduce((a, key) => a + ` ${key}="${this.textAttributes[key]}"`, '');
      this.textElement += `<text${attr}>`
      for (const character of Array.from(text)) {
        const q = this.measureText(character, encoding) * this.textScale;
        const r = (p + q / 2) * this.charWidth / this.textScale;
        p += q;
        this.textElement += `<tspan x="${r}">${character.replace(/[ &<>]/g, r => ({' ': '&#xa0;', '&': '&amp;', '<': '&lt;', '>': '&gt;'}[r]))}</tspan>`;
      }
      this.textElement += `</text>`
      this.textPosition += this.measureText(text, encoding) * this.textScale;
      return '';
    },
  }
}

Most of these changes are transparent to the output, and will work fine in a browser, as well as with generic image processing tools. The only exception to this for which I have been unable to find a workaround for is the receiptlineinvert filter. Whilst what I have provided above seems to work well in an image processor or sharp, in chrome there is just a bit too much "padding" around the element.

Is there some way to incorporate these changes so that generic image processing tools can be used to process the svg?

Cannot use designer

Installing the project with npm or cloning master gives me the following error when trying to run the designer:

/mnt/d/Tools/receiptline-master$ node designer.js
node:internal/modules/cjs/loader:936
  throw err;
  ^

Error: Cannot find module 'receiptline'
Require stack:
- /mnt/d/Tools/receiptline-master/designer.js
    at Function.Module._resolveFilename (node:internal/modules/cjs/loader:933:15)
    at Function.Module._load (node:internal/modules/cjs/loader:778:27)
    at Module.require (node:internal/modules/cjs/loader:999:19)
    at require (node:internal/modules/cjs/helpers:102:18)
    at Object.<anonymous> (/mnt/d/Tools/receiptline-master/designer.js:23:21)
    at Module._compile (node:internal/modules/cjs/loader:1099:14)
    at Object.Module._extensions..js (node:internal/modules/cjs/loader:1153:10)
    at Module.load (node:internal/modules/cjs/loader:975:32)
    at Function.Module._load (node:internal/modules/cjs/loader:822:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:77:12) {
  code: 'MODULE_NOT_FOUND',
  requireStack: [ '/mnt/d/Tools/receiptline-master/designer.js' ]
}

Node.js v17.9.1

[enhancement] More programming languages

Is there any planning to support other programming languages!
Like Go python, dart C++, rust, ruby, php etc ...
The good thing of ReceiptLine is the use of Markdown! So the portability is fulfilled here.
You just have to remake the parser to the other programming languages!

in my opinion you have just to support SVG rendering, then the developer convert it to PNG image and print it easily, That's what i did in nodejs

An imagination example code (python):

import receiptline as rc

doc = '{code:2012345678903;option:ean,hri}'
display = (cpl: 42, encoding: 'cp437')
svg = rc.transform(doc, display)

Sending print jobs through AWS Lambda

Hello receiptline,
I have printer mC-Print2 and integration with it through AWS Lambda at node js
Here is the code

 const printer = {
            cpl: 42,
            encoding: 'cp865',
            upsideDown: true,
            spacing: true,
            command: 'starmbcs2'
        };

 res.status(200).type('application/vnd.star.starprntcore').send(Buffer.from(receiptline.transform(job, printer).slice(6), 'binary'));
 res.end()

here is the print job

{border: space; width: * 4 8}
-
|ITEM|QTY|AMOUNT|
-
Boiled salted peanuts | 1| 5.00
Tanashi cabbage with salted flavor | 1| 5.00
Shinshu lettuce salad | 1| 5.00
Ishigaki strawberry rolled cake | 1| 5.00
Peach juice from Date | 1| 5.00
-

I have tried few different config sets, but the result it's still not the best :(
With starmbcs2 it's somehow works, but not all of formatting

I've attached a photo with results

Can you please provide tips to print it correctly?
Thanks!

20220530_143745

printing Hebrew language

Hi,
i just bought star MC3-printer, i would like to send a print job with an Hebrew letters.

Additionally i need some help with the printer setup so if it's possible to get some help.

TNX.

[bug] A0 characters in the first line

Updated 2022-11-09: With the latest version 1.13.0, you may not run into these issues any more, just check out receiptio and add an option -p generic, everything should be normal now.


Hi team, thanks for the great work in advance!

I would like to report a bug here, check below as a reproduction repository:

https://github.com/Ynewtime/receiptline-report

Basic description: I copied the code directly from https://github.com/receiptline/receiptio and tried to print out something, but there is always an A0 characters in the first line:

const receiptio = require('receiptio');

const receiptmd = `^^^RECEIPT

12/18/2021, 11:22:33 AM
Asparagus | 1| 1.00
Broccoli  | 2| 2.00
Carrot    | 3| 3.00
---
^TOTAL | ^6.00`;

receiptio.print(receiptmd, '-d 192.168.192.168 -p escpos -c 42').then(result => {
    console.log(result);
});

I switched another printer model but it appeared again.

1

So I suspect if it was related to the receiptline codebase.

Thanks again for the great work!

Bluetooth thermal printer - PT-210 - Lines are not displayed correctly

Hello receiptline,

I have been printing to my Bluetooth thermal printer PT-210 from my website for a long time. So far I had not done any formatting and just printed text.

Now I came across this project and I think it's great. I would like to customize my receipts and also use QR codes and a logo.

With browserify I created and integrated the receiptline-full.js.

For my first test i want to print the following:

^^^^RECEIPT

12/18/2021, 11:22:33 AM
-
|Asparagus | 1| 1.00|
|Carrot    | 3| 3.00|
-
^TOTAL | ^6.00
{code:https://receiptline.github.io/designer/; option:qrcode,3,L}

When I print out this example, the lines are not displayed correctly and the QR code is missing entirely.

IMG_20221018_154019

I use this code and deliver the content of escPos to the BT printer

const printerEscPos = {
    cpl: 32,
    encoding: 'utf-8',    // utf-8, multilingual
    spacing: false,
    cutting: false,
    gamma: 1.0,
    command: 'impact'     // impact, escpos
};

const escPos = receiptline.transform(reader.result, printerEscPos);

BluetoothPrinter.connect()
  .then(() => {
  BluetoothPrinter.print(escPos);
});
...
    print(command) {
      var encoder = new TextEncoder("utf-8");
      var commandEnc = encoder.encode(command + '\x0a');

      console.log(commandEnc);
      console.hex(commandEnc);

      const maxLength = 100;
      let chunks = Math.ceil(commandEnc.length / maxLength);
      if (chunks === 1) {
        this._queue(commandEnc);
      } else {
        for (let i = 0; i < chunks; i++) {
          let byteOffset = i * maxLength;
          let length = Math.min(commandEnc.length, byteOffset + maxLength);
          this._queue(commandEnc.slice(byteOffset, length));
        }
      }
    }
...

Here is the console output for console.log(commandEnc) and console.hex(commandEnc)
image

I guess it's an ecoding problem, maybe you could give me a hint please?

Sending commands to printer through Cloud Print

Hi,

First - Thank you San for your work and sharing. This is very helpful.

We are using Star - MC3 printer and using its CloudPrint facility to send print through the REST API server as we need to print directly on the printer without any intermediate device. After looking through your markup language, I am reluctant to use Star proprietary markup language. We would like to follow a standard, that you are developing.

I ran your sample code and it works fine if I send the print commands directly to my printer in the local subnet using its IP address and port 9100. The prints are as advertised and seen through the designer - which is really very useful to visualize.

But, when I send the same command through the REST API through our API server to the printer, everything prints OK except the line.

Here is the sample code:

printCommands.js file

var doc = `
{width:auto}
|^^^^Pizza Station^^^^|

-
{width:5 *}
|^^2 @^^ |^^Royal Special Pizza |
|   |Olive, Spinach, Asparagus, Tomato  | 
|^^1 @^^ |^^12 inch Subway with basil |
-

-
{width:auto}
Delivery Station
{width:5 *}
|2 @|French Fries |
|1 @|Diet Coke |
-


{code:2012345678903;option:ean,hri}


`;
...
async function ticket() {
	// printer example
	const printer = {
		cpl: 42,
		encoding: 'cp437',
		upsideDown: false,
		gamma: 1.8,
		command: 'starmbcs'
	};
	return receiptline.transform(doc, printer); ;
}
...

The above is called in the REST API GET request sent by the printer to my API server.

var printer = require("./printCommands");
app.get('/api/v1/cloudprint', (req, res) => {
    printer.ticket().then((buffer) => {
        res.status(200).type("application/vnd.star.starprnt").send(buffer);
        toPrint = false;
    }).catch((err) => {
        console.log("Getting error in sending commands to the printer", err);
        res.status(200).end();
    });
}

I have tried starsbcs and various supported input methods from Star Link but I was not able to get the line printing properly.

I am attaching here both the prints - one sent directly to the printer (works perfectly) and another sent through REST API using CloudPrint of Star Printer.

sample

Can you please provide tips or hacks for the time being so that I am able to print it correctly?

Thank-You San!

Question: Unable to print Simplified Chinese & Japanese characters (Epson TM-T82X)

Hi receiptline team! I'm really loving what you guys are building so far.

I'm trying to print Simplified Chinese characters onto using escpos command on an Epson TM-T82X printer, but I'm getting gibberish instead.
For context, I'm using this in a React-Native app.
Also, it seems like Chinese printing is supported from the official docs for this specific printer model.
https://reference.epson-biz.com/modules/ref_escpos/index.php?content_id=364

Chinese

image

receiptline document

敏捷的棕色狐狸跳过懒狗

Printer config

const printer = {
  encoding: 'gb18030', // and cp936
  command: 'escpos',
};

Japanese

I tried printing the Japanese sample afterwards to test it and there was a similar problem

image

receiptline document

敏捷的棕色狐狸跳过懒狗

Printer config

const printer = {
  encoding: 'cp932', // and shiftjis
  command: 'escpos',
};

English

Here's the working English sample for comparison.

image

Thank you team in advance!

Allow to override/extend printer implementations

I would like to use my own open() for a ESC/POS printer that I work with.

However, all implementations live in a closure and there is no way to extend or provide an override.

I would expect at least something simple as:

const receipt_data = receiptline.transform(doc, {
	encoding: "cp866",
	command: "escpos",
	commands: {
		open: function (printer) { return "..." }
	},
})

Possible support for other Asian languages?

Would like to know is there any possibility to have other Asian languages (e.g. Traditional Chinese) support?

If it can be done where should I get started so I could contribute a PR?

Thanks!

[enhancement] inline images

First of all Thanks for this amazing project!
Is there any planning to support inline images? Like this example below:
(This is an SVG printed as image)

Sending data directly to the printer (possibility)

Is there some way to send the output directly to the printer or is there some plan to implement it? It'd be too usefull. Currently, Node environment doesn't have good choices for that. Actually, I just know a lib called printer for that which has some problems and limitations.
Thank you so much.

Customize the output font

I want to change the output font to something other than the font that is currently being used

default:
                    p.font = `'Courier Prime', 'Courier New', 'Courier', monospace`;
                    p.size -= 2;
                    p.style = '@import url("https://fonts.googleapis.com/css2?family=Courier+Prime&display=swap");';
                    break;

Example that is printing?

I am trying to make this work with a TM-T88v

While I am able to start the designer and create receipts there, I am still puzzled about how this library actually is able to send anything to a printer. In one terminal window I have this :

Virtual printer running at 127.0.0.1:19100
Server running at http://127.0.0.1:8080/

I also looked at example receiptes. Those render nicely in designer, but not sure how we would use them. Base templates?

Then I am copying the example code and running it in separate project and nothing seems to happen.

I modified the example code here with my printer IP as well as the Virtual Printer + port

const printer = {
        "host": "127.0.0.1",
        "port": 19100,   
    cpl: 42,
    encoding: 'cp437',
    upsideDown: false,
    gamma: 1.8,
    command: 'escpos'
};

When I run node testprint.js where testprint contains my code. Nothing happens.
Is this library supposed to send anything to the TM-T88v?

In short, is there a direct example that I can follow that show how I can send something to the printer via IP to print?

In contrast this library made this fairly easy:
https://www.npmjs.com/package/node-thermal-printer
I was able to run the example command and it printed an example directly to the printer
node examples/example.js tcp://x.x.x.x

Any insight is appreciated.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.