altium monkey v2026.11.26 · gobblerito
On This Page (5)

Examples Showcase / pcbdoc_barcodes_1d_and_2d

Author and render 1D and 2D PCB barcodes

Place CODE_39, CODE_128, QR_CODE, and DATA_MATRIX barcodes on a generated PcbDoc, verify binary save/reload round-trip, and flatten to Gerber X2 and SVG through Fab.

pcbdocfabsvgpcbdocbarcodeqr-codedata-matrixcode-128code-39

Output Previews

pcbdoc_barcodes_1d_and_2d.svg
Open SVG
pcbdoc_barcodes_1d_and_2d.svg

Author all four Altium PCB barcode symbologies (CODE_39, CODE_128, QR_CODE, DATA_MATRIX) with AltiumPcbDoc.add_text(..., font_kind=PcbTextKind.BARCODE), save and reload the .PcbDoc, and emit both Gerber X2 outputs and a preview SVG through Fab.

What It Shows

  1. Placing 1D (CODE_39, CODE_128) and 2D (QR_CODE, DATA_MATRIX) barcodes on TOP_OVERLAY and TOP copper
  2. Comparing PcbBarcodeRenderMode.BY_MIN_WIDTH vs. BY_FULL_WIDTH, human-readable captions (barcode_show_text), quiet-zone margins (barcode_margin_mils), and inverted boxes (barcode_inverted)
  3. Verifying binary .PcbDoc save/reload round-trip on AltiumPcbText.font_type == 2 and its barcode metadata fields
  4. Flattening every barcode into Gerber X2 and SVG geometry via pcbdoc.fab()

Run

From the repository root:

powershell
uv run python examples\pcbdoc_barcodes_1d_and_2d\pcbdoc_barcodes_1d_and_2d.py

Output

The script writes:

text
examples/pcbdoc_barcodes_1d_and_2d/output/pcbdoc_barcodes_1d_and_2d.PcbDoc
examples/pcbdoc_barcodes_1d_and_2d/output/pcbdoc_barcodes_1d_and_2d.svg
examples/pcbdoc_barcodes_1d_and_2d/output/gerbers/
examples/pcbdoc_barcodes_1d_and_2d/output/barcodes_manifest.json

Source Code

examples/pcbdoc_barcodes_1d_and_2d/pcbdoc_barcodes_1d_and_2d.py
from __future__ import annotations

import json
import shutil
from pathlib import Path

from altium_monkey import (
    AltiumBoardOutline,
    AltiumPcbDoc,
    BoardOutlineVertex,
    PcbBarcodeKind,
    PcbBarcodeRenderMode,
    PcbLayer,
    PcbTextKind,
)

SAMPLE_DIR = Path(__file__).resolve().parent
OUTPUT_DIR = SAMPLE_DIR / "output"
PCBDOC_PATH = OUTPUT_DIR / "pcbdoc_barcodes_1d_and_2d.PcbDoc"
SVG_PATH = OUTPUT_DIR / "pcbdoc_barcodes_1d_and_2d.svg"
GERBERS_DIR = OUTPUT_DIR / "gerbers"
MANIFEST_PATH = OUTPUT_DIR / "barcodes_manifest.json"


def _sample_relative(path: Path) -> str:
    return path.relative_to(SAMPLE_DIR).as_posix()


def _rect_outline(width_mils: float, height_mils: float) -> AltiumBoardOutline:
    return AltiumBoardOutline(
        vertices=[
            BoardOutlineVertex.line(0.0, 0.0),
            BoardOutlineVertex.line(width_mils, 0.0),
            BoardOutlineVertex.line(width_mils, height_mils),
            BoardOutlineVertex.line(0.0, height_mils),
        ]
    )


