Tuesday, September 5, 2017

Generating a barcode in a NativeScript application

NativeScript is a great platform for building cross-platform mobile applications that I'm currently working on. One problem that I had to solve recently was how to generate a barcode in a NativeScript I'm currently building.

One very straight forward approach is to use a plugin like the nativescipt-zxing plugin. While this will do a great job, it will have a significant impact if you only want to generate the barcode and you don't need a scanning functionality.

Another approach that I found more appropriate is to use a barcode font. The steps for implementation are very similar:

  1. Found a barcode font that suits your needs and add it to the 'fonts' folder of your app. This font is a good free choice if you want to generate a CODE39 barcode.
  2. Create a css class that uses your font. Have in mind that Android uses the file name of your font as font name and iOS uses the font name embedded in the font file. With the font above the name of the file is 'free3of9' and the font name itself is 'New'. To work around this - you can rename the file name to match the font name.
  3. .barcode {
        font-family: 'free3of9';
    }
  4. After than create a Label with text of the value that you want to be encoded in the barcode and class, the css class that you previously created. For example, if the next that the barcode should read is 234345631, your Label should look like this:
    <Label class="barcode" text="*234345631*"> </Label>
    
Mind that the text is surrounded with * signs. This is required by the CODE39 standard, more about the barcode standards can be found here: http://www.keyence.com/ss/products/auto_id/barcode_lecture/basic/mechanism

Depending on your css rules, your barcode might look like a little short, which will make the scanning hard as you will need to align more precisely the scanner. To make the barcode "taller", you can add a css scale transform to your 'barcode' class:
.barcode {
    font-family: 'free3of9';
    transform: scaleY(2);
}
I hope you find this little trick useful!