Python ReportLab – Generate a Code 128 barcode

In this post we will be creating a Python script that will generate a Code 128 barcode using the ReportLab library. ReportLab is a powerful Python library that lets you create professional-looking PDF documents. It also provides support for generating various types of barcodes. With these barcode types, you can easily create custom barcodes to make your documents stand out and automate your business processes.

Industries commonly use the Code 128 barcode type for tracking and inventory management in logistics, manufacturing, and other areas. This type of barcode is linear and capable of encoding all 128 ASCII characters.

See the sample of Python code below where we use the ReportLab library to generate a Code 128 barcode. We start by creating a new PDF document called ‘barcode.pdf’ and assign it to the variable ‘myCanvas’. We then create a new instance of the Code 128 class named ‘newBarcode’ and pass the string “236597857” as an argument to generate the barcode. Our ‘newBarcode’ object is then drawn onto the PDF canvas at the position (50, 50) on the page.

from reportlab.graphics.barcode import code128
from reportlab.pdfgen import canvas

myCanvas = canvas.Canvas("myBarcode.pdf")

newBarcode = code128.Code128("236597857")

newBarcode.drawOn(myCanvas, 50, 50)

myCanvas.save()

An image of the barcode in our PDF can be seen below.

Python ReportLab - Generate a Code 128 barcode

Take a look at some of our other content around the Python programming language by clicking here.

Leave a Reply