20

Does someone knows a tool to generate barcode image (preferably code 39) from a string and converts it to base64 string, something to use like this:

var text = "11220"; // text to convert
var base64Str = textToBase64Barcode(text); // function to convert its input 
        // to an image formatted in a base64 string like : "data:image/jpeg;base64..."

?

Nikhil K Mannem
  • 41
  • 1
  • 1
  • 14
lennin92
  • 493
  • 2
  • 8
  • 17

3 Answers3

45

Using JsBarcode this function will do what you want.

function textToBase64Barcode(text){
  var canvas = document.createElement("canvas");
  JsBarcode(canvas, text, {format: "CODE39"});
  return canvas.toDataURL("image/png");
}
Lindell
  • 701
  • 6
  • 6
3

if you need this function in node.js side, you can try below

const bwipjs = require('bwip-js');

function textToBarCodeBase64 (text) {
    return new Promise((resolve, reject) => {
        bwipjs.toBuffer({
            bcid: 'code128',
            text: text,
            scale: 3,
            height: 10,
            includetext: true,
            textxalign: 'center'
        }, function(error, buffer) {
            if(error) {
                reject(error)
            } else {
                let gifBase64 = `data:image/gif;base64,${buffer.toString('base64')}`
                resolve(gifBase64)
            }
        })
    })
}

about bwip-js see bwip-js for more details

2

From my perspective (frontend), the alternative option is bwipjs

const canvas = document.createElement('canvas');

    const dataURL = bwipjs
      .toCanvas(canvas, {
        bcid: 'upca', // Barcode type
        text: barcode,
        scale: 3, // 3x scaling factor
        height: 20, // Bar height, in millimeters,
        border: 5,
        includetext: true, // Show human-readable text
      })
      .toDataURL('image/png');
Will
  • 325
  • 2
  • 9
  • How can you use it in JS/TS. I get an error `Property 'toCanvas' does not exist on type 'typeof BwipJs'.` when running `yarn unit-test`. – Sardar Faisal Sep 01 '23 at 10:54