python-barcode

0.16.1 · active · verified Sat Apr 11

python-barcode provides a simple way to create standard barcodes in Python. It requires no external dependencies for generating SVG files. For outputting image formats like PNGs, the optional Pillow library is needed. The current version is 0.16.1, supporting Python 3.9 up to 3.13. The library maintains an active development status with regular updates addressing Python compatibility and bug fixes.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates generating an EAN13 barcode as an SVG file and a Code128 barcode as a PNG image. The PNG generation specifically highlights the dependency on Pillow and shows how to handle potential `ImportError`. It includes both direct file writing and in-memory byte stream handling for images.

import os
from io import BytesIO
from barcode import EAN13, Code128
from barcode.writer import SVGWriter, ImageWriter

# Example 1: Generate EAN13 as SVG
number_ean13 = '590123412345' # 12 digits, 13th (checksum) is calculated
ean = EAN13(number_ean13, writer=SVGWriter())
with open('ean13_barcode.svg', 'wb') as f:
    ean.write(f)
print('Generated ean13_barcode.svg')

# Example 2: Generate Code128 as PNG (requires Pillow)
try:
    # Use a dummy number for Code128, it supports alphanumeric data
    code128_data = 'MY-PRODUCT-ABC-123'
    code = Code128(code128_data, writer=ImageWriter())
    # To write to a file directly, ensure the output path is writable
    # code.write(open('code128_barcode.png', 'wb'))

    # Or, to an in-memory byte stream, then save
    # This pattern is good for web apps or if you don't want to save to disk immediately
    fp = BytesIO()
    code.write(fp)

    # Simulate saving from BytesIO if Pillow is available
    from PIL import Image
    fp.seek(0) # Rewind to the beginning of the stream
    img = Image.open(fp)
    img.save('code128_barcode.png')
    print('Generated code128_barcode.png (requires Pillow)')

except ImportError:
    print("Pillow not installed. Skipping PNG generation. Install with: pip install \"python-barcode[images]\".")
except Exception as e:
    print(f"Error generating Code128 PNG: {e}")

view raw JSON →