Search code examples
reactjsnpmbarcodezebra-printers

npm react-barcodes print barcode


Im trying to print a barcode from reactjs to zebra printer.

I use npm package react-barcodes to gen a barcode then tried this post below to print but barcodes are not correct.

How to print a react-barcode component

Has anyone got this working?


function Barcode(ref) {
  const { inputRef } = useBarcode({
    value: ref.barId,
    options: {
      format: "ean13",
      flat: true,
      height: 60,
      width: 1.2,
      fontSize: 18
    }
  });

  return <canvas id="barcode-canvas" ref={inputRef}/>;
};

Barcode that I generate

Then finally using the print function

const opt = {
        scale: 4
    }
    const elem = document.getElementById("barcode-canvas");
    html2canvas(elem, opt).then(canvas => {
        const iframe = document.createElement('iframe')
        iframe.name = 'printf'
        iframe.id = 'printf'
        iframe.height = 0;
        iframe.width = 0;
        document.body.appendChild(iframe)
    
        const imgUrl = canvas.toDataURL({
            format: 'jpeg',
            quality: '1.0'
        })
    
        const style=`
            height:100vh;
            width:100vw;
            position:absolute;
            left:0:
            top:0;
        `;
    
        const url = `<img style="${style}" src="${imgUrl}"/>`;
        var newWin = window.frames["printf"];
        newWin.document.write(`<body onload="window.print()">${url}</body>`);
        newWin.document.close();
    });

The barcode prints out low res and on only a small section of the barcode. Dont know if its the print function or the printer settings.


Solution

  • The barcode prints out low res and on only a small section of the barcode. Dont know if its the print function or the printer settings.

    This was due to both the way the barcode was rendered and the method used.

    I changed to svg instead and then used this to download the barcode:

    onPrintBarcode = () => {
        var container = document.getElementById("div-svg");
        var mySVG = document.getElementById("barcode-canvas");
        var width = "100%";
        var height = "100%";
        var printWindow = window.open('', 'PrintMap',
        'width=' + width + ',height=' + height);
        printWindow.document.writeln(container.innerHTML);
        printWindow.document.close();
        printWindow.print();
        printWindow.close();
      }
    

    This worked for me.