0
# PyQRCode
1
2
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.
3
4
## Package Information
5
6
- **Package Name**: PyQRCode
7
- **Language**: Python
8
- **Installation**: `pip install PyQRCode`
9
- **Optional Dependency**: `pip install pypng` (for PNG support)
10
11
## Core Imports
12
13
```python
14
import pyqrcode
15
```
16
17
Direct class import:
18
19
```python
20
from pyqrcode import QRCode
21
```
22
23
Constants and tables:
24
25
```python
26
import pyqrcode.tables as tables
27
```
28
29
## Basic Usage
30
31
```python
32
import pyqrcode
33
34
# Create a QR code using the factory function (recommended)
35
url_code = pyqrcode.create('http://example.com')
36
37
# Save as SVG (no dependencies required)
38
url_code.svg('example.svg', scale=4)
39
40
# Save as PNG (requires pypng: pip install pypng)
41
url_code.png('example.png', scale=5)
42
43
# Display in terminal
44
print(url_code.terminal())
45
46
# Get text representation
47
print(url_code.text())
48
49
# Direct class instantiation (alternative)
50
number_code = QRCode(123456789012345)
51
number_code.svg('number.svg', scale=3)
52
```
53
54
## Architecture
55
56
PyQRCode follows the QR code standard structure with these key components:
57
58
- **Data Encoding**: Supports four encoding modes (numeric, alphanumeric, binary, kanji) with automatic mode detection
59
- **Error Correction**: Implements Reed-Solomon error correction with four levels (L, M, Q, H) providing 7%, 15%, 25%, or 30% recovery capability
60
- **Version Management**: Handles QR code versions 1-40 (21×21 to 177×177 modules) with automatic size selection based on data length
61
- **Mask Selection**: Generates and evaluates all eight mask patterns using standard penalty rules to optimize readability
62
- **Multi-format Output**: Provides rendering engines for SVG, PNG, EPS, XBM, terminal, and text formats without external dependencies (except pypng for PNG)
63
64
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.
65
66
## Capabilities
67
68
### QR Code Creation
69
70
Factory function for creating QR codes with automatic parameter detection and manual control options.
71
72
```python { .api }
73
def create(content, error='H', version=None, mode=None, encoding=None):
74
"""
75
Create a QR code with the given content.
76
77
Parameters:
78
- content: Data to encode (string, number, bytes)
79
- error: Error correction level ('L', 'M', 'Q', 'H' or float/percentage)
80
- version: QR code version 1-40 (auto-detected if None)
81
- mode: Encoding mode ('numeric', 'alphanumeric', 'binary', 'kanji' or None for auto)
82
- encoding: Character encoding (default: 'iso-8859-1')
83
84
Returns:
85
QRCode instance
86
"""
87
```
88
89
### QR Code Class
90
91
Main class representing a QR code with methods for various output formats.
92
93
```python { .api }
94
class QRCode:
95
def __init__(self, content, error='H', version=None, mode=None, encoding='iso-8859-1'):
96
"""
97
Initialize QR code with given parameters.
98
Same parameters as create() function.
99
"""
100
101
# Instance attributes (read-only)
102
data: bytes # Encoded data
103
error: str # Error correction level
104
version: int # QR code version (1-40)
105
mode: str # Encoding mode
106
encoding: str # Character encoding
107
code: list # 2D array of QR code pattern
108
```
109
110
### SVG Output
111
112
Generate QR codes as Scalable Vector Graphics with extensive customization options.
113
114
```python { .api }
115
def svg(self, file, scale=1, module_color='#000', background=None,
116
quiet_zone=4, xmldecl=True, svgns=True, title=None,
117
svgclass='pyqrcode', lineclass='pyqrline', omithw=False, debug=False):
118
"""
119
Save QR code as SVG document.
120
121
Parameters:
122
- file: File path or writable stream
123
- scale: Scale factor (accepts fractional values)
124
- module_color: SVG color for modules (default: black)
125
- background: SVG color for background (None for transparent)
126
- quiet_zone: Quiet zone width in modules (default: 4)
127
- xmldecl: Include XML declaration (default: True)
128
- svgns: Include SVG namespace (default: True)
129
- title: SVG title element content
130
- svgclass: CSS class for SVG element
131
- lineclass: CSS class for path elements
132
- omithw: Omit height/width, add viewBox instead
133
- debug: Enable debug mode
134
"""
135
```
136
137
### PNG Output
138
139
Generate QR codes as PNG images with color and scaling options.
140
141
```python { .api }
142
def png(self, file, scale=1, module_color=(0, 0, 0, 255),
143
background=(255, 255, 255, 255), quiet_zone=4):
144
"""
145
Save QR code as PNG image (requires pypng).
146
147
Parameters:
148
- file: File path or writable stream
149
- scale: Integer scale factor for module size
150
- module_color: RGBA tuple for module color (default: black)
151
- background: RGBA tuple for background color (default: white)
152
- quiet_zone: Quiet zone width in modules (default: 4)
153
"""
154
155
def png_as_base64_str(self, scale=1, module_color=(0, 0, 0, 255),
156
background=(255, 255, 255, 255), quiet_zone=4):
157
"""
158
Generate PNG as base64 string (requires pypng).
159
160
Parameters: Same as png() method
161
162
Returns:
163
Base64-encoded PNG string suitable for data URLs
164
"""
165
166
def get_png_size(self, scale=1, quiet_zone=4):
167
"""
168
Calculate PNG dimensions in pixels.
169
170
Parameters:
171
- scale: Scale factor
172
- quiet_zone: Quiet zone width in modules
173
174
Returns:
175
Integer representing width/height in pixels (QR codes are square)
176
"""
177
```
178
179
### EPS Output
180
181
Generate QR codes as Encapsulated PostScript documents.
182
183
```python { .api }
184
def eps(self, file, scale=1, module_color=(0, 0, 0), background=None, quiet_zone=4):
185
"""
186
Save QR code as EPS document.
187
188
Parameters:
189
- file: File path or writable stream
190
- scale: Scale factor in points (1/72 inch)
191
- module_color: RGB tuple for modules (0-1 float or 0-255 int)
192
- background: RGB tuple for background (None for transparent)
193
- quiet_zone: Quiet zone width in modules (default: 4)
194
"""
195
```
196
197
### Terminal Output
198
199
Generate QR codes for display in terminal emulators using ANSI escape codes.
200
201
```python { .api }
202
def terminal(self, module_color='default', background='reverse', quiet_zone=4):
203
"""
204
Generate terminal-displayable QR code with ANSI colors.
205
206
Parameters:
207
- module_color: Terminal color name, 'default', or 256-color number (0-256)
208
- background: Terminal color name, 'reverse', or 256-color number (0-256)
209
- quiet_zone: Quiet zone width in modules (default: 4)
210
211
Returns:
212
String with ANSI escape codes for terminal display
213
214
Supported color names:
215
black, red, green, yellow, blue, magenta, cyan, white,
216
light gray, dark gray, light red, light green, light blue,
217
light yellow, light magenta, light cyan
218
"""
219
```
220
221
### Text Output
222
223
Generate plain text representation of QR codes using 1s and 0s.
224
225
```python { .api }
226
def text(self, quiet_zone=4):
227
"""
228
Generate text representation of QR code.
229
230
Parameters:
231
- quiet_zone: Quiet zone width in modules (default: 4)
232
233
Returns:
234
String with '1' for modules and '0' for background
235
"""
236
```
237
238
### XBM Output
239
240
Generate X11 Bitmap format for Tkinter compatibility.
241
242
```python { .api }
243
def xbm(self, scale=1, quiet_zone=4):
244
"""
245
Generate XBM format for Tkinter display.
246
247
Parameters:
248
- scale: Integer scale factor
249
- quiet_zone: Quiet zone width in modules (default: 4)
250
251
Returns:
252
XBM format string suitable for tkinter.BitmapImage
253
"""
254
```
255
256
### Display Functionality
257
258
Display QR codes using the system's default image viewer.
259
260
```python { .api }
261
def show(self, wait=1.2, scale=10, module_color=(0, 0, 0, 255),
262
background=(255, 255, 255, 255), quiet_zone=4):
263
"""
264
Display QR code in default image viewer (creates temporary PNG).
265
266
Parameters:
267
- wait: Seconds to wait before cleanup (default: 1.2)
268
- scale: PNG scale factor
269
- module_color: RGBA tuple for modules
270
- background: RGBA tuple for background
271
- quiet_zone: Quiet zone width in modules
272
"""
273
```
274
275
## Error Correction Levels
276
277
PyQRCode supports four error correction levels with various specification formats:
278
279
```python { .api }
280
# Level specifications (all equivalent):
281
'L' or 'l' or '7%' or 0.7 # 7% correction capability
282
'M' or 'm' or '15%' or 0.15 # 15% correction capability
283
'Q' or 'q' or '25%' or 0.25 # 25% correction capability (most common)
284
'H' or 'h' or '30%' or 0.30 # 30% correction capability (default)
285
```
286
287
Note: The float values are as defined in the source code's error_level table.
288
289
## Encoding Modes
290
291
PyQRCode automatically detects the best encoding mode or allows manual specification:
292
293
- **numeric**: Digits 0-9 only
294
- **alphanumeric**: Limited ASCII character set (uppercase letters, digits, spaces, and symbols: $%*+-./: )
295
- **binary**: Arbitrary byte data (least efficient but most flexible)
296
- **kanji**: Shift-JIS encoded Japanese characters
297
298
## Version Range
299
300
- Supports QR code versions 1-40 (21×21 to 177×177 modules)
301
- Automatic version selection based on content length and error correction level
302
- Manual version specification available for consistency across multiple codes
303
304
## Constants and Tables
305
306
PyQRCode exposes several constants and lookup tables for advanced usage.
307
308
### Mode Constants
309
310
```python { .api }
311
# From pyqrcode.tables.modes
312
modes = {
313
'numeric': 1, # Numeric encoding (0-9)
314
'alphanumeric': 2, # Alphanumeric encoding (limited ASCII)
315
'binary': 4, # Binary/byte encoding
316
'kanji': 8 # Kanji encoding (Shift-JIS)
317
}
318
```
319
320
### Error Correction Level Constants
321
322
```python { .api }
323
# From pyqrcode.tables.error_level
324
# Maps various formats to standard QR error levels
325
# Supports: 'L'/'l', 'M'/'m', 'Q'/'q', 'H'/'h'
326
# Supports: '7%', '15%', '25%', '30%'
327
# Supports: 0.7, 0.15, 0.25, 0.30
328
error_level = {
329
'L': 1, # ~7% error correction
330
'M': 0, # ~15% error correction
331
'Q': 3, # ~25% error correction
332
'H': 2 # ~30% error correction (default)
333
}
334
```
335
336
### Alphanumeric Character Support
337
338
```python { .api }
339
# From pyqrcode.tables.ascii_codes
340
# Characters allowed in alphanumeric mode with their numeric values
341
ascii_codes = {
342
'0': 0, '1': 1, ..., '9': 9, # Digits 0-9
343
'A': 10, 'B': 11, ..., 'Z': 35, # Uppercase A-Z
344
' ': 36, # Space
345
'$': 37, '%': 38, '*': 39, '+': 40, # Symbols
346
'-': 41, '.': 42, '/': 43, ':': 44 # More symbols
347
}
348
```
349
350
### Terminal Color Constants
351
352
```python { .api }
353
# From pyqrcode.tables.term_colors
354
# ANSI color codes for terminal display
355
term_colors = {
356
# Basic colors
357
'black': 30, 'red': 31, 'green': 32, 'yellow': 33,
358
'blue': 34, 'magenta': 35, 'cyan': 36, 'white': 37,
359
360
# Light variants
361
'light red': 91, 'light green': 92, 'light blue': 94,
362
'light yellow': 93, 'light magenta': 95, 'light cyan': 96,
363
364
# Gray variants
365
'light gray': 37, 'dark gray': 90,
366
367
# Special values
368
'default': 39, # Terminal default color
369
'reverse': 'rev' # Reverse video mode
370
}
371
```
372
373
### Version Size Information
374
375
```python { .api }
376
# From pyqrcode.tables.version_size
377
# QR code dimensions in modules for each version (1-40)
378
# version_size[version] returns size in modules
379
# Version 1: 21x21, Version 2: 25x25, ..., Version 40: 177x177
380
```
381
382
## Error Handling
383
384
PyQRCode raises `ValueError` for:
385
- Invalid version numbers (not 1-40)
386
- Invalid error correction levels
387
- Invalid encoding modes
388
- Content that doesn't fit in specified version
389
- Content incompatible with specified encoding mode
390
- Missing pypng dependency for PNG operations