Examples Showcase / pcbdoc_svg
Render PcbDoc layers to SVG
Load the RT Super C1 project with AltiumDesign, open its PcbDoc, and write one SVG per visible PCB layer plus a separate board-outline SVG.
Output Previews
Load the RT Super C1 project with AltiumDesign, open its PcbDoc, and render individual PCB SVG files for each layer of the board's Fab view plus a separate board-outline SVG (the view's PROFILE key). For review clarity, copper layers render as black geometry on a white/transparent SVG background, and the holes render green.
This example is read-only. It demonstrates the core PcbDoc SVG API rather than variant-aware or web-view rendering.
What It Shows
AltiumDesign.from_prjpcb(...)AltiumDesign.load_pcbdoc(...)- Passing project parameters into PCB text substitution:
pcbdoc.fab(parameters=...) fab.to_layer_svgs(scale=10.0, layer_colours={...}): one image per layer key of the board's Fab view, the board outline as itsPROFILEkey and the holes asDRILLS- Colouring the copper layers black and the holes green with
layer_colours, keyed by layer key - Resolving layer selectors from enum, legacy layer id, JSON token, or resolved friendly layer name to a layer key for
layers=(...) - Using
PcbLayer.to_display_name()as the default fallback label when a parsed board does not provide a stack-specific layer name
Layer Selection
The SVG options select layers by the board's Fab view's layer keys:
images = pcbdoc.to_layer_svgs(layers=("TOP",))This example includes resolve_pcb_svg_layer(...) to show a friendlier shape for callers. It accepts selectors such as:
PcbLayer.TOP
1
"TOP"
"Top Layer"
"[8] Board Outline"The RT Super C1 board includes keepout-layer tracks, so its view has a KEEPOUT key and the per-layer output emits a KEEPOUT SVG. The resolver also resolves "Keep-Out Layer" to PcbLayer.KEEPOUT.
Scale
scale sets the display size of one millimetre: it changes the SVG width and height attributes, while the viewBox and geometry stay in millimetres so downstream CAD or viewer code can continue to reason in physical units.
Run
From the repo root:
uv run python examples\pcbdoc_svg\pcbdoc_svg.pyOutput
examples/pcbdoc_svg/output/board_outline.svg
examples/pcbdoc_svg/output/layers/
examples/pcbdoc_svg/output/pcbdoc_svg_manifest.jsonSource Code
from __future__ import annotations
import json
import re
import shutil
from pathlib import Path
from altium_monkey import AltiumDesign, PcbLayer, PcbLayerRef
from altium_monkey.altium_pcb_layer_context import PcbLayerContext
SCALE_FACTOR = 10.0
COPPER_LAYER_COLOR = "#000000"
DRILL_HOLE_COLOR = "#00A000"
SAMPLE_DIR = Path(__file__).resolve().parent
EXAMPLES_DIR = SAMPLE_DIR.parent
PROJECT_DIR = EXAMPLES_DIR / "assets" / "projects" / "rt_super_c1"
PROJECT_FILE = PROJECT_DIR / "RT_SUPER_C1.PrjPcb"
OUTPUT_DIR = SAMPLE_DIR / "output"
OUTPUT_LAYERS_DIR = OUTPUT_DIR / "layers"
OUTPUT_MANIFEST = OUTPUT_DIR / "pcbdoc_svg_manifest.json"
OUTPUT_BOARD_OUTLINE = OUTPUT_DIR / "board_outline.svg"
DRILLS_LAYER_KEY = "DRILLS"
OUTLINE_KEY = "PROFILE"
def _layer_colours(copper_keys: list[str]) -> dict[str, str]:
colours = {key: COPPER_LAYER_COLOR for key in copper_keys}
colours[DRILLS_LAYER_KEY] = DRILL_HOLE_COLOR
return colours
def _examples_relative(path: Path) -> str:
return str(path.relative_to(EXAMPLES_DIR)).replace("\\", "/")
def _sample_relative(path: Path) -> str:
return str(path.relative_to(SAMPLE_DIR)).replace("\\", "/")
def _safe_filename(value: str) -> str:
token = re.sub(r"[^A-Za-z0-9._-]+", "_", value.strip())
return token.strip("_").lower() or "layer"
def _display_name_for_layer(layer: PcbLayer, layers_ctx: PcbLayerContext) -> str:
layer_id = layers_ctx.resolve(PcbLayerRef.from_legacy(layer.value)).found
if layer_id is not None:
return layers_ctx.layer(layer_id).name
return layer.to_display_name()
def resolve_pcb_svg_layer(
selector: PcbLayer | int | str,
layers_ctx: PcbLayerContext,
) -> PcbLayer:
"""
Resolve common user-facing layer selectors to the PcbLayer enum used by SVG options.
"""
if isinstance(selector, PcbLayer):
return selector
if isinstance(selector, int):
return PcbLayer(selector)
raw = str(selector).strip()
if not raw:
raise ValueError("Layer selector cannot be empty")
if raw.isdecimal():
return PcbLayer(int(raw))
normalized = re.sub(r"[^A-Za-z0-9]+", "", raw).upper()
for candidate in (raw.upper(), normalized):
try:
return PcbLayer.from_json_name(candidate)
except ValueError:
pass
layer_id = layers_ctx.by_token(raw).found
if layer_id is None:
raise ValueError(f"Unknown PCB layer selector: {selector!r}")
legacy_id = layers_ctx.layer(layer_id).ref.legacy_layer_id
if legacy_id is None:
raise ValueError(f"Unknown PCB layer selector: {selector!r}")
return PcbLayer(int(legacy_id))
def _layer_sort_key(layer_key: str) -> tuple[int, str]:
if layer_key == DRILLS_LAYER_KEY:
return (10_000, layer_key)
try:
return (PcbLayer.from_json_name(layer_key).value, layer_key)
except ValueError:
return (9_000, layer_key)
def _layer_output_path(layer_key: str) -> Path:
if layer_key == DRILLS_LAYER_KEY:
return OUTPUT_LAYERS_DIR / "layer_drills.svg"
try:
layer = PcbLayer.from_json_name(layer_key)
except ValueError:
# V7-only layers (e.g. MECHANICAL17..53) have no legacy enum value.
return OUTPUT_LAYERS_DIR / f"layer_v7_{_safe_filename(layer_key)}.svg"
filename = f"layer_{layer.value:02d}_{_safe_filename(layer_key)}.svg"
return OUTPUT_LAYERS_DIR / filename
def _layer_manifest_entry(
layer_key: str,
output_path: Path,
layers_ctx: PcbLayerContext,
) -> dict[str, object]:
if layer_key == DRILLS_LAYER_KEY:
return {
"key": DRILLS_LAYER_KEY,
"display_name": "Drill Holes",
"legacy_id": None,
"enum_name": None,
"selector_examples": [DRILLS_LAYER_KEY],
"svg": _sample_relative(output_path),
"byte_count": output_path.stat().st_size,
}
try:
layer = PcbLayer.from_json_name(layer_key)
except ValueError:
# V7-only layers carry their identity in the V7 token; there is no
# legacy enum value or id to report.
layer_id = layers_ctx.by_token(layer_key).found
display_name = (
layers_ctx.layer(layer_id).name if layer_id is not None else layer_key
)
return {
"key": layer_key,
"display_name": display_name,
"legacy_id": None,
"enum_name": None,
"selector_examples": [layer_key, display_name],
"svg": _sample_relative(output_path),
"byte_count": output_path.stat().st_size,
}
display_name = _display_name_for_layer(layer, layers_ctx)
return {
"key": layer_key,
"display_name": display_name,
"legacy_id": layer.value,
"enum_name": layer.name,
"selector_examples": [
layer.name,
layer.value,
layer_key,
display_name,
],
"svg": _sample_relative(output_path),
"byte_count": output_path.stat().st_size,
}
def _write_svg(path: Path, svg: str) -> None:
path.parent.mkdir(parents=True, exist_ok=True)
path.write_text(svg, encoding="utf-8")
def _as_stroked_outline_svg(
svg: str,
*,
stroke: str = "#000000",
stroke_width_mm: float = 0.25,
pad_mm: float = 0.5,
) -> str:
"""Convert a filled PROFILE SVG into a stroked board-perimeter drawing."""
import xml.etree.ElementTree as ET
ET.register_namespace("", "http://www.w3.org/2000/svg")
root = ET.fromstring(svg)
view_box = root.get("viewBox")
if view_box:
parts = [float(v) for v in view_box.split()]
if len(parts) == 4:
x, y, w, h = parts
root.set(
"viewBox",
f"{x - pad_mm:.6g} {y - pad_mm:.6g} {w + 2 * pad_mm:.6g} {h + 2 * pad_mm:.6g}",
)
for elem in root.iter():
if elem.tag.endswith("path"):
elem.set("fill", "none")
elem.set("stroke", stroke)
elem.set("stroke-width", f"{stroke_width_mm:g}")
elem.set("stroke-linejoin", "round")
return ET.tostring(root, encoding="unicode") + "\n"
def main() -> None:
design = AltiumDesign.from_prjpcb(PROJECT_FILE)
pcbdoc = design.load_pcbdoc()
layers_ctx = pcbdoc.layers()
project_parameters = design.get_pcb_project_parameters()
if OUTPUT_DIR.exists():
shutil.rmtree(OUTPUT_DIR)
OUTPUT_LAYERS_DIR.mkdir(parents=True, exist_ok=True)
# One Fab for the board: its images share one draw of the board.
fab = pcbdoc.fab(parameters=project_parameters)
copper_keys = [
layer.key for layer in fab.view().layers() if layer.role == "conductor"
]
layer_svgs = fab.to_layer_svgs(
scale=SCALE_FACTOR, layer_colours=_layer_colours(copper_keys)
)
layers: list[dict[str, object]] = []
# Each image is named by its layer key (`<key>.svg`, the holes `DRILLS.svg`).
images = {Path(name).stem: image.text for name, image in layer_svgs.items()}
for layer_key in sorted(images, key=_layer_sort_key):
if layer_key == OUTLINE_KEY:
# The board outline is the view's PROFILE key; render as a stroked
# perimeter rather than a solid filled slab.
_write_svg(OUTPUT_BOARD_OUTLINE, _as_stroked_outline_svg(images[layer_key]))
continue
output_path = _layer_output_path(layer_key)
_write_svg(output_path, images[layer_key])
layers.append(_layer_manifest_entry(layer_key, output_path, layers_ctx))
selector_demo_layer = resolve_pcb_svg_layer("Top Layer", layers_ctx)
keepout_layer = resolve_pcb_svg_layer("Keep-Out Layer", layers_ctx)
manifest = {
"project": _examples_relative(PROJECT_FILE),
"pcbdoc": _examples_relative(Path(pcbdoc.filepath or "")),
"scale_factor": SCALE_FACTOR,
"project_parameters": project_parameters,
"board_outline_svg": _sample_relative(OUTPUT_BOARD_OUTLINE),
"render_style": {
"copper_layer_color": COPPER_LAYER_COLOR,
"drill_hole_color": DRILL_HOLE_COLOR,
},
"layer_count": len(layers),
"layers": layers,
"selector_demo": {
"input": "Top Layer",
"resolved_key": selector_demo_layer.to_json_name(),
"resolved_legacy_id": selector_demo_layer.value,
"layers_option": "pcbdoc.to_layer_svgs(layers=('TOP',))",
},
"keepout": {
"selector_resolves_to": keepout_layer.to_json_name(),
"selector_legacy_id": keepout_layer.value,
"written_for_this_board": any(
layer["key"] == keepout_layer.to_json_name() for layer in layers
),
"note": (
"Keep-Out Layer is selectable for SVG export. It is emitted by "
"automatic per-layer export only when keepout primitives are present."
),
},
}
OUTPUT_MANIFEST.write_text(
json.dumps(manifest, indent=2, ensure_ascii=False) + "\n",
encoding="utf-8",
)
print(f"Loaded project: {_examples_relative(PROJECT_FILE)}")
print(f"Loaded PCB: {Path(pcbdoc.filepath or '').name}")
print(f"SVG display scale factor: {SCALE_FACTOR:g}")
print(f"Layer SVG files written: {len(layers)}")
print(f"Wrote board outline: {_sample_relative(OUTPUT_BOARD_OUTLINE)}")
print(f"Wrote manifest: {_sample_relative(OUTPUT_MANIFEST)}")
if __name__ == "__main__":
main()