Users Pricing

blog

Home Blogs How to Generate QR Codes and Barcodes in Python – MindStick
How to Generate QR Codes and Barcodes in Python

How to Generate QR Codes and Barcodes in Python

Rishabh Thakur 39 19 Nov 2026

QR codes and barcodes are everywhere in Indian business: UPI payment QR codes at every shop counter, barcodes on invoices and courier labels, QR codes on product packaging and tickets.

Generating them yourself is easy in Python, and useful when you want them on invoices, labels or reports created by your own systems. This guide covers website QR codes, UPI payment QR codes, standard barcodes and a simple printable product label.

Install the libraries

pip install qrcode[pil] python-barcode pillow
  • qrcode creates QR codes.
  • python-barcode creates linear barcodes like Code 128 and EAN-13.
  • Pillow handles images, so we can combine them into labels.

The complete script

import qrcode
from qrcode.constants import ERROR_CORRECT_M
import barcode
from barcode.writer import ImageWriter
from PIL import Image, ImageDraw


def make_qr(data: str, filename: str, bosize: int = 10):
    qr = qrcode.QRCode(error_correction=ERROR_CORRECT_M, bosize=bosize, border=4)
    qr.add_data(data)
    qr.make(fit=True)  # choose the smallest version that fits the data
    img = qr.make_image(fill_color="black", back_color="white")
    img.save(filename)
    return filename


def make_upi_qr(upi_id: str, name: str, amount: float, note: str, filename: str):
    # Standard UPI deep link; any UPI app can scan it
    from urllib.parse import quote
    link = (f"upi://pay?pa={quote(upi_id, safe="@")}&pn={quote(name)}"
            f"&am={amount:.2f}&cu=INR&tn={quote(note)}")
    return make_qr(link, filename)


def make_barcode(code: str, filename_stem: str, kind: str = "code128"):
    cls = barcode.get_barcode_class(kind)
    return cls(code, writer=ImageWriter()).save(filename_stem)  # adds .png


def make_label(product: str, sku: str, price: str, filename: str):
    """A simple 600x300 product label with a barcode and a QR code."""
    bar_file = make_barcode(sku, "tmp_bar")
    qr_file = make_qr(f"https://example.com/p/{sku}", "tmp_qr.png", bosize=4)

    label = Image.new("RGB", (600, 300), "white")
    draw = ImageDraw.Draw(label)
    draw.text((20, 20), product, fill="black")
    draw.text((20, 45), f"MRP {price}", fill="black")
    label.paste(Image.open(bar_file).resize((380, 160)), (10, 120))
    label.paste(Image.open(qr_file).resize((170, 170)), (410, 110))
    label.save(filename)
    return filename


if __name__ == "__main__":
    make_qr("https://www.mindstick.com", "website_qr.png")
    make_upi_qr("yourshop@okbank", "Your Shop", 499.00, "Invoice INV-1042", "upi_qr.png")
    print(make_barcode("INV-2027-001042", "invoice_barcode"))
    print(make_barcode("890123456789", "product_ean", kind="ean13"))
    print(make_label("Steel Water Bottle 1L", "SKU-10442", "Rs 649", "label.png"))

Running it creates five image files: website_qr.png, upi_qr.png, invoice_barcode.png, product_ean.png and label.png. We checked both QR codes by decoding them with OpenCV’s QR detector, and they returned exactly the website URL and the UPI link we encoded.

QR codes explained

The basics

qr = qrcode.QRCode(error_correction=ERROR_CORRECT_M, bosize=10, border=4)
qr.add_data(data)
qr.make(fit=True)
  • bosize: how many pixels each small square (“module”) is. Bigger means a larger image.
  • border: the quiet zone around the code, in modules. The QR standard asks for at least 4. Don’t trim it; scanners need that white margin.
  • fit=True: automatically picks the smallest QR version that fits your data.

Error correction

QR codes include redundant data so they still scan when partly damaged or covered:

LevelApproximate recoveryUse when
Labout 7%Clean screens, maximum data
Mabout 15%Good default
Qabout 25%Printed labels that might get scuffed
Habout 30%Logo placed in the middle, harsh conditions

Higher levels make the code denser. If you put a logo in the centre of a QR code, use level H and keep the logo small, then test scanning with several phones.

Keep the data short

More data means more modules, and a denser code that’s harder to scan, especially when printed small. Use short URLs, and put details on a web page the QR code links to rather than inside the code itself.

UPI payment QR codes

