> For the complete documentation index, see [llms.txt](https://infinitode-docs.gitbook.io/documentation/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://infinitode-docs.gitbook.io/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-api-functions.md).

# qrforge API & Functions

Full API reference for qrforge: the QR and Artwork classes, shortcut functions, verification helpers, the low-level encoder and exceptions.

**Available classes:** [`QR`](#qr) (alias `QRCode`), [`Artwork`](#artwork), `Style`, `Color`, `Gradient`, `SolidFill`, `Pixmap`, `QRMatrix`, `Shape`, `Shader`.

**Available functions:** [`make`](#make), [`save`](#save), [`svg`](#svg), [`png`](#png), [`terminal`](#terminal), [`preset`](#preset), [`shape`](/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-shapes-and-shaders.md#custom-shapes), [`register_shape`](/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-shapes-and-shaders.md#shape-registry), [`shader`](/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-shapes-and-shaders.md#custom-shaders), [`expression`](/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-shapes-and-shaders.md#expression-shaders), [`build_matrix`](#low-level-encoding), [`decode`](#verification).

**Available exceptions:** [`QRForgeError`](#exceptions), [`DataTooLong`](#exceptions), [`StyleError`](#exceptions), [`UnsupportedFeature`](#exceptions).

***

## QR

`qrforge.QR` (aliased as `qrforge.QRCode`) holds the payload, the encoding options and the rendering style.

```
QR(data, *, ec="M", version=None, mask=None, mode="auto", style=None, **style_options)
```

* `data` (`str`, `bytes` or anything stringifiable): the payload to encode. Non-ASCII text is UTF-8 encoded; `bytes` are used verbatim.
* `ec`: error correction level — `"L"`, `"M"`, `"Q"` or `"H"` (case insensitive), default `"M"`.
* `version`: force a QR version (1–40). Chosen automatically when `None`.
* `mask`: force a mask pattern (0–7). Chosen automatically when `None`.
* `mode`: `"auto"` (default), `"numeric"`, `"alnum"` or `"byte"`.
* `style`: preset name, `Style` object or dict.
* `**style_options`: any [Style option](/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-style-options.md) as a keyword argument.

```python
import qrforge

qr = qrforge.QR("https://example.com", ec="h",
                module_shape="dot", fg=["#ff0080", "#7928ca"])
```

### Properties

| Member      | Type       | Description                                                 |
| ----------- | ---------- | ----------------------------------------------------------- |
| `qr.matrix` | `QRMatrix` | The encoded matrix, built on first use.                     |
| `qr.size`   | `int`      | Side length of the symbol in modules.                       |
| `qr.style`  | `Style`    | The current style object (a plain attribute, not a method). |

### Methods

| Method                                           | Returns           | Description                                                                                                    |
| ------------------------------------------------ | ----------------- | -------------------------------------------------------------------------------------------------------------- |
| `qr.encode(data=None, **options)`                | `QR`              | Change the payload and/or the `ec`, `version`, `mask`, `mode` options, then drop the cached matrix. Chainable. |
| `qr.styled(style=None, **options)`               | `QR`              | Return a **copy** with a different style; the encoded matrix is shared.                                        |
| `qr.use_style(style=None, **options)`            | `QR`              | Change this code's style **in place**. Chainable.                                                              |
| `qr.render(style=None, **options)`               | `Artwork`         | Rasterise to a pixel buffer.                                                                                   |
| `qr.png(style=None, **options)`                  | `bytes`           | Render and encode as PNG.                                                                                      |
| `qr.svg(style=None, **options)`                  | `str`             | Render to an SVG document.                                                                                     |
| `qr.pdf(style=None, **options)`                  | `bytes`           | Render to a single-page vector PDF.                                                                            |
| `qr.terminal(style=None, color=True, **options)` | `str`             | ANSI half-block text for the terminal.                                                                         |
| `qr.print(style=None, **options)`                | `QR`              | Print `terminal()` and return the QR.                                                                          |
| `qr.ascii(dark="██", light=" ")`                 | `str`             | Plain text art straight from the matrix (no styling).                                                          |
| `qr.to_pil(style=None, **options)`               | `PIL.Image.Image` | Render as a Pillow image (requires Pillow).                                                                    |
| `qr.save(path, style=None, **options)`           | `str`             | Render and write to `path`; the format follows the extension. Returns the path.                                |
| `qr.show(style=None, **options)`                 | `QR`              | Render and open in the system image viewer.                                                                    |
| `qr.verify()`                                    | `str`             | Decode the symbol again and return its text (round-trip check).                                                |
| `qr.info()`                                      | `dict`            | Encoding details: version, level, mask, size, modules, codewords, dark ratio, penalty and segments.            |

Any render method accepts a style override as a preset name, `Style`, dict, or plain keywords:

```python
qr = qrforge.QR("overrides", ec="h")

qr.render(scale=12)                                     # keywords
qr.render("neon")                                       # preset
qr.render(qrforge.Style(module_shape="star"))           # Style object
qr.render({"module_shape": "dot", "fg": "#00ff88"})     # dict
qr.svg("gold", scale=16)
```

### Encoding details

```python
qr = qrforge.QR("https://example.com", ec="h")
qr.info()
# {'data': 'https://example.com', 'version': 3, 'level': 'H', 'mask': 3,
#  'size': 29, 'modules': 841, 'codewords': 70, 'dark_ratio': 0.5184,
#  'penalty': 1280, 'segments': [('byte', 19)]}
```

* `version` and `mask` are selected automatically (the mask with the lowest penalty score).
* `mode="auto"` performs optimal segmentation, so mixed content such as `"HELLO 123"` may produce several segments.
* Encoding is lazy and cached: changing the payload with `encode()` invalidates the matrix, and `styled()` reuses it.

### Saving formats

`QR.save()` picks the writer from the file extension:

| Extension                     | Content | Notes                                                                                                                                                                     |
| ----------------------------- | ------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `.png`                        | Raster  | Pure-Python PNG codec, no dependency.                                                                                                                                     |
| `.svg`                        | Vector  | Includes gradients, textures and SVG-capable shader filters.                                                                                                              |
| `.pdf`                        | Vector  | Single page; see [Presets & Outputs](/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-presets-and-outputs.md#output-formats). |
| `.html`                       | Vector  | Standalone page with the SVG inlined on a dark card.                                                                                                                      |
| `.txt`                        | Text    | Plain block characters.                                                                                                                                                   |
| `.ansi`                       | Text    | Terminal output with ANSI colour codes.                                                                                                                                   |
| `.webp` `.bmp` `.gif` `.tiff` | Raster  | Requires Pillow.                                                                                                                                                          |
| `.jpg` `.jpeg`                | Raster  | Requires Pillow **and** an RGB buffer: `qr.to_pil().convert("RGB").save("out.jpg")`.                                                                                      |

***

## Artwork

`QR.render()` returns an `Artwork`: either a pixel buffer (`kind == "pixmap"`) or vector markup (`kind == "svg"`).

| Member              | Type              | Description                                                       |
| ------------------- | ----------------- | ----------------------------------------------------------------- |
| `art.kind`          | `str`             | `"pixmap"`, `"svg"`, `"text"`, `"pdf"` or `"bytes"`.              |
| `art.payload`       | varies            | The underlying `Pixmap` or markup string.                         |
| `art.style`         | `Style`           | The resolved style used for the render.                           |
| `art.matrix`        | `QRMatrix`        | The encoded matrix.                                               |
| `art.pixmap`        | `Pixmap`          | The pixel buffer (raises `QRForgeError` for non-pixmap artwork).  |
| `art.text`          | `str`             | The markup (raises `QRForgeError` for non-text artwork).          |
| `art.width`         | `int`             | Pixel width, or the length of the markup.                         |
| `art.save(path)`    | `str`             | Write to `path`; PNG is native, other raster formats need Pillow. |
| `art.to_bytes()`    | `bytes`           | PNG bytes for pixmaps, UTF-8 bytes for markup.                    |
| `art.to_pil()`      | `PIL.Image.Image` | Requires Pillow.                                                  |
| `art.to_data_uri()` | `str`             | A `data:` URI for HTML/CSS embedding.                             |
| `str(art)`          | `str`             | The markup for SVG/text artwork.                                  |

`Artwork` also implements `_repr_png_`, `_repr_svg_` and `_repr_html_`, so it displays inline in Jupyter.

```python
art = qrforge.QR("hello").render(scale=12)
art.kind                        # 'pixmap'
art.width, art.pixmap.height    # pixel dimensions
art.save("hello.png")
payload = art.to_bytes() # PNG bytes
uri = art.to_data_uri()  # data:image/png;base64,…
```

***

## Shortcut functions

These helpers render a payload in one call. `style` may be a preset name or a dict; every other keyword is a [Style option](/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-style-options.md).

| Function                | Returns   | Description                               |
| ----------------------- | --------- | ----------------------------------------- |
| [`make`](#make)         | `Artwork` | Render `data` in one call.                |
| [`save`](#save)         | `str`     | Render `data` straight to `path`.         |
| [`svg`](#svg)           | `str`     | Render `data` to an SVG string.           |
| [`png`](#png)           | `bytes`   | Render `data` to PNG bytes.               |
| [`terminal`](#terminal) | `str`     | Render `data` to ANSI text.               |
| [`preset`](#preset)     | `Style`   | Shortcut for `qrforge.presets.get(name)`. |

### make

```
make(data, style=None, **options) -> Artwork
```

```python
art = qrforge.make("hello", "dots", fg="#123")
art.save("hello.png")
```

### save

```
save(data, path, style=None, **options) -> str
```

```python
qrforge.save("https://example.com", "code.png", "neon", scale=12)
```

### svg

```
svg(data, style=None, **options) -> str
```

```python
document = qrforge.svg("hello", "gold")
```

### png

```
png(data, style=None, **options) -> bytes
```

```python
payload = qrforge.png("hello", "dots")
```

### terminal

```
terminal(data, style=None, **options) -> str
```

```python
print(qrforge.terminal("hello", "neon"))
```

### preset

```
preset(name) -> Style
```

```python
style = qrforge.preset("sunset")
```

{% hint style="warning" %}
The shortcut functions create the underlying `QR` with default options, so they always use error correction level `M` and an automatic version/mask. Every keyword you pass is treated as a **style** option, which means encoding options such as `ec`, `version`, `mask` and `mode` raise `StyleError: unknown style option(s): …` there — use `qrforge.QR(data, ec="h")` when you need control over the encoding.
{% endhint %}

***

## Verification

### QR.verify

```python
qr = qrforge.QR("https://example.com", ec="h")
qr.verify()      # 'https://example.com'
```

`QR.verify()` decodes the symbol from its own module matrix, so it validates the encoder and styling decisions that affect the matrix (not raster artefacts such as blur or a low-contrast colour scheme).

### verify.decode

```python
import qrforge
from qrforge.verify import decode

qr = qrforge.QR("hello", ec="h")
result = decode(qr.matrix.rows())     # 0 = light, 1 = dark
print(result.text, result.version, result.level, result.mask, result.corrected)
```

`decode(matrix)` accepts a matrix of `0`/`1` rows (`0` = light, `1` = dark) and returns a `DecodeResult`:

| Attribute   | Type  | Description                                              |
| ----------- | ----- | -------------------------------------------------------- |
| `text`      | `str` | The decoded payload.                                     |
| `version`   | `int` | QR version read from the symbol.                         |
| `level`     | `str` | Error correction level read from the format information. |
| `mask`      | `int` | Mask pattern index.                                      |
| `corrected` | `int` | Number of codewords repaired by Reed–Solomon.            |

```python
import qrforge
from qrforge.verify import decode

qr = qrforge.QR("hello", ec="h")
damaged = [list(row) for row in qr.matrix.modules]
for row, col in [(19, 18), (18, 19)]:      # flip two data modules
    damaged[row][col] ^= 1
print(decode(damaged))
# DecodeResult(text='hello', version=1, level='H', mask=6, corrected=2)
```

***

## Low-level encoding

```python
from qrforge import build_matrix, encoder, gf, matrix, tables
```

| Function                                                                           | Description                                                                                  |
| ---------------------------------------------------------------------------------- | -------------------------------------------------------------------------------------------- |
| `matrix.build(text, level="M", version=None, mask=None, mode="auto")`              | Encode text and return a `QRMatrix` (no rendering). Also exported as `qrforge.build_matrix`. |
| `encoder.normalize(data)`                                                          | Convert `str`/`bytes` into the latin-1 string form used internally.                          |
| `encoder.segment(text, version, mode="auto")`                                      | Segment text into optimal `Segment`s.                                                        |
| `encoder.segment_bits(segments, version)`                                          | Bit length of the segment headers plus payload.                                              |
| `encoder.capacity_bits(version, level)`                                            | Data capacity in bits.                                                                       |
| `encoder.pick_version(text, level, mode="auto", min_version=1, max_version=40)`    | Return `(version, segments)` for the smallest version that fits.                             |
| `encoder.build_data_bits(segments, version, level)`                                | Produce the padded data codewords.                                                           |
| `encoder.interleave(data, version, level)`                                         | Add Reed–Solomon parity and interleave the blocks.                                           |
| `encoder.encode_codewords(text, version, level, segments=None)`                    | Full pipeline from text to final codewords.                                                  |
| `gf.rs_encode(data, ec_len)`                                                       | Reed–Solomon parity bytes.                                                                   |
| `gf.rs_correct(msg, nsym)`                                                         | Correct a codeword block; returns `(corrected_message, fixed_count)`.                        |
| `tables.version_size(version)`                                                     | Side length in modules (`version * 4 + 17`).                                                 |
| `tables.alignment_positions(version)`                                              | Alignment pattern centres.                                                                   |
| `tables.block_layout(version, level)`                                              | `(ec_codewords_per_block, ((count, data_codewords), …))`.                                    |
| `tables.total_codewords(version, level)` / `tables.data_codewords(version, level)` | Codeword counts.                                                                             |
| `tables.count_bits(mode, version)`                                                 | Character count indicator width.                                                             |
| `bits.BitBuffer`                                                                   | The MSB-first bit buffer used by the encoder (`append`, `bit`, `to_bytes`, `len`).           |

`QRMatrix` exposes:

| Member                                  | Description                                                           |
| --------------------------------------- | --------------------------------------------------------------------- |
| `version`, `level`, `mask`, `size`      | Encoding metadata.                                                    |
| `modules`                               | The module grid (rows of `0`/`1`).                                    |
| `segments`                              | The chosen segment list.                                              |
| `penalty_score`                         | Mask penalty score of the final matrix.                               |
| `dark_ratio()`                          | Fraction of dark modules.                                             |
| `total_codewords()`                     | Total codewords in the symbol.                                        |
| `rows()`                                | `modules` as a list of lists.                                         |
| `is_dark(row, col)`                     | Whether a module is dark.                                             |
| `role(row, col)`, `role_name(row, col)` | Module role code / name (`data`, `finder`, `separator`, `timing`, …). |
| `iter_modules()`                        | Yield `(row, col, dark, role)` for every module.                      |
| `ascii(dark="##", light=" ")`           | Text art of the matrix.                                               |
| `to_dict()`                             | A serialisable dictionary of the matrix.                              |

```python
from qrforge import matrix, encoder

qr_matrix = matrix.build("HELLO", level="M")
print(qr_matrix.version, qr_matrix.size, qr_matrix.dark_ratio())

segments = encoder.segment("HELLO 123", qr_matrix.version, mode="auto")
codewords = encoder.encode_codewords("HELLO 123", qr_matrix.version, "M")
print(segments, len(codewords))
```

***

## Exceptions

| Exception            | Raised when                                                                                                          |
| -------------------- | -------------------------------------------------------------------------------------------------------------------- |
| `QRForgeError`       | Base class for every qrforge error; also raised for invalid operations such as writing an SVG from a raster artwork. |
| `DataTooLong`        | The payload does not fit into a symbol with the requested version/EC level.                                          |
| `StyleError`         | A style, shader or preset option is invalid (for example an unknown option or shader name).                          |
| `UnsupportedFeature` | Declared for optional-dependency errors. In 1.0.1 the imaging helpers raise `ValueError` when Pillow is missing.     |

```python
import qrforge

try:
    qrforge.QR("x" * 5000, ec="h").matrix
except qrforge.DataTooLong as error:
    print(error)     # data does not fit in version 40 at error correction level H

try:
    qrforge.QR("hi").use_style(nope=1)
except qrforge.StyleError as error:
    print(error)     # unknown style option(s): nope
```

All of them are importable from the top level:

```python
from qrforge import QRForgeError, DataTooLong, StyleError, UnsupportedFeature
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://infinitode-docs.gitbook.io/documentation/package-documentation/qrforge-package-documentation/qrforge-reference/qrforge-api-functions.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
