首页 > 解决方案 > 如何将 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);
    });

任何帮助将不胜感激。

标签: angularsvgwebusb

解决方案


像这样的东西应该工作。在这里,我们从 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'


推荐阅读