treepoem

repository·main·Indexed 41 days ago

https://github.com/adamchainz/treepoem

A Python barcode renderer that wraps the BWIPP (Barcode Writer in Pure PostScript) library and uses Ghostscript to generate images. It supports approximately 100 barcode types, including QRcode, Aztec, PDF417, I25, Code128, and Code39. Version 3.28.0 provides a Python API via `generate_barcode()` and a command-line interface for creating barcodes as PIL Image objects or files.

Tokens
2.9K
Snippets
12
Records
13
Agent score
48%

What's inside treepoem

  1. Explore supported barcode types

    main

    Treepoem provides a barcode_types dictionary containing approximately 100 supported barcode types from BWIPP.

    Each entry is a BarcodeType object containing:

    • type_code: The string value required for the barcode_type argument in generate_barcode().
    • description: A human-readable description of the type.

    Commonly used types include:

    • qrcode (QR Code)
    • azteccode (Aztec Code)
    • pdf417 (PDF417)
    • interleaved2of5 (Interleaved 2 of 5)
    • code128 (Code 128)
    • code39 (Code 39)
  2. Install treepoem and Ghostscript

    main

    To use treepoem, you must install the Python package via pip and ensure the ghostscript command-line tool is installed on your system.

    Supported Python versions: 3.10 to 3.15.

    Ghostscript Installation:

    • Ubuntu/Debian: apt-get install ghostscript
    • macOS: brew install ghostscript
    • Other: Use your distribution's package manager (look for ghostscript).

    You can verify your Ghostscript installation and version using:

    gs --version

    Note: Ghostscript versions 9.22+ may cause image smearing. Version 9.26+ contains fixes for common barcodes, though some smearing may persist.

    python -m pip install treepoem
  3. Use monolithic barcode.ps flavors

    main

    The monolithic barcode.ps file provides Barcode Writer in Pure PostScript (BWIPP) as generic PostScript Level 2 named resources. This single file is designed for easy inclusion in the Prolog section of a PostScript document or for installation into a printer's initial job VM.

    To obtain these flavors:

    • Download prepared tarballs from the BWIPP releases. Filenames typically follow the pattern postscriptbarcode-monolithic or postscriptbarcode-monolithic-package.
    • Build from source using make monolithic or make monolithic_package.
    make monolithic
    # or
    make monolithic_package
  4. Include barcode.ps in a PostScript document Prolog

    main

    To use the monolithic barcode resources in a PostScript file, include the contents of barcode.ps in the Prolog section. You can then access specific barcode resources (like qrcode) using one of the following patterns:

    1. Standard Setup

    Define the resource in the Setup or PageSetup section using its full name, then call it by its short name.

    2. Avoiding Name Conflicts (Aliasing)

    If you need to avoid namespace collisions, map the resource to a local name. This is analogous to from uk.co.terryburton.bwipp import qrcode as foo.

    3. Direct Execution (No Setup)

    For a quick implementation without a setup section or local names, you can find and execute the resource directly in the page description. This technique also reduces the possibility of namespace collision.

    // 1. Standard Setup
    /qrcode dup /uk.co.terryburton.bwipp findresource def
    0 0 moveto (BWIPP) (eclevel=M) qrcode
    
    // 2. Aliasing to avoid conflicts
    /foo /qrcode /uk.co.terryburton.bwipp findresource def
    0 0 moveto (BWIPP1) (eclevel=M) foo
    0 0 moveto (BWIPP2) (eclevel=M) foo
    
    // 3. Direct Execution (No setup section)
    0 0 moveto (BWIPP) (eclevel=M) /qrcode /uk.co.terryburton.bwipp findresource exec
  5. Install barcode.ps to a printer's initial job VM

    main

    You can install the barcode resources into a printer's initial job VM so they remain available between jobs. To do this, send barcode.ps to the printer with the following line added to the very top of the file:

    true () startjob

    Note: Replace the empty parentheses () with the printer's startjob password. These resources will persist between jobs but will be lost if the printer undergoes a power cycle.

    true (YOUR_PASSWORD_HERE) startjob
    // ... rest of barcode.ps content ...
  6. Generate barcodes with generate_barcode()

    main

    The generate_barcode function is the primary API for creating barcodes. It returns a PIL Image object.

    Signature: generate_barcode(barcode_type: str, data: str | bytes, options: dict[str, str | bool] | None=None, *, scale: int = 2) -> Image

    Parameters:

    • barcode_type: The name of the barcode type (e.g., qrcode, code128). Refer to the BWIPP Symbologies Reference for supported types.
    • data: The str or bytes data to embed in the barcode.
    • options: A dictionary of BWIPP-specific options (strings to strings or booleans).
    • scale: Controls output image size. Use 1 for the smallest size; larger values increase size.
    import treepoem
    from PIL import ImageOps
    
    image = treepoem.generate_barcode(
        barcode_type="qrcode",
        data="https://example.com",
    )
    image = ImageOps.expand(image, border=10, fill="white")
    image.convert("1").save("barcode.png")
  7. Use the treepoem CLI

    main

    The treepoem command-line interface allows you to generate barcodes directly from your terminal.

    Example usage: To generate two QR codes with different error correction levels (eclevel):

    treepoem -o barcode1.png -t qrcode "This is a test" eclevel=H
    treepoem -o barcode2.png -t qrcode "^084his is a test" eclevel=L parse

    Use treepoem --help for complete usage instructions.

    treepoem -o barcode1.png -t qrcode "This is a test" eclevel=H
  8. Generate a barcode with `generate_barcode()`

    main

    Use generate_barcode() to create a barcode image. This function wraps the BWIPP (Barcode Writer in Pure PostScript) engine. It requires a barcode_type (a string identifying the symbology), the data to encode (as a string or bytes), and optional configuration options.

    Parameters:

    • barcode_type (str): The identifier for the barcode symbology (e.g., 'code128').
    • data (str | bytes): The content to be encoded in the barcode.
    • options (dict[str, str | bool] | None): A dictionary of BWIPP-specific options. Boolean values in the dictionary are treated as flags (included if True).
    • scale (int, keyword-only): An integer multiplier for the output image resolution. Defaults to 2.

    Returns:

    • PIL.Image.Image: A PIL Image object containing the generated barcode.

    Errors:

    • Raises NotImplementedError if the barcode_type is unsupported.
    • Raises ValueError if scale is less than 1.
    • Raises TreepoemError if Ghostscript is not found or if BWIPP encounters an error during generation.
    from treepoem import generate_barcode
    
    # Example: Generate a Code 128 barcode
    image = generate_barcode('code128', 'Hello World', options={'narrow': '1'})
    image.show()
  9. Reference treepoem CLI arguments and options

    main

    The following arguments are available for the treepoem CLI:

    FlagLong FlagDescription
    -t--typeBarcode type (e.g., qrcode, code128). Defaults to qrcode.
    -f--formatOutput image format. Defaults to file extension, or xbm if outputting to stdout without a filename.
    -o--outputOutput file path. Defaults to stdout.
    -s--scalePositive integer factor for scaling the output image size. Defaults to 2.
    (positional)dataThe raw data to encode in the barcode.
    (positional)optionsA list of BWIPP options in key=value format (e.g., width=1.5). If a key is provided without =, it is treated as a boolean True option.
    # Example of using key=value options
    python -m treepoem --type qrcode "data" module_size=4
    
    # Example of using a boolean option
    python -m treepoem --type qrcode "data" quiet
  10. Reference the supported barcode types

    main

    The barcode_types dictionary contains all supported barcode symbologies available in treepoem. Each entry maps a type_code (string) to a BarcodeType object containing a human-readable description. Use these type_code values when specifying which symbology to generate or decode via the API or CLI.

    from treepoem import barcode_types
    
    # Example: Accessing a specific barcode type
    qr_type = barcode_types['qrcode']
    print(f"Code: {qr_type.type_code}, Description: {qr_type.description}")
    
    # Example: Listing all available type codes
    print(list(barcode_types.keys()))
  11. Use the treepoem CLI to generate barcodes

    main

    You can run treepoem as a standalone command-line tool using python -m treepoem. This allows you to generate various barcode types from data provided via the command line, with options to specify output format, scale, and BWIPP-specific parameters.

    Basic Syntax: python -m treepoem [OPTIONS] DATA [OPTIONS_LIST]

    Key Behaviors:

    • Output Destination: If no --output is specified, the barcode is sent to stdout.
    • Output Format: If outputting to stdout without an explicit --format, the tool defaults to xbm format.
    • Scaling: Use --scale to provide a positive integer factor to increase the output image size.
    # Basic usage: generate a QR code from text
    python -m treepoem "Hello World"
    
    # Generate a specific barcode type with custom BWIPP options and scale
    python -m treepoem --type code128 --scale 4 --format png --output my_barcode.png "12345678" width=1.5
  12. Identify supported barcode types using `barcode_types`

    main

    The barcode_types object is a collection of all supported barcode symbology identifiers available in the current installation. You can use this to validate input or to list available formats.

    from treepoem import barcode_types
    
    print(f"Supported types: {list(barcode_types.keys())}")
    
    # Check if a specific type is supported
    if 'code128' in barcode_types:
        print("Code 128 is supported")