Generating barcodes with Python is straightforward thanks to libraries specifically designed for barcode creation. Below is a detailed guide on how to generate various types of barcodes using Python, including code examples and explanations.
1. Install Required Libraries
Two popular Python libraries for generating barcodes are:
-
python-barcode — for creating standard 1D barcodes (e.g., EAN, UPC, Code 128).
-
Pillow — for image handling (used internally or for customizing output).
-
treepoem — for generating both 1D and 2D barcodes (requires Ghostscript installed).
To install these, run:
You may also need to install Ghostscript on your system for treepoem
to work:
-
Windows: Download from https://ghostscript.com/download/gsdnld.html
-
macOS:
brew install ghostscript
-
Linux: Use your package manager, e.g.,
sudo apt install ghostscript
2. Generate 1D Barcodes with python-barcode
This library supports barcodes like EAN, UPC, Code 128, and more.
Example: Generate a Code 128 Barcode
This saves a file called code128_barcode.png
in the current directory.
3. Generate EAN-13 Barcode
EAN-13 requires exactly 12 numeric digits input; the library computes the 13th checksum digit automatically.
4. Customize Barcode Appearance
You can customize barcode output with options passed to ImageWriter
:
5. Generate QR Codes or 2D Barcodes Using treepoem
treepoem
supports many barcode symbologies including QR, PDF417, DataMatrix.
Example: Generate a QR code:
6. Generate Code 39 Barcode
7. Output Barcode as SVG (Vector Format)
python-barcode
can also output SVGs instead of PNGs:
Note: This works without ImageWriter
.
Summary
-
Use
python-barcode
for easy 1D barcode generation (EAN, UPC, Code128, Code39). -
Use
treepoem
for advanced barcodes including 2D codes like QR, PDF417. -
Customize barcodes with options for size, colors, fonts.
-
Save output as PNG or SVG.
If you want a ready-to-use script for any specific barcode type or integration with other systems, just ask!
Leave a Reply