or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

index.md
tile.json

tessl/pypi-pyqrcode

A QR code generator written purely in Python with SVG, EPS, PNG and terminal output.

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
pypipkg:pypi/pyqrcode@1.2.x

To install, run

npx @tessl/cli install tessl/pypi-pyqrcode@1.2.0

index.mddocs/

PyQRCode

A QR code generator written purely in Python with SVG, EPS, PNG and terminal output. PyQRCode enables developers to create QR codes with multiple output formats and comprehensive encoding support for numeric, alphanumeric, kanji, and binary data types with configurable error correction levels and QR code versions.

Package Information

  • Package Name: PyQRCode
  • Language: Python
  • Installation: pip install PyQRCode
  • Optional Dependency: pip install pypng (for PNG support)

Core Imports

import pyqrcode

Direct class import:

from pyqrcode import QRCode

Constants and tables:

import pyqrcode.tables as tables

Basic Usage

import pyqrcode

# Create a QR code using the factory function (recommended)
url_code = pyqrcode.create('http://example.com')

# Save as SVG (no dependencies required)
url_code.svg('example.svg', scale=4)

# Save as PNG (requires pypng: pip install pypng)
url_code.png('example.png', scale=5)

# Display in terminal
print(url_code.terminal())

# Get text representation
print(url_code.text())

# Direct class instantiation (alternative)
number_code = QRCode(123456789012345)
number_code.svg('number.svg', scale=3)

Architecture

PyQRCode follows the QR code standard structure with these key components:

  • Data Encoding: Supports four encoding modes (numeric, alphanumeric, binary, kanji) with automatic mode detection
  • Error Correction: Implements Reed-Solomon error correction with four levels (L, M, Q, H) providing 7%, 15%, 25%, or 30% recovery capability
  • Version Management: Handles QR code versions 1-40 (21×21 to 177×177 modules) with automatic size selection based on data length
  • Mask Selection: Generates and evaluates all eight mask patterns using standard penalty rules to optimize readability
  • Multi-format Output: Provides rendering engines for SVG, PNG, EPS, XBM, terminal, and text formats without external dependencies (except pypng for PNG)

The library uses a builder pattern internally where the QRCode class coordinates encoding, error correction, and masking, then delegates to format-specific renderers for output generation.

Capabilities

QR Code Creation

Factory function for creating QR codes with automatic parameter detection and manual control options.

def create(content, error='H', version=None, mode=None, encoding=None):
    """
    Create a QR code with the given content.
    
    Parameters:
    - content: Data to encode (string, number, bytes)
    - error: Error correction level ('L', 'M', 'Q', 'H' or float/percentage)
    - version: QR code version 1-40 (auto-detected if None)
    - mode: Encoding mode ('numeric', 'alphanumeric', 'binary', 'kanji' or None for auto)
    - encoding: Character encoding (default: 'iso-8859-1')
    
    Returns:
    QRCode instance
    """

QR Code Class

Main class representing a QR code with methods for various output formats.

class QRCode:
    def __init__(self, content, error='H', version=None, mode=None, encoding='iso-8859-1'):
        """
        Initialize QR code with given parameters.
        Same parameters as create() function.
        """
    
    # Instance attributes (read-only)
    data: bytes  # Encoded data
    error: str   # Error correction level
    version: int # QR code version (1-40) 
    mode: str    # Encoding mode
    encoding: str # Character encoding
    code: list   # 2D array of QR code pattern

SVG Output

Generate QR codes as Scalable Vector Graphics with extensive customization options.

def svg(self, file, scale=1, module_color='#000', background=None, 
        quiet_zone=4, xmldecl=True, svgns=True, title=None, 
        svgclass='pyqrcode', lineclass='pyqrline', omithw=False, debug=False):
    """
    Save QR code as SVG document.
    
    Parameters:
    - file: File path or writable stream
    - scale: Scale factor (accepts fractional values)
    - module_color: SVG color for modules (default: black)
    - background: SVG color for background (None for transparent)
    - quiet_zone: Quiet zone width in modules (default: 4)
    - xmldecl: Include XML declaration (default: True)
    - svgns: Include SVG namespace (default: True)
    - title: SVG title element content
    - svgclass: CSS class for SVG element
    - lineclass: CSS class for path elements
    - omithw: Omit height/width, add viewBox instead
    - debug: Enable debug mode
    """

PNG Output

Generate QR codes as PNG images with color and scaling options.

def png(self, file, scale=1, module_color=(0, 0, 0, 255), 
        background=(255, 255, 255, 255), quiet_zone=4):
    """
    Save QR code as PNG image (requires pypng).
    
    Parameters:
    - file: File path or writable stream
    - scale: Integer scale factor for module size
    - module_color: RGBA tuple for module color (default: black)
    - background: RGBA tuple for background color (default: white)
    - quiet_zone: Quiet zone width in modules (default: 4)
    """

def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255),
                      background=(255, 255, 255, 255), quiet_zone=4):
    """
    Generate PNG as base64 string (requires pypng).
    
    Parameters: Same as png() method
    
    Returns:
    Base64-encoded PNG string suitable for data URLs
    """

def get_png_size(self, scale=1, quiet_zone=4):
    """
    Calculate PNG dimensions in pixels.
    
    Parameters:
    - scale: Scale factor
    - quiet_zone: Quiet zone width in modules
    
    Returns:
    Integer representing width/height in pixels (QR codes are square)
    """

EPS Output

Generate QR codes as Encapsulated PostScript documents.

