Barcodes are widely used in retail, logistics, healthcare, and many other industries for quick and reliable data encoding. Generating barcodes programmatically can streamline your workflows, automate inventory management, or add a professional touch to your applications.
In this post, we’ll explore how to generate barcodes in Python using popular libraries. By the end, you’ll be able to create various barcode formats effortlessly.
Prerequisites
Before we begin, ensure you have Python installed on your system. The following libraries are required:
python-barcode
pillow
(for image handling)
You can install these using pip:
pip install python-barcode pillow
Generating Barcodes with python-barcode
The python-barcode
library is a simple and efficient tool for creating different barcode formats like CODE39, EAN13, UPC, and more.
Basic Example: Generate a CODE39 Barcode
import barcode
from barcode.writer import ImageWriter
# Data to encode
data = 'HELLO123'
# Generate barcode
code39 = barcode.get('code39', data, writer=ImageWriter())
# Save as PNG image
filename = code39.save('code39_barcode')
print(f"Barcode saved as {filename}.png")
This script creates a CODE39 barcode for the string 'HELLO123'
and saves it as code39_barcode.png
.
Customizing Barcode Appearance
You can customize the barcode’s appearance by passing options to the save()
method:
options = {
'module_width': 0.2,
'module_height': 15.0,
'font_size': 10,
'text_distance': 5.0,
'background': 'white',
'foreground': 'black',
'write_text': True,
}
code39 = barcode.get('code39', data, writer=ImageWriter())
filename = code39.save('custom_code39', options=options)
Generating Other Barcode Types
python-barcode
supports various formats:
- EAN-13: Common in retail for product codes
- EAN-8
- UPC-A
- Code128: Versatile for alphanumeric data
- Code39
Example: Generate a UPC-A Barcode
upc = barcode.get('upc', '12345678901', writer=ImageWriter())
upc.save('upc_barcode')
Note: Ensure the data conforms to the specific barcode format’s requirements (like length).
Alternative: Using treepoem
for More Formats
If you need more barcode types (like Data Matrix, PDF417, QR Codes), consider using treepoem
, which leverages Ghostscript.
Install:
pip install treepoem
import treepoem
# Generate QR code
qr = treepoem.generate_barcode(
barcode_type='qrcode',
data='https://example.com'
)
# Save image
qr.save('qrcode.png')
Summary
- Use
python-barcode
for common barcode formats like CODE39, EAN13, UPC, and Code128. - Customize appearance with options.
- For more advanced or different barcode types, consider
treepoem
.
Final Thoughts
Generating barcodes programmatically can save time and reduce manual errors. With Python’s rich ecosystem, creating and customizing barcodes is straightforward.
Feel free to experiment with different formats and styles to best suit your project’s needs!
Happy coding!