On This Page (5)
Examples Showcase / fab_view_query_and_fonts
Query FabView collections, virtual layers, font policies, and annotated SVGs
Compare altium vs. embedded_first font policies on RT_SUPER_C1.PCBdoc, query FabView layers, holes, placements, nets, and virtual_layer(...) results, round-trip FabView JSON, and render annotated and virtual-layer SVGs.
Output Previews
Query a flattened FabView directly (layers(), holes(), placements(), nets(), fonts(), and virtual_layer(...)), compare fonts={"policy": "altium"} vs. "embedded_first", inspect VirtualLayerResult.to_fab_layer_items(), round-trip the view through FabView.to_json() / FabView.from_json(), and render annotated and virtual-layer board SVGs.
What It Shows
- Opening
pcbdoc.fab(fonts={"policy": ...}).view()to inspect font provenance under"altium"vs."embedded_first" - Querying structured
FabViewgeometry and manufacturing collections (layers,holes,placements,nets) - Querying virtual layers (
PIN1_TOP,DIODES_TOP,ASSEMBLY_OUTLINES_TOP,ASSEMBLY_DESIGNATORS_TOP) viaview.virtual_layer(key, VirtualLayerOptions(...))and inspectingVirtualLayerResult(placed,styles,color_mode) andto_fab_layer_items()(strokes,areas,lands) - Round-tripping the flattened board view through canonical JSON with
FabView.to_json()andFabView.from_json() - Rendering an annotated board SVG (
annotations=[{"kind": "pad_labels"}, {"kind": "origin_marker"}]) and a companion virtual-layer SVG
Run
From the repository root:
uv run python examples\fab_view_query_and_fonts\fab_view_query_and_fonts.pyOutput
The script writes:
examples/fab_view_query_and_fonts/output/board_annotated.svg
examples/fab_view_query_and_fonts/output/board_virtual_layers.svg
examples/fab_view_query_and_fonts/output/fab_view.json
examples/fab_view_query_and_fonts/output/fab_view_query_manifest.jsonSource Code
from __future__ import annotations
import json
import shutil
from pathlib import Path
from altium_monkey import AltiumDesign
from altium_monkey.fab import (
AssemblyDesignatorLayerOptions,
AssemblyOutlineLayerOptions,
DiodeLayerOptions,
FabView,
Pin1LayerOptions,
VirtualLayerOptions,
VirtualLayerResult,
)
from altium_monkey.fab_view_contracts.generated import (
FabSvgOriginMarker,
FabSvgPadLabels,
)
SAMPLE_DIR = Path(__file__).resolve().parent
EXAMPLES_DIR = SAMPLE_DIR.parent
PROJECT_FILE = (
EXAMPLES_DIR / "assets" / "projects" / "rt_super_c1" / "RT_SUPER_C1.PrjPcb"
)
OUTPUT_DIR = SAMPLE_DIR / "output"
ANNOTATED_SVG_PATH = OUTPUT_DIR / "board_annotated.svg"
VIRTUAL_SVG_PATH = OUTPUT_DIR / "board_virtual_layers.svg"
VIEW_JSON_PATH = OUTPUT_DIR / "fab_view.json"
MANIFEST_PATH = OUTPUT_DIR / "fab_view_query_manifest.json"
def _examples_relative(path: Path) -> str:
return path.relative_to(EXAMPLES_DIR).as_posix()
def _sample_relative(path: Path) -> str:
return path.relative_to(SAMPLE_DIR).as_posix()
def build_fab_view_query_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)
design = AltiumDesign.from_prjpcb(PROJECT_FILE)
pcbdoc = design.load_pcbdoc()
project_parameters = design.get_pcb_project_parameters()
# Compare the two font resolution policies on a board with embedded TTFs.
fab_altium = pcbdoc.fab(
parameters=project_parameters,
fonts={"policy": "altium"},
)
fab_embedded = pcbdoc.fab(
parameters=project_parameters,
fonts={"policy": "embedded_first"},
)
view_altium = fab_altium.view()
view_embedded = fab_embedded.view()
# Round-trip FabView through canonical JSON and verify counts match.
view_json = view_embedded.to_json()
view_json_path = output_dir / "fab_view.json"
view_json_path.write_bytes(view_json)
reloaded_view = FabView.from_json(view_json)
layers = reloaded_view.layers()
holes = reloaded_view.holes()
placements = reloaded_view.placements()
nets = reloaded_view.nets()
if len(reloaded_view.holes()) != len(view_embedded.holes()):
raise RuntimeError("FabView JSON round-trip hole count mismatch")
# Query board-derived virtual layers directly on FabView and inspect
# both VirtualLayerResult and its canonical FabLayerItems conversion.
virtual_options = VirtualLayerOptions(
font_mode="stroke",
stroke_font="sans_serif",
pin1=Pin1LayerOptions(
exclude_designator_prefixes=("R", "C", "L"),
diode_ak_labels=True,
),
diodes=DiodeLayerOptions(color_mode="shaded"),
assembly_outlines=AssemblyOutlineLayerOptions(detail="simple"),
assembly_designators=AssemblyDesignatorLayerOptions(
min_font_size_mm=0.08,
max_font_size_mm=2.40,
fill_ratio=0.78,
),
)
virtual_summary: dict[str, dict[str, object]] = {}
for key in (
"PIN1_TOP",
"DIODES_TOP",
"ASSEMBLY_OUTLINES_TOP",
"ASSEMBLY_DESIGNATORS_TOP",
):
result = view_embedded.virtual_layer(key, virtual_options)
assert isinstance(result, VirtualLayerResult)
fab_items = result.to_fab_layer_items()
virtual_summary[key] = {
"color_mode": result.color_mode,
"placed_items": len(result.placed),
"styled_items": len(result.styles),
"fab_strokes": len(fab_items.strokes or ()),
"fab_areas": len(fab_items.areas or ()),
"fab_lands": len(fab_items.lands or ()),
}
# Render an annotated board SVG with pad designator labels and origin marker.
annotated_svg = fab_embedded.to_svg(
scale=8.0,
layers=("PROFILE", "TOP", "TOPSOLDER", "TOPOVERLAY", "DRILLS"),
layer_colours={
"PROFILE": "#F4F5F2",
"TOP": "#D4D8DE",
"TOPSOLDER": "rgba(235, 193, 74, 0.90)",
"TOPOVERLAY": "#141619",
"DRILLS": "#2B3038",
},
annotations=(FabSvgPadLabels(), FabSvgOriginMarker()),
clip_to_outline=True,
metadata=True,
)
svg_path = output_dir / "board_annotated.svg"
svg_path.write_bytes(annotated_svg["board.svg"].data)
# Render a companion SVG showing the queried virtual layers over the board.
virtual_svg = fab_embedded.to_svg(
scale=8.0,
layers=(
"PROFILE",
"TOP",
"DRILLS",
"ASSEMBLY_OUTLINES_TOP",
"ASSEMBLY_DESIGNATORS_TOP",
"PIN1_TOP",
"DIODES_TOP",
),
layer_colours={
"PROFILE": "#F4F5F2",
"TOP": "#D4D8DE",
"DRILLS": "#2B3038",
"ASSEMBLY_OUTLINES_TOP": "#374151",
"ASSEMBLY_DESIGNATORS_TOP": "#111827",
},
clip_to_outline=True,
metadata=True,
virtual_options=virtual_options,
)
virtual_svg_path = output_dir / "board_virtual_layers.svg"
virtual_svg_path.write_bytes(virtual_svg["board.svg"].data)
def _font_rows(view: FabView) -> list[dict[str, object]]:
report = view.fonts()
rows: list[dict[str, object]] = []
for entry in report.entries:
rows.append(
{
"family": entry.family,
"bold": entry.bold,
"italic": entry.italic,
"texts": entry.texts,
"layers": list(entry.layers),
"altium_source": entry.altium,
"altium_face": entry.altium_face,
}
)
return rows
manifest: dict[str, object] = {
"project": _examples_relative(PROJECT_FILE),
"pcbdoc": _examples_relative(Path(pcbdoc.filepath or "")),
"fab_view_summary": {
"layer_count": len(layers),
"conductor_layers": [
layer.key for layer in layers if layer.role == "conductor"
],
"hole_count": len(holes),
"plated_hole_count": sum(
1 for hole in holes if getattr(hole, "plated", False)
),
"placement_count": len(placements),
"net_count": len(nets),
"json_round_trip_bytes": view_json_path.stat().st_size,
},
"virtual_layers": virtual_summary,
"font_policies": {
"altium": _font_rows(view_altium),
"embedded_first": _font_rows(view_embedded),
},
"outputs": {
"annotated_svg": _sample_relative(svg_path),
"virtual_layers_svg": _sample_relative(virtual_svg_path),
"fab_view_json": _sample_relative(view_json_path),
},
}
manifest_path = output_dir / "fab_view_query_manifest.json"
manifest_path.write_text(
json.dumps(manifest, indent=2) + "\n",
encoding="utf-8",
newline="\n",
)
return manifest
def main() -> None:
manifest = build_fab_view_query_example()
summary = manifest["fab_view_summary"]
virtual = manifest["virtual_layers"]
assert isinstance(summary, dict) and isinstance(virtual, dict)
print(f"Loaded board: {manifest['pcbdoc']}")
print(
f"FabView: {summary['layer_count']} layers, {summary['hole_count']} holes, "
f"{summary['placement_count']} placements, {summary['net_count']} nets"
)
for key, stats in virtual.items():
assert isinstance(stats, dict)
print(
f"Virtual {key:24s}: placed={stats['placed_items']}, "
f"strokes={stats['fab_strokes']}, areas={stats['fab_areas']}, "
f"mode={stats['color_mode']}"
)
outputs = manifest["outputs"]
assert isinstance(outputs, dict)
print(f"FabView JSON bytes: {summary['json_round_trip_bytes']}")
print(f"Wrote annotated SVG: {outputs['annotated_svg']}")
print(f"Wrote virtual SVG: {outputs['virtual_layers_svg']}")
if __name__ == "__main__":
main()