UPI apps understand a standard deep link format:

upi://pay?pa=yourshop@okbank&pn=Your%20Shop&am=499.00&cu=INR&tn=Invoice%20INV-1042
ParameterMeaning
paPayee UPI ID (VPA)
pnPayee name
amAmount (optional; leave out to let the payer enter it)
cuCurrency, INR
tnTransaction note, such as an invoice number

The script URL-encodes the name and note (spaces become %20) but keeps the @ in the UPI ID as-is.

Important caveats:

  • A QR code generated like this is a static payment request. It doesn’t confirm payment. You must check your bank statement, or use a payment gateway, to know the money actually arrived.
  • For businesses collecting many payments, a payment gateway or your bank’s merchant QR is better: it gives dynamic QR codes per invoice, automatic confirmation via webhooks, and easier reconciliation.
  • Always test with a small real payment from a couple of different UPI apps before printing QR codes on invoices.

Barcodes explained

cls = barcode.get_barcode_class("code128")
cls("INV-2027-001042", writer=ImageWriter()).save("invoice_barcode")

Which barcode type should you use?

TypeCharactersTypical use
Code 128Letters, numbers, symbolsInvoices, internal labels, courier and warehouse labels
EAN-1312 digits + check digitRetail products sold in stores
UPC-A11 digits + check digitRetail products (mainly North America)
Code 39Uppercase letters, numbers, a few symbolsOlder industrial and inventory systems

For internal use, Code 128 is the usual choice: compact and supports letters.

For EAN-13, python-barcode calculates the check digit automatically from the first 12 digits. But for products sold in retail stores, you can’t just invent numbers. Retail barcodes must come from GS1, the organisation that issues official product codes (GS1 India in India). Made-up EAN numbers may clash with real products.

ImageWriter saves PNG files. Without it, python-barcode saves SVG, which is great for print-quality output because it scales without blurring.

Building a printable label

The make_label function creates a simple 600 × 300 pixel label with product name, price, a barcode and a QR code linking to the product page. For real labels:

  • Use a TrueType font with ImageFont.truetype("arial.ttf", 28) for readable text. The default bitmap font is tiny.
  • Design at print resolution. For a 50 × 25 mm label at 300 DPI, that’s about 590 × 295 pixels, very close to our example.
  • For thermal label printers, check the printer’s supported resolution (often 203 or 300 DPI) and size your image to match exactly to avoid blurry scaling.
  • For sheets of labels, generate a PDF with ReportLab, placing each label image at the right position on A4 label sheets.

Making codes scan reliably

  • Size: As a rough guide, keep printed QR codes at least about 2 cm wide for close-range scanning, larger for scanning from a distance.
  • Contrast: Dark code on a light background. Inverted colours and low contrast cause failures.
  • Quiet zones: Leave white space around both QR codes and barcodes.
  • Don’t stretch: Resizing barcodes unevenly can make them unreadable. Scale proportionally, or regenerate at the target size.
  • Test on real devices: several phones, a cheap one included, and your actual barcode scanners, under normal lighting.

Reading codes, too

To decode QR codes in Python, for example to verify generated images automatically, OpenCV works well:

import cv2

data, _, _ = cv2.QRCodeDetector().detectAndDecode(cv2.imread("upi_qr.png"))
print(data)

For linear barcodes, libraries like pyzbar (which needs the zbar system library) are common.

Ideas for using this

  • add a UPI QR code to every PDF invoice, with the invoice number in the note
  • print Code 128 barcodes on job cards and dispatch slips for quick scanning
  • add QR codes to certificates linking to an online verification page
  • put QR codes on product packaging linking to manuals and warranty registration
  • generate event passes with a unique QR code per attendee

Quick summary

With qrcode and python-barcode, generating QR codes and barcodes takes a few lines of Python. Choose a sensible error correction level, keep QR data short, use Code 128 for internal labels and official GS1 numbers for retail products, and treat UPI QR codes as payment requests that still need confirmation.

Most importantly, test printed codes with real scanners before you print a thousand labels.


Rishabh Thakur

Technology Officer at Infosys

Hi, I am Rishabh. I work as a Technology Officer at Infosys and my work is mostly about IT governance, vendor management and technology planning. Before this I spent 2 years at Hexaware Technologies. I studied BCA from Patna University and MCA at the same institute. I am originally from Patna, Bihar. Weekends are for cooking.


Markdown for AI

A clean, structured version of this page for AI assistants and LLMs.

Open .md