IONIC:如何通过蓝牙串行打印HTML内容?



我正在制作一个POS应用程序。我通过蓝牙串口连接我的应用程序,将数据发送到打印机。我的打印机是RPP02N蓝牙热敏打印机。我正在使用蓝牙串行插件。

下面是我的代码:
await BluetoothSerial.clear();
await BluetoothSerial.disconnect();
let connection = await BluetoothSerial.connect(pId);
connection.subscribe(async success => {
if (success == 'OK') {
BluetoothSerial.write("Test Print").then(() => {
console.log("Print finished");
BluetoothSerial.disconnect();
});
} else {
BluetoothSerial.disconnect();
}

这工作得很好,但我必须使用raw string的数据,像这样:

"     SHOP NAME     "
"  77 ABC ST, 12345 "
" ----------------- "
" <MY_________DATA> "

很难像这样对齐内容。我需要我的内容是响应,它可以在不同的纸张尺寸打印。此外,它还需要能够打印图像徽标。

我该怎么做?


转换为图像

我尝试了另一种方法,将其转换为图像。

这是我的html内容:

<canvas>
<h3>Shop Name</h3>
<h5>77 ABC ST, 12345</h5>
<hr/>
<p>My content</p>
</canvas>

这是代码:

var img = new Image();
img.src = canvas.toDataURL("image/png");

img.onLoad()方法中:

img.onLoad = async() => {
....
....
const encoder = new EscPosEncoder();
let result = encoder
.image(img, 320, 160, 'atkinson', 128) //width must be multiplication of 8
.encode();
BluetoothSerial.write(result).then(() => {
console.log("Print finished");
BluetoothSerial.disconnect();
});
}

我正在使用这个节点模块转换成ecs pos

不工作,打印机打印1个空行。


打印原始html

我尝试打印原始html。事实证明,它实际上是按字面意思打印原始html(如:<canvas>....</canvas>)。

要在蓝牙打印上打印HTML内容,您需要使用esc-pos-encoder对HTML数据进行编码。

以下是在蓝牙打印机上打印HTML内容的步骤。
  1. 将HTML代码附加到body。
  2. 现在取HTML节点并创建它的图像。
  3. 一旦图像创建使用esc- post -encoder编码图像数据
  4. 发送编码数据到打印机。

public print() {
const elemId = this.prepareHtmlData(htmlStr, width);
const node = document.getElementById(elemId);
const img = new Image();
img.onload = async () => {
const imgWidth = this.checkNumberMultiple(img.naturalWidth, 8);
const height = this.checkNumberMultiple(img.naturalHeight, 8);
const encoder = new EscPosEncoder();
const printData = (encoder.initialize().image(img, imgWidth, height).newline().encode()).buffer;
console.log('sending data to device...');
await bluetoothSerial.write(printData);
await bluetoothSerial.disconnect();
}
const canvas = await html2canvas(node);
let imgSrc = canvas.toDataURL("image/png");
img.src = imgSrc;
}

最新更新