Linux

How To Generate Barcode using Python

Generate Barcode using Python

Barcodes are essential in many industries, from retail to logistics, providing a fast and efficient way to encode data for machine reading. Whether you’re managing inventory, creating product labels, or developing a ticketing system, generating barcodes can be a critical part of your workflow. In this comprehensive guide, you’ll learn how to generate barcodes using Python, one of the most versatile programming languages available today.

Understanding Different Types of Barcodes

Before diving into the technical steps of generating barcodes in Python, it’s important to understand the different types of barcodes and their applications. Barcodes generally fall into two categories: 1D (linear) and 2D.

1D Barcodes vs. 2D Barcodes

1D Barcodes, also known as linear barcodes, consist of vertical lines that represent data. Common examples include:

  • EAN-13: Used globally for retail products.
  • UPC-A: Common in North American retail.
  • Code 39: Frequently used in logistics and inventory management.
  • Code 128: Known for its ability to encode alphanumeric data efficiently.

2D Barcodes, on the other hand, store data in both horizontal and vertical dimensions. Examples include:

  • QR Code: Popular for encoding URLs and other data types.
  • Data Matrix: Used in industrial applications due to its compact size.

The choice between 1D and 2D barcodes depends on your specific use case. For instance, if you’re working with retail products, EAN-13 or UPC-A might be ideal. If you need to encode more data in a smaller space, a QR code or Data Matrix could be more suitable.

Common Barcode Formats Supported by Python Libraries

The most popular Python library for barcode generation is python-barcode. It supports several formats commonly used across industries:

  • EAN-13
  • UPC-A
  • Code 39
  • Code 128
  • ISBN (International Standard Book Number)
  • ISSN (International Standard Serial Number)

Setting Up the Environment for Barcode Generation in Python

The first step to generating barcodes is setting up your environment by installing the necessary Python libraries. You’ll need two main libraries: python-barcode, which handles the barcode generation itself, and Pillow, which is required if you want to save your barcodes as image files like PNG or JPEG.

Installing Required Libraries

You can install both libraries using pip:

pip install python-barcode pillow

This command installs both the barcode generation library and Pillow for image processing. Once installed, you’re ready to start generating barcodes.

Verifying Installation

You can verify that the installation was successful by importing the libraries in a Python script:

import barcode
from PIL import Image
print("Libraries installed successfully!")

If no errors occur when running this script, you’re good to go!

Generating Barcodes Using the python-barcode Library

The python-barcode library makes it easy to generate various types of barcodes with just a few lines of code. Let’s walk through an example of generating an EAN-13 barcode.

Basic Example: Generating an EAN-13 Barcode

The following code shows how to generate an EAN-13 barcode and save it as an image file:

from barcode import EAN13
from barcode.writer import ImageWriter

# Define the number to be encoded in the barcode
number = '5901234123457'

# Generate the barcode
my_code = EAN13(number, writer=ImageWriter())

# Save the barcode as an image file
my_code.save('ean13_barcode_image')

This script generates an EAN-13 barcode from the number provided and saves it as a PNG image file named “ean13_barcode_image.png”. The key components here are:

  • The EAN13() class for generating EAN-13 barcodes.
  • The use of ImageWriter(), which allows saving the barcode as an image file rather than just as SVG (the default format).

Generating Other Barcode Types

You can easily generate other types of barcodes by changing the class used. For example, to generate a Code128 barcode:

from barcode import Code128

# Generate Code128 Barcode
barcode_code128 = Code128('123456789012')
barcode_code128.save('code128_barcode_image')

This code will create a Code128 barcode from the provided string and save it as an image file.

Saving Barcodes in Different Formats (SVG vs PNG)

The default format for saving barcodes is SVG (Scalable Vector Graphics), but you can also save them as PNG or JPEG images using ImageWriter. Here’s how you can save a barcode in both formats:

# Saving as SVG (default)
my_code.save('barcode.svg')

# Saving as PNG using ImageWriter()
my_code.save('barcode.png')

This flexibility allows you to choose between vector-based images (SVG) or raster images (PNG/JPEG), depending on your needs.

Customizing Barcodes in Python

The python-barcode library provides several options for customizing your barcodes’ appearance. You can adjust parameters such as font size, module height (the height of each individual line in the barcode), quiet zone (the margin around the barcode), and more.

Customizing Appearance with Options

You can pass customization options when saving your barcode. Here’s an example of how to customize font size and module height:

options = {
   'font_size': 10,
   'module_height': 15,
   'quiet_zone': 1,
}

barcode_custom = EAN13('5901234123457', writer=ImageWriter())
barcode_custom.save('custom_barcode', options=options)

This code generates a customized EAN-13 barcode with a smaller font size and taller bars than usual.

Add Text Labels to Barcodes

You can also add custom text labels below your barcodes. This is useful when you want additional information displayed alongside the encoded data.

Adjusting Image Size and Resolution

If you need higher resolution images for printing purposes or specific dimensions for integration into documents or websites, you can modify the image size parameters directly within Pillow’s ImageWriter settings.

Advanced Features and Use Cases

Generating Multiple Barcodes Programmatically

If you need to generate multiple barcodes at once—perhaps from a list of product codes—you can use a loop like this:

barcodes = ['5901234123457', '123456789012', '987654321098']

for i, code_number in enumerate(barcodes):
   code = EAN13(code_number, writer=ImageWriter())
   code.save(f'barcode_{i}') # Saves each with unique filenames: 'barcode_0', 'barcode_1', etc.

This script will generate three different EAN-13 barcodes based on the list of numbers provided.

Dynamically Generating Barcodes from Databases or CSV Files

You can also generate barcodes dynamically by pulling data from external sources such as databases or CSV files. This is particularly useful if you’re working with large datasets like product inventories or shipping records.

VPS Manage Service Offer
If you don’t have time to do all of this stuff, or if this is not your area of expertise, we offer a service to do “VPS Manage Service Offer”, starting from $10 (Paypal payment). Please contact us to get the best deal!

r00t

r00t is an experienced Linux enthusiast and technical writer with a passion for open-source software. With years of hands-on experience in various Linux distributions, r00t has developed a deep understanding of the Linux ecosystem and its powerful tools. He holds certifications in SCE and has contributed to several open-source projects. r00t is dedicated to sharing her knowledge and expertise through well-researched and informative articles, helping others navigate the world of Linux with confidence.
Back to top button