angular - 如何将 SVG 转换为 ArrayBuffer 以发送到 webusb 设备
问题描述
我有一个连接到 chrome 的 WEBUSB 打印机,它可以打印从我的 Angular 应用程序发送的数据。我能够使用 ngx-barcode 以 SVG 的形式创建 BARCODE。但是我应该以哪种格式将其发送到 USB 打印机。我尝试了以下方式。但它会打印一些特殊字符文本。
const barcodeSvg = this.barcodeElm.bcElement.nativeElement.querySelector('svg');
const serializer = new XMLSerializer();
const svgXmlString = serializer.serializeToString(barcodeSvg);
const typedArraySvg = Uint8Array.from(Array.prototype.map.call(svgXmlString, c => c.charCodeAt(0)));
this._service.printBarcode(typedArraySvg);
我的 printBarcode 函数是
this.device.transferOut(1, printdata)
.catch(error => {
console.log('Failed to print', error);
});
任何帮助将不胜感激。
解决方案
像这样的东西应该工作。在这里,我们从 SVG 字符串创建一个 Blob,然后在 FileReader 的帮助下将其转换为 ArrayBuffer。
const barcodeSvg = this.barcodeElm.bcElement.nativeElement.querySelector('svg');
const serializer = new XMLSerializer();
const svgXmlString = serializer.serializeToString(barcodeSvg);
// Create a blob from SVG string
const blob = new Blob([svgXmlString], {
type: 'image/svg+xml'
});
const reader = new FileReader();
reader.onload = function() {
var arrayBuffer = reader.result;
// Feed the service with result ArrayBuffer
this._service.printBarcode(arrayBuffer);
};
// Use reader to transform the Blob to the ArrayBuffer
reader.readAsArrayBuffer(blob);
要尝试的另一件事是将其用作纯 HTML 字符串
const barcodeSvg = this.barcodeElm.bcElement.nativeElement.querySelector('svg');
// Create a blob from SVG string
const blob = new Blob([barcodeSvg], {
type: 'image/svg+xml'
});
const reader = new FileReader();
reader.onload = function() {
var arrayBuffer = reader.result;
// Feed the service with result ArrayBuffer
this._service.printBarcode(arrayBuffer);
};
// Use reader to transform the Blob to the ArrayBuffer
reader.readAsArrayBuffer(blob);
此外,它可能值得尝试更改type: 'image/svg+xml'
为type: 'text/html'
推荐阅读
- haskell - 两个列表元素的所有非重复组合
- android - Android 如何在 Spinner 中更改滚动条颜色
- c# - 正在更改 SessionId 导致此错误“视图状态验证失败。原因:视图状态提供的完整性检查失败。”
- android - Activity.setTheme() 之后的 Activity.recreate() 导致活动泄漏
- unique - 根据第二列计算列中的不同值
- xcode - 目标的构建设置中没有“金属编译器”
- generics - Kotlin 中的协议实现可识别的推断类型
- xcode - 在某些设备上查看效果不佳
- coq - 当 Coq 扩展一个函数作为目标的一部分时,这意味着什么?
- couchdb - CouchDB 2.x 下 local_seq 的行为是什么?