def eps(self, file, scale=1, module_color=(0, 0, 0), background=None, quiet_zone=4):
    """
    Save QR code as EPS document.
    
    Parameters:
    - file: File path or writable stream
    - scale: Scale factor in points (1/72 inch)
    - module_color: RGB tuple for modules (0-1 float or 0-255 int)
    - background: RGB tuple for background (None for transparent)
    - quiet_zone: Quiet zone width in modules (default: 4)
    """

Terminal Output

Generate QR codes for display in terminal emulators using ANSI escape codes.

def terminal(self, module_color='default', background='reverse', quiet_zone=4):
    """
    Generate terminal-displayable QR code with ANSI colors.
    
    Parameters:
    - module_color: Terminal color name, 'default', or 256-color number (0-256)
    - background: Terminal color name, 'reverse', or 256-color number (0-256)
    - quiet_zone: Quiet zone width in modules (default: 4)
    
    Returns:
    String with ANSI escape codes for terminal display
    
    Supported color names:
    black, red, green, yellow, blue, magenta, cyan, white,
    light gray, dark gray, light red, light green, light blue,
    light yellow, light magenta, light cyan
    """

Text Output

Generate plain text representation of QR codes using 1s and 0s.

def text(self, quiet_zone=4):
    """
    Generate text representation of QR code.
    
    Parameters:
    - quiet_zone: Quiet zone width in modules (default: 4)
    
    Returns:
    String with '1' for modules and '0' for background
    """

XBM Output

Generate X11 Bitmap format for Tkinter compatibility.

def xbm(self, scale=1, quiet_zone=4):
    """
    Generate XBM format for Tkinter display.
    
    Parameters:
    - scale: Integer scale factor
    - quiet_zone: Quiet zone width in modules (default: 4)
    
    Returns:
    XBM format string suitable for tkinter.BitmapImage
    """

Display Functionality

Display QR codes using the system's default image viewer.

def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
         background=(255, 255, 255, 255), quiet_zone=4):
    """
    Display QR code in default image viewer (creates temporary PNG).
    
    Parameters:
    - wait: Seconds to wait before cleanup (default: 1.2)
    - scale: PNG scale factor
    - module_color: RGBA tuple for modules
    - background: RGBA tuple for background
    - quiet_zone: Quiet zone width in modules
    """

Error Correction Levels

PyQRCode supports four error correction levels with various specification formats:

# Level specifications (all equivalent):
'L' or 'l' or '7%' or 0.7    # 7% correction capability
'M' or 'm' or '15%' or 0.15  # 15% correction capability
'Q' or 'q' or '25%' or 0.25  # 25% correction capability (most common)
'H' or 'h' or '30%' or 0.30  # 30% correction capability (default)

Note: The float values are as defined in the source code's error_level table.

Encoding Modes

PyQRCode automatically detects the best encoding mode or allows manual specification:

  • numeric: Digits 0-9 only
  • alphanumeric: Limited ASCII character set (uppercase letters, digits, spaces, and symbols: $%*+-./: )
  • binary: Arbitrary byte data (least efficient but most flexible)
  • kanji: Shift-JIS encoded Japanese characters

Version Range

  • Supports QR code versions 1-40 (21×21 to 177×177 modules)
  • Automatic version selection based on content length and error correction level
  • Manual version specification available for consistency across multiple codes

Constants and Tables

PyQRCode exposes several constants and lookup tables for advanced usage.

Mode Constants

# From pyqrcode.tables.modes
modes = {
    'numeric': 1,       # Numeric encoding (0-9)
    'alphanumeric': 2,  # Alphanumeric encoding (limited ASCII)
    'binary': 4,        # Binary/byte encoding
    'kanji': 8          # Kanji encoding (Shift-JIS)
}

Error Correction Level Constants

# From pyqrcode.tables.error_level
# Maps various formats to standard QR error levels
# Supports: 'L'/'l', 'M'/'m', 'Q'/'q', 'H'/'h'
# Supports: '7%', '15%', '25%', '30%'
# Supports: 0.7, 0.15, 0.25, 0.30
error_level = {
    'L': 1,    # ~7% error correction
    'M': 0,    # ~15% error correction  
    'Q': 3,    # ~25% error correction
    'H': 2     # ~30% error correction (default)
}

Alphanumeric Character Support

# From pyqrcode.tables.ascii_codes
# Characters allowed in alphanumeric mode with their numeric values
ascii_codes = {
    '0': 0, '1': 1, ..., '9': 9,           # Digits 0-9
    'A': 10, 'B': 11, ..., 'Z': 35,       # Uppercase A-Z
    ' ': 36,                               # Space
    '$': 37, '%': 38, '*': 39, '+': 40,   # Symbols
    '-': 41, '.': 42, '/': 43, ':': 44    # More symbols
}

Terminal Color Constants

# From pyqrcode.tables.term_colors
# ANSI color codes for terminal display
term_colors = {
    # Basic colors
    'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
    'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37,
    
    # Light variants  
    'light red': 91, 'light green': 92, 'light blue': 94,
    'light yellow': 93, 'light magenta': 95, 'light cyan': 96,
    
    # Gray variants
    'light gray': 37, 'dark gray': 90,
    
    # Special values
    'default': 39,     # Terminal default color
    'reverse': 'rev'   # Reverse video mode
}

Version Size Information

# From pyqrcode.tables.version_size
# QR code dimensions in modules for each version (1-40)
# version_size[version] returns size in modules
# Version 1: 21x21, Version 2: 25x25, ..., Version 40: 177x177

Error Handling

PyQRCode raises ValueError for:

  • Invalid version numbers (not 1-40)
  • Invalid error correction levels
  • Invalid encoding modes
  • Content that doesn't fit in specified version
  • Content incompatible with specified encoding mode
  • Missing pypng dependency for PNG operations