Open In App

How to Generate Barcode in Python?

In this article, we are going to write a short script to generate barcodes using Python. We’ll be using the python-barcode module which is a fork of the pyBarcode module. This module provides us the functionality to generate barcodes in SVG format. Pillow is required to generate barcodes in image formats (such as png or jpg).

Modules Needed

pip install python-barcode 
pip install pillow

Here, we are going to generate a barcode in the EAN-13 format. First, let’s generate it as an SVG file.






# import EAN13 from barcode module
from barcode import EAN13
  
# Make sure to pass the number as string
number = '5901234123457'
  
# Now, let's create an object of EAN13
# class and pass the number
my_code = EAN13(number)
  
# Our barcode is ready. Let's save it.
my_code.save("new_code")

Output:

Generated barcode as SVG file

Now, let’s generate the same barcode in PNG format.






# import EAN13 from barcode module
from barcode import EAN13
  
# import ImageWriter to generate an image file
from barcode.writer import ImageWriter
  
# Make sure to pass the number as string
number = '5901234123457'
  
# Now, let's create an object of EAN13 class and 
# pass the number with the ImageWriter() as the 
# writer
my_code = EAN13(number, writer=ImageWriter())
  
# Our barcode is ready. Let's save it.
my_code.save("new_code1")

Output:

Generated barcode as PNG file


Article Tags :