Javascript Interface for ESC/POS

David
2 min readJul 29, 2015

--

ESC/POS is a proprietary almost-open-source language, written by EPSON. It enables software to send commands and print data, in the form of a stream of bytes to the device through a USB interface.

So why the hell build an interface in Javascript?! Recently, we have been looking at deploying Google Chrome Kiosk applications. Coincidently, Google provide a set of libraries for communicating with USB devices, allowing data to be transferred directly to the device, without the need for a driver.

As Kiosk extensions are essentially packaged web applications, we needed an interface that was able to communicate with EPSON printers, using their slightly-bizarre, albeit strangely efficient ESC/POS language.

“Enough talking, show me some code!”

String.prototype.toBytes = function() {
var arr = []
for (var i=0; i < this.length; i++) {
arr.push(this[i].charCodeAt(0))
}
return arr
}
var data = “hello world”.toBytes().concat([0x01B, 0x64, 10])

Here, we have simply modified the String prototype to return an array of character codes built from itself. In Javascript, hexadecimal numbers can be represented by their decimal counterparts, therefore `0x41 === 65` holds true.

Now that we have our array of characters in hexadecimal/decimal format, we simply have to append the command informing the EPSON printer to print the data.

This command is represented by the array `[0x01B, 0x64, 10]`. Here, the commands translate into ESC/POS as `ESC d 10`; referring back to the ESC/POS documentation, we can determine that this command tells the printer to print the data preceeding this command, and feed the paper *10* lines.

Easy, right?

ESC/POS command codes are either added to a buffer at the start of a new line, or at the end of a line. An example of a command that needs to be set at the start of a line, is `[0x01B, 0x61, 0]`, which sets a particular alignment (left in this case), for text on the following lines.

So how do I send this data?

Using the `chrome.usb.*` APIs of course! Once you have constructed your array of hexadecimal representations for your text and command codes, you simply need to transform it into an ArrayBuffer of unsigned 8-bit integers.

Following on from the previous example,

var buffer = new Uint8Array(data).buffer

Summary

ESC/POS is easy once you’ve got the hang of creating the buffer of data you want to send. A buffer is an array of ASCII characters, that use the ESC character coupled with a function character to set commands.

--

--

David

Coding is both my hobby and my job. I love writing about things I'm working on ❤️