Python ReportLab – Change barcode height

In this post we will be creating a Python script that will generate a barcode of a predefined height 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.

For the purpose of this example we will be creating an EAN-13 barcode. Retail and other industries commonly use the EAN-13 barcode for product identification and tracking. EAN-13 barcodes are 13 digits long, this allows EAN-13 barcodes to encode more information than other types of barcodes. (usually 12 digits long)

See the sample of Python code below where we use the ReportLab library to generate a barcode of a predefined height. We start by creating a new PDF document called ‘barcode.pdf’ and assign it to the variable ‘myCanvas’. We then create a new EAN-13 barcode drawing object with the value ‘8523659632598’ and assign it to the variable ‘newBarcode’. Here ‘barHeight=10*mm‘ is also passed as an argument which sets the height of the barcode to 10 millimeters. Our ‘newBarcode’ object is then drawn onto the PDF canvas at the position (50, 50) on the page. The PDF document is then saved and the canvas is closed.

from reportlab.lib.units import mm
from reportlab.graphics import barcode
from reportlab.pdfgen import canvas

myCanvas = canvas.Canvas('barcode.pdf')

newBarcode = barcode.createBarcodeDrawing('EAN13', value='8523659632598', barHeight=10*mm)

newBarcode.drawOn(myCanvas, 50, 50)

myCanvas.save()

See below a barcode with no height defined. (Default)

Python ReportLab - barcode with no height defined

See below our barcode with a predefined height of 10 millimetres.

Python ReportLab - barcode with predefined height of 10 millimetres.

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

Leave a Reply