How to Generate a Barcode Using Python

How to Generate a Barcode Using Python

Introduction

Install module

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.

Leave a Comment

Your email address will not be published. Required fields are marked *