Backend Development 4 min read

Generating Barcodes in Python with Pillow and pyBarcode

This guide explains how to install the Pillow and pyBarcode Python packages and demonstrates two methods for generating various barcode formats—such as EAN13, Code39, and UPC—using the pyBarcode library, including code examples, configuration options, and saving the output as image files.

Test Development Learning Exchange
Test Development Learning Exchange
Test Development Learning Exchange
Generating Barcodes in Python with Pillow and pyBarcode

First, install the Pillow library (skip if already installed) using:

pip install Pillow

Next, install the pyBarcode library:

pip install pyBarcode

The pyBarcode library supports the following barcode formats: 'code39', 'ean', 'ean13', 'ean8', 'gs1', 'gtin', 'isbn', 'isbn10', 'isbn13', 'issn', 'jan', 'pzn', 'upc', 'upca'.

Method 1: Generate an EAN13 barcode and save it as an image.

# Generate barcode
# Import modules
import barcode
from barcode.writer import ImageWriter

print(barcode.PROVIDED_BARCODES)

img_path = "/Users/XXX/Downloads/demo"
EAN = barcode.get_barcode_class('ean13')
ean = EAN('5901234123457', writer=ImageWriter())
fullname = ean.save(img_path + '')
print(fullname)

Method 2: Generate a Code39 barcode with custom options.

# Import module
import barcode

# Get barcode class for Code39
Code = barcode.get_barcode_class('code39')  # supported format

# Create barcode object
bar = Code("123456")
"""
Code constructor signature: Code(code, writer=None, add_checksum=True)
- code: data to encode (e.g., '123456')
- writer: defaults to SVGWriter; use ImageWriter for PNG/JPEG/BMP
- add_checksum: default True, adds checksum; set False to omit
"""

# Save barcode file (no extension needed)
bar.save("/Users/XXX/Downloads/test-imgs")
"""
save(filename, options=None)
- filename: base name without extension; extension added automatically based on writer
- options: dictionary to customize output, e.g.,
    {'module_width': 0.2, 'module_height': 15.0, 'quiet_zone': 6.5,
     'font_size': 10, 'text_distance': 5.0, 'background': 'white',
     'foreground': 'black', 'text': '', 'write_text': True,
     'center_text': True, 'format': 'PNG', 'dpi': 300}
"""
Pythonimage generationcoding tutorialpillowBarcodepyBarcode
Test Development Learning Exchange
Written by

Test Development Learning Exchange

Test Development Learning Exchange

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.