python-barcode

repository·main·Indexed 20 days ago

https://github.com/whynothugo/python-barcode

A lightweight Python library for generating standard barcodes in multiple formats, including SVG and raster images such as PNG, JPEG, BMP, and TIFF. It supports a wide variety of standards including EAN, UPC, Code 39, Code 128, and ISBN. The library provides both a programmatic API and a CLI for barcode creation, with optional Pillow support for image generation.

Tokens
3.5K
Snippets
13
Records
18
Agent score
70%

What's inside python-barcode

  1. Overview of python-barcode

    main
    python-barcode is a Python library designed to provide a simple way to create barcodes. It supports Python versions 3.9 through 3.13. It can generate barcodes in various formats, including SVG (zero dependencies) and image formats like PNG (requires Pillow).
  2. List of supported barcode formats

    main

    The python-barcode library supports a wide variety of barcode standards. You can use specific classes from the corresponding modules to generate these formats. Supported formats include:

    • Codabar: barcode.codabar.CODABAR
    • Code 39: barcode.codex.Code39
    • Code 128: barcode.codex.Code128
    • PZN (PZN7): barcode.codex.PZN
    • EAN-13: barcode.ean.EuropeanArticleNumber13 and barcode.ean.EuropeanArticleNumber13WithGuard
    • EAN-8: barcode.ean.EuropeanArticleNumber8 and barcode.ean.EuropeanArticleNumber8WithGuard
    • EAN-14 / EAN14 (GTIN): barcode.ean.EuropeanArticleNumber14
    • JAN (Japan Article Number): barcode.ean.JapanArticleNumber
    • ISBN-13 (GS1, ISBN): barcode.isxn.InternationalStandardBookNumber13
    • ISBN-10: barcode.isxn.InternationalStandardBookNumber10
    • ISSN: barcode.isxn.InternationalStandardSerialNumber
    • UPC-A / UPCA: barcode.upc.UniversalProductCodeA and barcode.upc.UPCA
    • GS1-128: barcode.codex.Gs1_128
    • ITF: barcode.itf.ITF
  3. Create a custom writer by inheriting from BaseWriter

    main

    You can implement custom rendering logic by inheriting from barcode.writer.BaseWriter. To work correctly, your custom writer must implement the following callbacks within its __init__ method:

    1. initialize(raw_code)
    2. paint_module(xpos, ypos, width, color)
    3. paint_text(xpos, ypos)
    4. finish()

    To use it, instantiate your custom writer and pass it as an argument when creating a barcode instance. When render() is called on the barcode, your implementation's callbacks will be triggered.

  4. Install python-barcode

    main

    You can install python-barcode via PyPI.

    Note on dependencies:

    • SVG generation: No external dependencies required.
    • Image generation (e.g., PNG): Requires the Pillow library to be installed.
    pip install python-barcode
    # If you need to generate PNGs, also install Pillow:
    pip install Pillow
  5. Install python-barcode via pip

    main

    Install the core library using pip:

    pip install python-barcode

    If you need to export barcodes as images (e.g., PNG, JPEG) instead of just SVG, you must install the images extra, which includes the necessary dependencies like Pillow:

    pip install "python-barcode[images]"

    Note: Use quotes around the package name in most shells to prevent issues with square brackets.

  6. Generate SVG barcodes

    main

    To generate SVG barcodes, use a barcode class (like EAN13) and provide an SVGWriter. You can write the output to a file-like object (e.g., BytesIO) or directly to a file.

    Checksums are calculated automatically. For systems like Code 39 where checksums are optional, you can pass add_checksum=False as a keyword argument.

    from io import BytesIO
    from barcode import EAN13
    from barcode.writer import SVGWriter
    
    # Write to a file-like object:
    rv = BytesIO()
    EAN13("100000902922", writer=SVGWriter()).write(rv)
    
    # Or to an actual file:
    with open("somefile.svg", "wb") as f:
        EAN13(str(100000011111), writer=SVGWriter()).write(f)
  7. Save a compressed SVG (SVGZ)

    main

    To output a compressed SVG file, use the SVGWriter and set the compress option to True in the options dictionary passed to the save method.

    import barcode
    
    ean = barcode.get('ean13', '123456789102')
    # Checksum is automatically added
    print(ean.get_fullcode())
    
    # Save standard SVG
    filename = ean.save('ean13')
    print(filename)  # 'ean13.svg'
    
    # Save compressed SVGZ
    options = dict(compress=True)
    filename = ean.save('ean13', options)
    print(filename)  # 'ean13.svgz'
  8. Generate image barcodes (PNG, JPEG, etc.)

    main

    To generate raster images, use ImageWriter. This requires the [images] extra to be installed.

    Note: SVG files are vectorized and scale better than images. Use images only if your target medium does not support SVG.

    from io import BytesIO
    from barcode import EAN13
    from barcode.writer import ImageWriter
    
    # Write to a file-like object:
    rv = BytesIO()
    EAN13(str(100000902922), writer=ImageWriter()).write(rv)
    
    # Or to an actual file:
    with open("somefile.jpeg", "wb") as f:
        EAN13("100000011111", writer=ImageWriter()).write(f)
  9. Use barcode.generate() for quick barcode creation

    main

    The generate() function provides a high-level way to create barcodes without manually instantiating classes. You specify the barcode type, the data, and optionally the writer and output destination.

    from barcode import generate
    from barcode.writer import ImageWriter
    from io import BytesIO
    
    # Generate an SVG file
    name = generate('EAN13', '590123457', output='barcode_svg')
    
    # Generate an image to a file-like object
    fp = BytesIO()
    generate('EAN13', '590123457', writer=ImageWriter(), output=fp)
  10. Use ImageWriter for raster barcodes

    main

    The ImageWriter renders barcodes as images and supports any format compatible with the Pillow library. It supports all common writer options plus specific options for format and resolution.

    Special Options:

    • format: str. The image file format (e.g., 'PNG', 'JPEG', 'BMP'). Default: 'PNG'.
    • dpi: int. Dots per inch used to calculate image size in pixels from mm values. Default: 300.
    import barcode
    
    ean = barcode.get('ean13', '123456789102')
    # Save as a high-resolution JPEG
    ean.save('ean13', options={'format': 'JPEG', 'dpi': 600})
  11. Use barcode.get_barcode_class() to dynamically select barcode types

    main

    You can retrieve a barcode class by its string identifier using barcode.get_barcode_class(). This is useful for selecting types dynamically at runtime.

    Available barcode types can be found in barcode.PROVIDED_BARCODES.

    import barcode
    
    # List available types
    print(barcode.PROVIDED_BARCODES)
    
    # Get a specific class
    EAN = barcode.get_barcode_class('ean13')
    my_ean = EAN('590123457')
    
    # Save to a file (automatically adds extension)
    fullname = my_ean.save('ean13_barcode')