Barcodes are essential for inventory management, retail, and product tracking. In this blog post, we'll explore how to generate custom EAN-13 barcodes in Python using the barcode library.
Why Use Python for Barcode Generation?
Python provides simple yet powerful libraries to generate barcodes programmatically. This is useful for:
- Automated product labeling
- Inventory management systems
- Retail and e-commerce applications
Step 1: Install Required Libraries
First, install the python-barcode and pillow (for image handling) libraries:
pip install python-barcode pillow
Step 2: Generate a Random Barcode Number
EAN-13 barcodes require a 12-digit number (the 13th digit is a checksum). We can generate a random unique code:
import random def generate_unique_code(): return ''.join([str(random.randint(0, 9)) for _ in range(12)])
Step 3: Define Products and Their Barcodes
Store product names and their corresponding barcode numbers in a dictionary:
products = { "Product 1": generate_unique_code(), "Product 2": generate_unique_code() }Step 4: Configure Barcode Appearance
Customize barcode appearance for better readability:
writer_options = { "module_width": 0.4, # Thicker bars "module_height": 25.0, # Taller bars "font_size": 12, # Larger text "text_distance": 5.0, # Space between barcode and text "quiet_zone": 10.0, # Margin around the barcode "write_text": True # Display the number below }Step 5: Generate and Save Barcodes
Use the EAN13 format to generate and save barcodes as PNG files:
EAN13 = barcode.get_barcode_class('ean13') for product_name, code in products.items(): filename = product_name.lower().replace(" ", "_") barcode_obj = EAN13(code, writer=ImageWriter()) output_path = barcode_obj.save(filename, options=writer_options) print(f"✅ Barcode for {product_name} saved as {output_path}.png")Expected Output
Running the script will generate PNG files for each product:
✅ Barcode for Product 1 saved as product_1.png ✅ Barcode for Product 2 saved as product_2.pngPreview:
Conclusion
With just a few lines of Python, you can generate professional-looking barcodes for your products. This method is scalable, allowing batch generation for large inventories.
Try modifying the writer_options to adjust barcode size, text, and margins to fit your needs!
Happy coding!🚀