def build_barcodes_example(output_dir: Path = OUTPUT_DIR) -> dict[str, object]:
    if output_dir.exists():
        shutil.rmtree(output_dir)
    output_dir.mkdir(parents=True, exist_ok=True)

    pcbdoc = AltiumPcbDoc()
    pcbdoc.set_board_outline(_rect_outline(4200.0, 2400.0))
    pcbdoc.set_origin_to_outline_lower_left()

    # Title caption on Top Overlay
    pcbdoc.add_text(
        text="ALTIUM-MONKEY PCB BARCODES (1D + 2D)",
        position_mils=(160.0, 2180.0),
        height_mils=85.0,
        stroke_width_mils=14.0,
        layer=PcbLayer.TOP_OVERLAY,
    )

    # 1. Code 39 (1D, sized by minimum bar width)
    pcbdoc.add_text(
        text="SN-2026-C39",
        position_mils=(160.0, 1520.0),
        height_mils=75.0,
        layer=PcbLayer.TOP_OVERLAY,
        font_kind=PcbTextKind.BARCODE,
        barcode_kind=PcbBarcodeKind.CODE_39,
        barcode_render_mode=PcbBarcodeRenderMode.BY_MIN_WIDTH,
        barcode_full_size_mils=(1600.0, 320.0),
        barcode_min_width_mils=10.0,
        barcode_margin_mils=(30.0, 30.0),
        barcode_show_text=True,
        barcode_inverted=False,
    )

    # 2. Code 128 (1D, sized by full bounding box, inverted silkscreen box)
    pcbdoc.add_text(
        text="Batch-1126-A",
        position_mils=(160.0, 760.0),
        height_mils=75.0,
        layer=PcbLayer.TOP_OVERLAY,
        font_kind=PcbTextKind.BARCODE,
        barcode_kind=PcbBarcodeKind.CODE_128,
        barcode_render_mode=PcbBarcodeRenderMode.BY_FULL_WIDTH,
        barcode_full_size_mils=(1700.0, 340.0),
        barcode_margin_mils=(35.0, 35.0),
        barcode_show_text=True,
        barcode_inverted=True,
    )

    # 3. QR Code (2D, inverted silkscreen box)
    pcbdoc.add_text(
        text="https://wavenumber-eng.github.io/altium-monkey",
        position_mils=(2260.0, 1180.0),
        height_mils=75.0,
        layer=PcbLayer.TOP_OVERLAY,
        font_kind=PcbTextKind.BARCODE,
        barcode_kind=PcbBarcodeKind.QR_CODE,
        barcode_render_mode=PcbBarcodeRenderMode.BY_FULL_WIDTH,
        barcode_full_size_mils=(760.0, 760.0),
        barcode_margin_mils=(40.0, 40.0),
        barcode_show_text=False,
        barcode_inverted=True,
    )

    # 4. Data Matrix (2D, sized by minimum module width)
    pcbdoc.add_text(
        text="DM-2026-001",
        position_mils=(3240.0, 1340.0),
        height_mils=70.0,
        layer=PcbLayer.TOP_OVERLAY,
        font_kind=PcbTextKind.BARCODE,
        barcode_kind=PcbBarcodeKind.DATA_MATRIX,
        barcode_render_mode=PcbBarcodeRenderMode.BY_MIN_WIDTH,
        barcode_min_width_mils=28.0,
        barcode_margin_mils=(35.0, 35.0),
        barcode_show_text=True,
        barcode_inverted=False,
    )

    # 5. Secondary QR Code on Top Copper to verify copper barcode rendering
    pcbdoc.add_text(
        text="CU-QR-OK",
        position_mils=(2260.0, 260.0),
        height_mils=70.0,
        layer=PcbLayer.TOP,
        font_kind=PcbTextKind.BARCODE,
        barcode_kind=PcbBarcodeKind.QR_CODE,
        barcode_render_mode=PcbBarcodeRenderMode.BY_MIN_WIDTH,
        barcode_min_width_mils=22.0,
        barcode_margin_mils=(30.0, 30.0),
        barcode_show_text=True,
        barcode_inverted=False,
    )

    pcbdoc_path = output_dir / "pcbdoc_barcodes_1d_and_2d.PcbDoc"
    pcbdoc.save(pcbdoc_path)

    # Reload from disk and verify readback + Gerber/SVG rendering through Fab.
    reloaded = AltiumPcbDoc.from_file(pcbdoc_path)
    barcode_texts = [t for t in reloaded.texts if t.font_type == 2]

    fab = reloaded.fab()
    gerbers = fab.to_gerbers(x2_attributes=True)
    gerbers_dir = output_dir / "gerbers"
    gerbers.write(gerbers_dir)

    svg_out = fab.to_svg(
        scale=3.0,
        layers=("PROFILE", "TOP", "TOPOVERLAY"),
        layer_colours={
            "PROFILE": "#163822",
            "TOP": "#D9534F",
            "TOPOVERLAY": "#F7F4EA",
        },
        clip_to_outline=True,
        metadata=True,
    )
    svg_path = output_dir / "pcbdoc_barcodes_1d_and_2d.svg"
    svg_path.write_bytes(svg_out["board.svg"].data)

    manifest: dict[str, object] = {
        "pcbdoc": _sample_relative(pcbdoc_path),
        "svg": _sample_relative(svg_path),
        "barcode_count": len(barcode_texts),
        "barcodes": [
            {
                "text": t.text_content,
                "layer": str(t.layer),
                "barcode_kind": PcbBarcodeKind(t.barcode_kind).name,
                "render_mode": PcbBarcodeRenderMode(t.barcode_render_mode).name,
                "show_text": bool(t.barcode_show_text),
                "inverted": bool(t.barcode_inverted),
            }
            for t in barcode_texts
        ],
        "gerber_files": sorted(gerbers.keys()),
    }

    manifest_path = output_dir / "barcodes_manifest.json"
    manifest_path.write_text(
        json.dumps(manifest, indent=2) + "\n",
        encoding="utf-8",
        newline="\n",
    )
    return manifest


def main() -> None:
    manifest = build_barcodes_example()
    print(f"Wrote PcbDoc: {manifest['pcbdoc']}")
    print(f"Barcodes round-tripped: {manifest['barcode_count']}")
    for row in manifest["barcodes"]:
        print(
            f"  {row['barcode_kind']} ({row['render_mode']}): "
            f"{row['text']!r} inverted={row['inverted']}"
        )
    print(f"Gerber files: {len(manifest['gerber_files'])}")
    print(f"Wrote SVG: {manifest['svg']}")


if __name__ == "__main__":
    main()
altium-monkey v2026.11.26 · gobblerito·Docs updated 2026.11.29 17:55 UTC (0665053)