88 lines
1.7 KiB
TypeScript
88 lines
1.7 KiB
TypeScript
/**
|
|
* A simple ESC/POS encoder for thermal printers
|
|
*/
|
|
export class EscPosEncoder {
|
|
private encoder = new TextEncoder();
|
|
private buffer: number[] = [];
|
|
|
|
constructor() {}
|
|
|
|
/**
|
|
* Initialize printer
|
|
*/
|
|
initialize(): this {
|
|
this.buffer.push(0x1b, 0x40);
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Write text
|
|
*/
|
|
text(value: string): this {
|
|
const bytes = this.encoder.encode(value);
|
|
this.buffer.push(...Array.from(bytes));
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Write text with newline
|
|
*/
|
|
line(value: string = ''): this {
|
|
this.text(value + '\n');
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Set alignment
|
|
* 0: left, 1: center, 2: right
|
|
*/
|
|
align(value: 0 | 1 | 2): this {
|
|
this.buffer.push(0x1b, 0x61, value);
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Set bold
|
|
*/
|
|
bold(value: boolean): this {
|
|
this.buffer.push(0x1b, 0x45, value ? 1 : 0);
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Set font size
|
|
* 0: normal, 1: double height, 2: double width, 3: double height + width
|
|
*/
|
|
size(value: 0 | 1 | 2 | 3): this {
|
|
let size = 0;
|
|
if (value === 1) size = 0x01;
|
|
if (value === 2) size = 0x10;
|
|
if (value === 3) size = 0x11;
|
|
this.buffer.push(0x1d, 0x21, size);
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Feed and cut
|
|
*/
|
|
cut(): this {
|
|
this.buffer.push(0x1d, 0x56, 0x00);
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Feed lines
|
|
*/
|
|
feed(lines: number = 1): this {
|
|
this.buffer.push(0x1b, 0x64, lines);
|
|
return this;
|
|
}
|
|
|
|
/**
|
|
* Get the encoded bytes
|
|
*/
|
|
encode(): Uint8Array {
|
|
return new Uint8Array(this.buffer);
|
|
}
|
|
}
|