Introduction
A barcode is a machine-readable code in the form of numbers and a pattern of parallel lines of varying widths, printed on a commodity and is used especially for product management. In this tutorial, we will be looking at how to generate a barcode using Python.
Install module
In this program, we will be using the python-barcode module. To install this module open your terminal and run the command below.
pip3 install python-barcode
Create barcode
Now open a file called app.py and import the modules below.
from io import BytesIO
from barcode import EAN13
from barcode.writer import SVGWriter
Next, let’s create a class to generate and save our barcode.
class BarcodeGenerator:
def __init__(self, number):
self.number = number
def generate(self):
ph = BytesIO()
EAN13(str(self.number), writer=SVGWriter()).write(ph)
return ph.getvalue()
def save(self, filename):
with open(filename, 'wb') as f:
f.write(self.generate())
if __name__ == '__main__':
barcode = BarcodeGenerator("100000942922")
barcode.save('barcode.svg')
Run
Open your terminal and run the command shown below.
python3 app.py
Results
After running the command above your barcode should appear as shown below.
There you have it, Thanks for reading. Happy Coding.