Custom Barcode Generator Python

👤 Sharing: AI
```python
import barcode
from barcode.writer import ImageWriter

def generate_barcode(data, barcode_type='code128', filename='barcode'):
    """
    Generates a barcode image of the specified type with the given data and saves it to a file.

    Args:
        data: The data to encode in the barcode.
        barcode_type: The type of barcode to generate (e.g., 'code128', 'ean13', 'upca').
                       See the barcode library documentation for supported types.
        filename: The filename (without extension) to save the barcode image to.
    """

    try:
        barcode_class = barcode.get_barcode_class(barcode_type.upper())
    except barcode.errors.BarcodeNotFoundError:
        print(f"Error: Barcode type '{barcode_type}' not found.")
        return

    try:
        barcode_instance = barcode_class(data, writer=ImageWriter())
        fullname = barcode_instance.save(filename)
        print(f"Barcode saved to: {fullname}")

    except barcode.errors.NumberofDigitsError as e:
        print(f"Error: Invalid data for barcode type '{barcode_type}'. {e}")
    except Exception as e:
        print(f"An unexpected error occurred: {e}")


if __name__ == '__main__':
    # Example usage
    data_to_encode = '1234567890'  # Replace with your desired data
    barcode_type = 'code128'  # Choose your barcode type
    output_filename = 'my_barcode'  # Choose your filename (no extension)

    generate_barcode(data_to_encode, barcode_type, output_filename)

    # Example with EAN13 (requires 12 digits)
    # data_to_encode = '123456789012'  # 12 digits for EAN13
    # barcode_type = 'ean13'
    # output_filename = 'my_ean13_barcode'
    # generate_barcode(data_to_encode, barcode_type, output_filename)

    #Example with UPCA (requires 11 digits)
    # data_to_encode = '12345678905' # 11 digits for UPCA
    # barcode_type = 'upca'
    # output_filename = 'my_upca_barcode'
    # generate_barcode(data_to_encode, barcode_type, output_filename)
```
👁️ Viewed: 9

Comments