【问题标题】:How to convert SVG into ArrayBuffer to send to a webusb device如何将 SVG 转换为 ArrayBuffer 以发送到 webusb 设备
【发布时间】:2021-02-19 16:03:43
【问题描述】:

我有一个连接到 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);
    });

任何帮助将不胜感激。

【问题讨论】:

标签: angular svg webusb


【解决方案1】:

这样的事情应该可以工作。这里我们从 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'

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-03
    • 1970-01-01
    • 2023-02-08
    • 1970-01-01
    • 2011-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多