Back to Blog
Python

Generate Code128 and EAN13 Barcodes in Python

python barcode generate code128 and ean13: Learn how to generate Code128 and EAN13 barcodes in Python using the python-barcode library, including code examples, output...

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

python barcode generate code128 and ean13 requires a clear understanding of the core syntax, runtime behavior, and practical implementation patterns demonstrated in the examples below.

When you need to generate barcodes in Python, two symbologies come up repeatedly: Code128 and EAN13. Both are supported by the python-barcode library, but they serve different purposes and have different constraints. This article shows how to generate both, what output options matter, and how to choose between them.

Choosing a Barcode Library in Python

The python-barcode library is a pure-Python solution that supports a wide range of symbologies, including Code128, EAN13, EAN8, UPC-A, and ISBN. It is lightweight, has no external dependencies for the core functionality, and can render barcodes to PNG, SVG, and other formats via pluggable writers. Install it with pip:

pip install python-barcode

For most applications, this library is sufficient. If you need to embed barcodes inside PDFs or complex documents, you might also consider reportlab, which includes barcode generation as part of its PDF toolkit. However, python-barcode is the most direct choice when you simply need a standalone barcode image.

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. The python-barcode library makes generating a Code128 barcode straightforward:

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 is responsible for rendering 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 calculates the required checksum and adds the start/stop characters. You can encode any ASCII character, including lowercase letters, digits, and punctuation. There is no fixed length, so you can use Code128 for short product codes or longer serial numbers.

Generating an EAN13 Barcode

EAN13 is a numeric-only symbology used primarily for retail product identification. It encodes 12 digits plus a computed check digit, for a total of 13 digits. In python-barcode, you provide the 12 data digits and the library calculates the check digit for you:

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

Here, '5901234123457' is a 13-digit string. If you pass 13 digits, the library treats the last digit as the check digit and validates it. If you pass 12 digits, it calculates the check digit and appends it. 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 ideal for point-of-sale systems and global trade item numbers (GTINs). The check digit is calculated using a weighted sum algorithm, and the library handles that 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. The following table summarizes the key differences:

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. If you are generating barcodes for products sold in stores, EAN13 is almost always the correct choice.

Output Formats and Customization

The python-barcode library separates the barcode generation from the rendering via writer classes. The two most common writers are ImageWriter (PNG, JPEG, etc.) and SVGWriter (vector graphics). You can control the output through writer options passed as a dictionary:

from barcode.writer import ImageWriter 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)

The module_width controls the width of the narrowest bar, module_height sets the overall height, and quiet_zone defines the blank margin on each side. For SVG output, you can use SVGWriter and then convert to other formats if needed. These options let you match the barcode to your 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 must be encodable in the ASCII range; most strings work, but certain control characters may cause issues.

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(f"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 contains only printable ASCII characters.

Performance and Batch Generation

Generating a single barcode is inexpensive, but if you need to create thousands of barcodes, consider a few practical points. The library creates a new writer instance for each barcode unless you reuse it. You can reuse a writer object across multiple barcode instances to reduce overhead:

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

SVG output is generally smaller and faster to generate than PNG, which matters when storing or transmitting many barcodes. If you need raster images, consider generating SVG first and converting only when necessary. The generation process itself is CPU-bound but trivial for modern hardware; the bottleneck is usually file I/O, so writing to memory or using an in-memory buffer can help in high-throughput scenarios.

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 validate the existing check digit, so if you have a correct 13-digit code, it works fine. If you pass 12 digits, it computes the check digit and appends it. If you pass a string with letters or symbols, it raises an error.

For Code128, the library automatically selects the most efficient subset (A, B, or C) based on the data. However, if your data contains characters outside the standard ASCII range, you may need to handle encoding manually. Also, be aware that some barcode scanners expect a specific quiet zone; the quiet_zone option in the writer can be adjusted to meet that requirement.

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 or override the extension in the writer options.

python barcode generate code128 and ean13: Practical Usage a | RYUSLOG DEV