How to print barcode on sticker using React Native

What if you could print any barcode in React Native? That’s exactly what we’re going to do today! And the best part? We’re going to use the power of React-Native to do it! It will be easier than you think, trust me! Let’s get started!

Create react-native project

The first step in building a react native project is creating a React Native Project. If you don’t know about react native, I’d suggest you follow this link. React Native

Let's initialize our react native project using the following command

npx react-native init RNPrintBarcode

Once you are done with the project setup install the pods and run for both Android and iOS

To install pods:

npx pod-install

To run Android build:

npx react-native run-android

To run iOS build:

npx react-native run-ios

Install required library

Now let's install the react-native-print library to generate actual print. run the following command to install react-native-print library

npm install react-native-print --save

after installing the library install pods and link it with the native project

To install pods:

npx pod-install

To link:

npx react-native link

Important: This blog's main purpose is to display barcodes on print canvas rather than to display them on UI.

Set up print button

Okay, so we are all done with the installation part now let's just design a simple UI with one button and text input.

import {
  View,
  Text,
  SafeAreaView,
  StyleSheet,
  TextInput,
  TouchableOpacity,
} from 'react-native';
import React, {useState} from 'react';
import RNPrint from 'react-native-print';
const App = () => {
  // State variable
  const [text, setText] = useState('');
  const [checksum, setChecksum] = useState('');
  const [finalString, setFinalString] = useState('');
  const [selectedPrinter, setSelectedPrinter] = useState('');

  return (
    <SafeAreaView style={styles.container}>
      <Text style={styles.textStyle}>
        Enter text you want to print as barcode
      </Text>
      <TextInput
        placeholder="Enter Text"
        placeholderTextColor={'#fff'}
        style={[
          styles.textStyle,
          {
            fontWeight: 'normal',
            padding: 8,
            borderColor: '#fff',
            borderWidth: 1,
            width: '80%',
            marginVertical: 20,
          },
        ]}
        onChangeText={text => generateChecksum(text)}
      />
      <Text style={[styles.textStyle, {fontWeight: 'normal'}]}>
        {'Checksum of string: ' + checksum}
      </Text>
      <Text
        style={[styles.textStyle, {fontWeight: 'normal', marginVertical: 8}]}>
        {'Scannable barcode string: ' + finalString}
      </Text>
      <TouchableOpacity
        style={styles.button}
        onPress={() => printBarcode(finalString)}>
        <Text style={styles.buttonText}>{'Print'}</Text>
      </TouchableOpacity>
    </SafeAreaView>
  );
};

export default App;

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#333237',
    padding: 10,
    alignItems: 'center',
  },
  textStyle: {
    color: '#fff',
    fontSize: 16,
    fontWeight: 'bold',
  },
  button: {
    width: 150,
    padding: 10,
    borderRadius: 8,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#605d58',
    marginTop: 20,
  },
  buttonText: {
    fontSize: 18,
    color: '#fff',
  },
});

WhatsApp Image 2022-02-04 at 6.34.48 PM.jpeg

Print barcode on the sticker

Now we are done with our UI part. let's write the actual code which will display barcodes on print canvas. Before starting let's understand how does it work.

We are going to use google libre fonts to generate barcodes. These fonts automatically convert the text into meaningful barcodes. But there is one trick you can not directly scan these barcodes. to make barcodes scannable we have to generate a checksum and attach it with our original string. we have to wrap the original string + checksum between special characters that define our barcode belongs to which category like code 128, code 39, etc.

you can find out more about google libre fonts here.

Now let's write some code here is the checksum function which generates a checksum of string and wraps string between special characters. here I am using code 128.

// TODO: generate the checksum for given string
  const generateChecksum = text => {
    setText(text);

    var x = text;
    var i,
      j,
      intWeight,
      intLength,
      intWtProd = 0,
      arrayData = [],
      chrString;
    var arraySubst = ['Ã', 'Ä', 'Å', 'Æ', 'Ç', 'È', 'É', 'Ê'];

    /*
     * Checksum Calculation for Code 128 B
     */
    intLength = x.length;
    arrayData[0] = 104; // Assume Code 128B, Will revise to support A, C and switching.
    intWtProd = 104;
    for (j = 0; j < intLength; j += 1) {
      arrayData[j + 1] = x.charCodeAt(j) - 32; // Have to convert to Code 128 encoding
      intWeight = j + 1; // to generate the checksum
      intWtProd += intWeight * arrayData[j + 1]; // Just a weighted sum
    }
    arrayData[j + 1] = intWtProd % 103; // Modulo 103 on weighted sum
    arrayData[j + 2] = 106; // Code 128 Stop character
    chr = parseInt(arrayData[j + 1], 10); // Gotta convert from character to a number
    if (chr > 94) {
      chrString = arraySubst[chr - 95];
    } else {
      chrString = String.fromCharCode(chr + 32);
    }

    // Ì and Î special characters are use for barcode code 128
    let string =
      'Ì' + // Start Code B
      x + // The originally typed string
      chrString + // The generated checksum
      'Î'; // Stop Code
    setChecksum(chrString);
    setFinalString(string);
  };

Okay, now we have our newly generated string with checksum and special characters. Now we just need to print it on canvas using react-native-print

// TODO: print final string on canvas
  const printBarcode = async barcode => {
    /**
     * Print html design
     * we will link google fonts library here
     * we have to use google font family in styling
     */
    let html = `<html>
      <head>
      <link href="https://fonts.googleapis.com/css2?family=Libre+Barcode+128+Text&display=swap" rel="stylesheet">
      <style>
        .barcode {
          font-family: 'Libre Barcode 128 Text', cursive;
          font-size: 40px;
          text-align: center;
        }
      </style>
      </head>
      <body>
        <p class="barcode">${barcode}</p>
      </body>
      </html>`;

    await RNPrint.print({
      html: html,
    })
      .then(res => conso%[Link]le.log(res))
      .catch(error => console.log(error));
  };

Now let's run the code and see the output ezgif.com-gif-maker.gif You can find the whole source code here Buy Me A Coffee