Back to Blog
Python

Generate Code128 and EAN13 Barcodes in Python

Learn how to generate Code128 and EAN13 barcodes in Python with python-barcode, including code examples, writer options, and guidance for choosing between the two symbologies.

barcodecode128ean13python-barcodebarcode generation
Code128 and EAN13 barcode examples generated in Python with the python-barcode library.

Generating Code128 and EAN13 barcodes in Python is straightforward with the python-barcode library. Both symbologies are supported by the same package, but they have different data rules and use cases. This article shows how to generate each type, explains the available output options, and helps you choose between Code128 and EAN13.

Choosing a Barcode Library in Python

The python-barcode library is a pure-Python solution that supports Code128, EAN13, EAN8, UPC-A, ISBN, and other common symbologies. It has no external dependencies for the core functionality and can render barcodes to SVG or raster images through pluggable writers. Install it with pip:

pip install python-barcode

For standalone barcode images, this library is usually sufficient. If you need to embed barcodes directly inside a PDF or another document, reportlab also includes barcode generation, but python-barcode is the more direct choice when you just need an image file.

Generating a Code128 Barcode

Code128 is a high-density alphanumeric symbology that can encode the full ASCII character set. It is variable length and widely used in logistics and inventory systems.

import barcode from barcode.writer import ImageWriter code128 = barcode.get_barcode_class('code128') code128_instance = code128('ABC-12345', writer=ImageWriter()) code128_instance.save('code128_barcode')

This creates a PNG file named code128_barcode.png in the current directory. The ImageWriter renders the barcode as an image. If you omit the writer, the default SVGWriter produces an SVG file instead.

The string you pass to the code128 constructor is the data to encode. The library automatically adds the required start and stop characters and calculates the checksum. You can encode any ASCII character, including lowercase letters, digits, and punctuation. There is no fixed length, so Code128 works for short product codes and longer serial numbers.

Generating an EAN13 Barcode

EAN13 is a numeric-only symbology used primarily for retail product identification. It encodes 12 data digits plus a computed check digit, for a total of 13 digits.

import barcode from barcode.writer import ImageWriter ean = barcode.get_barcode_class('ean13') ean_instance = ean('5901234123457', writer=ImageWriter()) ean_instance.save('ean13_barcode')

This example uses a valid 13-digit EAN-13 code. If you pass 12 digits, the library calculates the check digit and appends it. If you pass 13 digits, the supplied code is used as a complete EAN-13 number, so make sure the last digit is the correct check digit. Passing a non-numeric string or a length other than 12 or 13 raises a ValueError.

EAN13 is strictly numeric and fixed-length. This makes it a good fit for point-of-sale systems and global trade item numbers (GTINs). The check digit is calculated with a weighted sum algorithm; when you provide 12 digits, the library handles that calculation automatically.

Code128 vs EAN13: Which One to Use

The choice between Code128 and EAN13 depends on your data and the environment where the barcode will be scanned.

CriterionCode128EAN13
Data typeAlphanumeric (full ASCII)Numeric only
LengthVariableFixed (12 data + 1 check digit)
Check digitAutomatic, internalAutomatic, weighted sum
Common useLogistics, internal labelingRetail, consumer goods
Scanner supportUniversal, but not retail-standardRequired for POS in many regions

Use Code128 when you need to encode letters, symbols, or variable-length data, such as serial numbers, asset tags, or internal SKUs. Use EAN13 when the barcode will be scanned at retail checkout and must conform to GTIN standards. For products sold in stores, EAN13 is usually the correct choice.

Output Formats and Customization

The python-barcode library separates barcode generation from rendering through writer classes. The two most common writers are ImageWriter for raster images and SVGWriter for vector graphics. You can control output by passing writer options to save() as a dictionary:

import barcode from barcode.writer import ImageWriter ean = barcode.get_barcode_class('ean13') options = { 'module_width': 0.2, 'module_height': 15.0, 'font_size': 10, 'text_distance': 5.0, 'quiet_zone': 6.5, } ean_instance = ean('5901234123457', writer=ImageWriter()) ean_instance.save('ean13_custom', options=options)

module_width controls the width of the narrowest bar, module_height sets the bar height, and quiet_zone defines the blank margin on each side. For SVG output, use SVGWriter and convert to another format if needed. These options let you match the barcode to label size and printer requirements.

Error Handling and Validation

Barcode generation fails when the input does not meet the symbology's requirements. For EAN13, the library raises a ValueError if the input is not numeric or has an invalid length. For Code128, the main constraint is that the data is ASCII-encodable; most labels use printable ASCII characters.

Wrap generation in a try/except block to handle invalid input gracefully:

try: ean_instance = ean('invalid', writer=ImageWriter()) ean_instance.save('bad_barcode') except ValueError as e: print('Invalid EAN13 data:', e)

Always validate input before calling the library if you are processing user-supplied data. For EAN13, a simple regex check for 12 or 13 digits can prevent most errors. For Code128, ensure the string uses ASCII characters.

Performance and Batch Generation

Generating a single barcode is inexpensive, but batch jobs can reuse a writer object across multiple barcode instances:

writer = ImageWriter() for code in product_codes: ean_instance = ean(code, writer=writer) ean_instance.save(f'barcode_{code}')

Choose the output format that matches your downstream needs. SVG output is vector data and useful when barcodes need to scale; PNG is convenient when a raster image is required.

Common Pitfalls and Edge Cases

One frequent mistake is passing a 13-digit EAN13 string and expecting the library to recalculate the check digit. It does not. If you pass 12 digits, the check digit is computed and appended; if you pass 13 digits, use a complete, valid EAN-13 code.

For Code128, the library handles the subset selection, so you do not need to specify Code128A, Code128B, or Code128C explicitly in the basic API. Non-ASCII text is outside the standard Code128 character set; use ASCII data. Some scanners also require a minimum quiet zone, so adjust the quiet_zone writer option if needed.

Another edge case is file naming. The save() method appends the appropriate extension (.png or .svg) automatically. If you pass a filename with an extension, it will be duplicated. For example, save('barcode.png') creates barcode.png.png. Use a filename without an extension.

Generate Code128 and EAN13 Barcodes with python-barcode | RYUSLOG DEV