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

Fab & FabView

Fab and FabView are the unified PCB fabrication and board-rendering surface in altium-monkey. Call board.fab(...) (or Fab(board, ...)) to create a Fab context once, then emit Gerber X2/X1, NC Drill, IPC-2581B, PCB SVG, Pick and Place CSV, and PCB BOM CSV — or query the normalized board geometry directly with fab.view(...).

Why FabView Exists

Before FabView, each PCB output (SVG, Gerber, IPC-2581, Pick and Place, BOM) re-interpreted .PcbDoc records on its own code path. Rules, pad stacks, solder-mask expansions, plane reliefs, panel copies, special strings, and TrueType fonts could subtly diverge between a board's SVG preview, its Gerbers, and its IPC-2581 package.

FabView fixes this by normalizing the board once through Altium's own rules and sharing that draw stage across every output of a Fab instance:

text
                  ┌────────────────────┐
                  │    AltiumPcbDoc    │
                  │  + PrjPcb / Fonts  │
                  └─────────┬──────────┘
                            │  board.fab(**context)
                            ▼
                  ┌────────────────────┐
                  │   Shared FabView   │
                  │ (rules, stackup,   │
                  │  lands, pours,     │
                  │  planes, fonts,    │
                  │  variants, copies) │
                  └───┬───┬───┬───┬───┬┘
     ┌────────────────┘   │   │   │   └────────────────┐
     ▼                    ▼   ▼   ▼                    ▼
to_gerbers()      to_nc_drill() to_ipc2581()       to_svg() /
(Gerber X2/X1)    (Excellon +   (IPC-2581B       to_layer_svgs()
                   board rout)   .cvg XML)       to_pnp() / to_bom()

Key design rules:

  1. Single draw stage: Every writer formats normalized FabView data; no writer re-reads .PcbDoc records or computes its own expansions.
  2. Shared work: Calling fab.to_gerbers(), fab.to_nc_drill(), fab.to_ipc2581(), and fab.to_svg() on the same Fab reuses one draw of the board.
  3. In-memory first: Every to_* method returns a FabOutput in memory. Nothing touches disk until you call output.write(directory).
  4. Best-effort on real boards: Unresolved special strings, missing fonts, or unsupported geometry are recorded in output.diagnostics while the rest of the board still writes. Caller errors (invalid options, missing input files, or existing target files without overwrite=True) still raise.
  5. Designed for future formats (ODB++ planned): ODB++ export is planned for a future release and is not included in this release. FabView was intentionally designed with ODB++ in mind — normalized stackups, plane films, padstacks, component packages, nets, drill spans, and panel step trees are already modeled in the view so the upcoming ODB++ writer will lower directly from the same shared FabView alongside Gerber, NC Drill, and IPC-2581B.

Quick Start

python
from altium_monkey import AltiumPcbDoc

board = AltiumPcbDoc.from_file("board.PcbDoc")

# Tier 1: fix board inputs once (auto-discovers the PrjPcb listing this board)
fab = board.fab(variant="A")

# Tier 2: emit multiple outputs from the same shared draw
gerbers = fab.to_gerbers()
drill = fab.to_nc_drill()
ipc = fab.to_ipc2581(merge_net_ties=True)
svg = fab.to_svg(hidden_component_texts="draw")
pnp = fab.to_pnp(units="mm")
bom = fab.to_bom()

# Inspect diagnostics before writing
for diag in gerbers.diagnostics:
    print(diag.severity, diag.code, diag.message)

# Write to disk (raises FileExistsError if a file already exists unless overwrite=True)
gerbers.write("out/gerber")
drill.write("out/gerber")
ipc.write("out/ipc2581")
svg.write("out/svg")
pnp.write("out/assembly")
bom.write("out/assembly")

For single-output scripts, AltiumPcbDoc provides one-call shortcuts that accept Tier 1 (ContextOptions) and Tier 2 output keywords together:

Fab(board, **context) accepts the same Tier 1 keyword options as board.fab(**context).

Tier 1 Context Options (board.fab(...))

All options are keyword-only. An unknown keyword raises TypeError; an invalid value raises ValueError.

OptionDefaultMeaning
projectauto-discoveredPath to .PrjPcb; when omitted, searches the board's folder and parent folders for a .PrjPcb listing the board (fab.project)
parameters{}Project parameter overrides (dict[str, str]) for .Name special strings
variantNoneVariant name; None draws [No Variations]
momentNoneISO 8601 local timestamp for .Print_Date and .Print_Time
build_numberNoneValue for .Application_BuildNumber (AOD-068)
fonts{}TrueType font settings (policy, files, folders, standard_only); see Text & Font Rendering
mask_shapes_without_region"draw"Draw pad mask/paste shapes without a board region (AOD-008); "omit" matches Altium
backdrill_start_lands"draw"Draw back-drill start lands and mask openings (AOD-014); "omit" matches Altium
keepout_texts"omit"Omit Keepout-flagged texts off the Keep-Out layer (AOD-042); "draw" matches Altium
omit_drilled_away_inner_landsFalseOmit inner lands of non-plated pads whose round hole is at least as wide as the land

Inspect fab.project for the resolved .PrjPcb path, fab.context for the decoded context options, and fab.diagnostics for project-discovery warnings (project_not_found, project_ambiguous, project_unreadable).

Working With FabOutput And FabFile

Every to_* method returns a FabOutput, which is a read-only Mapping[str, FabFile] ordered by file name:

python
gerbers = fab.to_gerbers()
print(gerbers.status)  # "written", "partial", or "empty"

for name, file in gerbers.items():
    print(name, file.key, file.role, file.status, file.count, len(file.data))

# Access text directly (decoded with file.encoding: utf-8 by default, cp1252 for PnP/BOM CSVs)
top_gerber = gerbers["board.GTL"].text

# Single-file outputs (to_ipc2581, to_pnp, to_bom) whose filename depends on board stem / variant:
pnp_file = next(iter(fab.to_pnp().values()))
print(pnp_file.name, pnp_file.encoding)  # e.g. "Pick Place for board.csv", "cp1252"
csv_text = pnp_file.text

# Check files intentionally skipped for used layers
for skipped in gerbers.omitted:
    print(skipped.output, skipped.files, skipped.reason)

FabOutput.write(directory, *, overwrite=False) creates directory, checks that no target file exists before writing anything (raising FileExistsError unless overwrite=True), skips status == "unavailable" entries, and returns the written tuple[Path, ...].

Output Guides

Gerber (to_gerbers)

Writes the board's full Gerber file set as Altium's reference OutJob names it (.GTL, .GBL, .G1…, .GP1…, .GTS, .GBS, .GTP, .GBP, .GTO, .GBO, .GM1…, .GKO, .GD1…, .GG1…, .GM profile), plus any requested board-derived virtual layers (.GCU, .GP1T/.GP1B, .GDT/.GDB, .GCT/.GCB, .GLT/.GLB, .GRT/.GRB, .GAT/.GAB, .GADT/.GADB, .GPLT/.GPLB). Defaults conform to Ucamco Gerber Layer Format Specification 2026.05 (X2 attributes on, 6 decimal places of a millimetre — a 1 nm grid, every copper pad flashed).

Key options (GerberOptions from altium_monkey.fab / FabGerberOptions from altium_monkey.fab_view_contracts.generated, plus keyword-only virtual_options):

OptionDefaultMeaning
x2_attributesTrueEmit Gerber X2 %TF/%TA attributes (False writes plain X1, AOD-004)
decimal_digits6Millimetre decimal places (0–9; 4 matches Altium's 100 nm grid)
datum"user""user" (board origin) or "absolute" (source zero)
offset_nm(0, 0)Additional (x, y) output offset in nanometres
stemboard stemFile name stem
same_coordinatesauto GUIDShared .SameCoordinates GUID across the file set
creation_datenow (UTC)ISO 8601 timestamp with timezone for .CreationDate
degenerate_strokes"draw""draw" emits zero-length strokes as disks (AOD-001); "omit" matches Altium
unconnected_inner_lands"draw"Currently only "draw" is supported ("omit" raises ValueError pending reference captures)
keepoutTrueEmit the Keep-Out layer film (.GKO)
profileTrueEmit the board profile film (.GM)
pad_mastersTrueEmit top/bottom pad master films (.GPT, .GPB)
drill_guideTrueEmit per-drill-pair drill guide films (.GG<n>)
drill_drawingTrueEmit per-drill-pair drill drawing films (.GD<n>)
mechanical_layersAltium OutJob plot setAbsent reproduces Altium's Mechanical 1..32 plot set; [] writes none; ["used"] writes every enabled/used mechanical layer; explicit selectors (["MECHANICAL8", "GM13", "15"]) write only those layers
extensions{}Dual-key custom extension overrides (dict[str, str]): keys accept either canonical FabView layer keys ("TOP", "PROFILE", "KEEPOUT", "MECHANICAL8", "MID1", "PLANE1", "DRILLGUIDE1", "CUTOUTS") or Altium default extensions ("GTL", "GM", "GKO", "GM8", "G1", "GP1", "GG1", "GCU"); leading . is stripped
virtual_layers()Additional virtual layers to lower as Gerber files (all 17 canonical keys: "CUTOUTS", "PIN1_TOP/BOTTOM" or alias "POLARITY_TOP/BOTTOM", "DIODES_TOP/BOTTOM", "CAPACITORS_TOP/BOTTOM", "INDUCTORS_TOP/BOTTOM", "RESISTORS_TOP/BOTTOM", "ASSEMBLY_OUTLINES_TOP/BOTTOM", "ASSEMBLY_DESIGNATORS_TOP/BOTTOM", "PAD_LABELS_TOP/BOTTOM")
profile_cutoutsFalseDraw hatched "CUTOUT" callout labels directly on the .GM profile film instead of solid-filling interior cutouts
virtual_optionsNoneOptional VirtualLayerOptions configuring fonts (font_mode, stroke_font, font_family), visibility, cutouts, Pin 1 styles & knockout, diodes, capacitors, inductors, resistors, assembly outlines, assembly designators, and pad labels (see Virtual Fab Layers)
python
from altium_monkey.fab import CutoutLayerOptions, VirtualLayerOptions

gerbers = fab.to_gerbers(
    keepout=True,
    profile=True,
    pad_masters=False,
    drill_guide=False,
    drill_drawing=True,
    mechanical_layers=["used"],
    extensions={
        "PROFILE": "GKO_OUTLINE",  # canonical FabLayerKey
        "GTO": "GTO_TOP_SILK",     # Altium default extension key
        "CUTOUTS": "GCU",          # virtual layer key
    },
    virtual_layers=("CUTOUTS", "PIN1_TOP", "DIODES_TOP", "ASSEMBLY_OUTLINES_TOP"),
    profile_cutouts=True,
    virtual_options=VirtualLayerOptions(
        cutouts=CutoutLayerOptions(hatch_pitch_mm=1.0, label="CUTOUT"),
    ),
)

See the Gerber contract for attribute rules, pad aperture forms, and region contour hygiene, and Virtual Fab Layers for full VirtualLayerOptions details.

NC Drill (to_nc_drill)

Writes Excellon drill files per drill pair (.TXT / .TX1… split by plated and non-plated, round, slot, square, rect, and counterhole files) and the board-edge rout when enabled.

Key options (NcDrillOptions):

OptionDefaultMeaning
stemboard stemFile name stem
datum"user""user" or "absolute"
offset_nm(0, 0)Additional (x, y) offset in nanometres
decimal_digits4Millimetre decimal places (Altium's 4:4 grid)
board_edge_routTrueEmit board-edge rout file (from the view's ROUT key; role="board_edge_rout")
board_edge_rout_tool5080000Board-edge rout tool diameter in nm (Altium's 200 mil default)

Each drill FabFile sets role ("round", "slot", "square", "rect", "board_edge_rout", "counterhole"), plated, and span (layer-name pair).

IPC-2581B (to_ipc2581)

Writes a single schema-valid IPC-2581 Rev B XML document (<stem>.cvg) from the board's saved-geometry FabView, preserving native contours with cutouts, stroke line caps, per-owner padstacks, packages, <Bom>/<Avl> BOM items, non-electrical document layers (KEEPOUT, MECHANICAL<n>, DRILLDRAWING<n>), and multi-level StepRepeat panel steps.

Key options (Ipc2581Options from altium_monkey.fab / FabIpc2581Options from altium_monkey.fab_view_contracts.generated, plus keyword-only virtual_options):

OptionDefaultMeaning
stemboard stemOutput file stem (<stem>.cvg) and root step name
creation_datenow (UTC)ISO 8601 history timestamp with timezone
degenerate_strokes"draw""draw" (AOD-001) or "omit"
outline_arcs"exact"Slot cavity arcs: "exact" true arcs or "altium_chords"
merge_net_tiesFalseMerge nets joined by Net Ties (Altium's MergeNetTieNets)
negative_standoffs"zero""zero" clamps negative standoffs to 0 for schema validity (AOD-021); "as_saved" matches Altium
edge_cutouts"fold"Cutouts touching/crossing the board edge: "fold" as notches (AOD-071), "drop" (matches Altium), or "saved"
bom_rulesAltium IPC-2581 rulesBOM grouping, $Name field templates, characteristics, bom toggle, and populate flag (partial dicts accepted)
panelAltium panel rulesPanel copy inclusion and copy designator format (partial dicts accepted)
document_layersall non-emptyNon-electrical DOCUMENT layers to include (KEEPOUT, MECHANICAL<n>, DRILLDRAWING<n>): omit for all non-empty document layers, [] for none, or pass an explicit list of keys
virtual_layers()Additional virtual layers written as <Layer> + <LayerFeature> outside <StackupGroup>: "CUTOUTS" (DOCUMENT, side ALL) and sixteen sided layers (PIN1_*/POLARITY_*, DIODES_*, CAPACITORS_*, INDUCTORS_*, RESISTORS_*, ASSEMBLY_OUTLINES_*, ASSEMBLY_DESIGNATORS_*, PAD_LABELS_* as ASSEMBLY, side TOP/BOTTOM)
virtual_optionsNoneOptional VirtualLayerOptions configuring virtual layers (see Virtual Fab Layers)

Customizing IPC-2581 BOM, Document Layers, And Virtual Layers

bom_rules accepts a FabBomRules instance (from altium_monkey.fab_view_contracts.generated) or a partial dict (omitted fields keep Altium's defaults). Any $Name template resolves component properties ($DesignItemId, $LibraryName, $Footprint, $Package, $FootprintDescription, $Description, $Comment) or case-insensitive component parameters. When the board has no components or bom=False, <Bom> and <Avl> are omitted to keep the document strictly schema-valid. Virtual layers passed in virtual_layers are emitted outside <StackupGroup> whenever non-empty:

python
from altium_monkey.fab import VirtualLayerOptions

# Emit custom OEM/MPN fields, selected document layers, and virtual assembly layers
ipc = fab.to_ipc2581(
    bom_rules={
        "design_number": "$MPN",
        "part_number": "$InternalPN",
        "characteristics": ["MPN", "Manufacturer"],
        "populate": True,
    },
    document_layers=["KEEPOUT", "MECHANICAL1"],
    virtual_layers=("CUTOUTS", "PIN1_TOP", "DIODES_TOP", "ASSEMBLY_OUTLINES_TOP"),
    virtual_options=VirtualLayerOptions(),
)

# Omit <Bom>/<Avl> and all optional document layers
minimal_ipc = fab.to_ipc2581(bom_rules={"bom": False}, document_layers=[])

PCB & Footprint SVG (to_svg, to_layer_svgs)

Draws either one composite board image (board.svg) or one aligned image per layer key (<KEY>.svg plus DRILLS.svg) in millimetres. Both methods accept any virtual layer key inside layers=(...) along with virtual_options=VirtualLayerOptions(...) (supporting monochrome and shaded + contrast-halo rendering). AltiumPcbFootprint exposes the same to_svg and to_layer_svgs methods (plus parameters via FootprintSvgOptions).

Key options (SvgOptions, plus keyword-only virtual_options):

OptionDefaultMeaning
layersall board keysOrdered layer keys to draw/image ("PROFILE" for board outline, "DRILLS" for holes, plus any virtual layer key such as "DIODES_TOP", "PIN1_TOP"/"POLARITY_TOP", "CAPACITORS_TOP", "INDUCTORS_TOP", "RESISTORS_TOP", "CUTOUTS", "ASSEMBLY_OUTLINES_TOP", "ASSEMBLY_DESIGNATORS_TOP", "PAD_LABELS_TOP")
layer_colours{}Override colours by layer key ("#rrggbb"); applies to monochrome layers and monochrome virtual layers
scale1.0Display size per millimetre
hidden_component_texts"omit""omit" hides NAMEON/COMMENTON-hidden texts; "draw" draws them
degenerate_strokes"draw""draw" or "omit"
mirrorFalseMirror left-to-right about the frame centre (bottom view)
clip_to_outlineFalseClip each layer to the board profile less its cutouts
clip_holesFalseKnock spanned drill holes out of each copper layer
metadataFalseEmit data-kind, data-id, data-net, data-source on elements
annotations[]Overlays drawn above layers: [{"kind": "pad_labels"}, {"kind": "origin_marker"}]
virtual_optionsNoneOptional VirtualLayerOptions controlling virtual layer geometry, text font mode, and shaded vs. monochrome styling (see Virtual Fab Layers)

See the SVG contract for coordinate conventions, layer ordering, and annotation markup.

Pick & Place (to_pnp) And PCB BOM (to_bom)

Panels And Embedded Board Arrays

Fab and FabView compose Altium panel .PcbDoc files containing EmbeddedBoards6 arrays across Gerber, NC drill, IPC-2581B, PCB SVG, Pick & Place, and PCB BOM.

Child Board Resolution

For each embedded board array, FabView searches for the child .PcbDoc in two locations, in order:

  1. Beside the panel file (panel_path.parent / stored_name for stored Windows-absolute paths, or panel_path.parent / relative_path for relative paths).
  2. At the stored Windows-absolute DOCUMENTPATH itself.

Flattened Copies vs. StepRepeat

Panel Assembly Options (panel={...})

to_pnp, to_bom, and to_ipc2581 accept a panel option (PanelOptions / FabPanelOptions from altium_monkey.fab) controlling copy inclusion and copy designator formatting. You can pass a FabPanelOptions instance or a partial dict — omitted keys take Altium's defaults (copies_in_pnp=True, copies_in_bom=False, copy_designators="same"):

python
pnp = fab.to_pnp(panel={"copy_designators": "$Component_$CopyIndex"})
bom = fab.to_bom(panel={"copies_in_bom": True})

Supported copy_designators template tokens are $Component, $ComponentPrefix, $ComponentIndex, $CopyIndex, $CopyRow, $CopyColumn, $CopyAlpha, $ArrayIndex, and $BoardName. Copy components remain fitted=True (panel project variants do not apply to child board copies).

For inspecting and authoring EmbeddedBoards6 records directly, see Embedded Board Arrays in PcbDoc and the pcbdoc_embedded_board_panel example.

Custom Lowerings With fab.view()

When building your own exporter, DRC check, or viewer, request a FabView directly:

python
from altium_monkey import AltiumPcbDoc, FabView

board = AltiumPcbDoc.from_file("board.PcbDoc")
view = board.fab().view(geometry="saved", copies="flatten", variant="applied")

for row in view.layers():
    items = view.layer(row.key)
    lands = items.lands or ()
    strokes = items.strokes or ()
    areas = items.areas or ()
    print(f"{row.key:16s} ({row.role}): {len(lands)} lands, {len(strokes)} strokes, {len(areas)} areas")

# Round-trip the view as validated altium_monkey.fab_view.a0 JSON
raw_json = view.to_json()
reloaded = FabView.from_json(raw_json)

# Or read a saved dump from disk
# reloaded = FabView.from_file("fab_view.json")

View Switches & Output Usage Table

Each to_* method selects the switches required by its target format. Pass the same switches to fab.view(...) when building a custom lowering:

Outputgeometrycopiesvariant / variationsWhy
Gerber"plotted""flatten""fabrication" / "unique_id"Gerber regions must be simple; strokes use round apertures; Altium flattens one panel level (AOD-043)
NC Drill"plotted""flatten""fabrication" / "unique_id"Shares the Gerber draw; drills every panel copy
SVG"plotted""flatten""fabrication" / "unique_id"Simple regions guarantee SVG even-odd fill matches non-zero fill
IPC-2581"saved""steps""fabrication" / "unique_id"Native contours with cutouts and stroke caps; nested StepRepeat
Pick & Place"saved""flatten""applied" / "designator"Variant always applies; parameter variations match by designator
PCB BOM"saved""flatten""applied" / "unique_id"Variant always applies; parameter variations match by UniqueId
fab.view() default"saved""flatten""applied" / "unique_id"Caller-configurable via ViewOptions

Layer Keys

view.layers() returns the board's layer matrix in Altium's IPC-2581 order. Pass any key to view.layer(key) (a key the board lacks returns empty FabLayerItems with no error):

KeyRoleNotes
TOP, MID<n>, BOTTOMconductorReal copper layers
PLANE<n>conductor (negative)Internal plane negative film (areas + clears)
PLANE<n>COPPERplane_copperVirtual positive plane copper derived once from the film
TOPSOLDER, BOTTOMSOLDER, TOPPASTE, BOTTOMPASTEsolder_mask, pasteMain mask and paste films
TOPSOLDER<n>, TOPPASTE<n>, …solder_mask, pasteNumbered rigid-flex substack films
TOPSOLDERCOVER, BOTTOMSOLDERCOVERmask_coverVirtual mask cover film (board dark, openings and open bores clear)
TOPOVERLAY, BOTTOMOVERLAYsilkscreenSilkscreen overlay layers
MECHANICAL<n>, KEEPOUTmechanical, keepoutMechanical layers (including coverlay outlines 64530+) and Keep-Out
DIELECTRIC<n>dielectricVirtual stackup dielectric rows (no drawn items)
TOPPADMASTER, BOTTOMPADMASTERpad_masterVirtual pad-master layers
DRILLGUIDE<n>, DRILLDRAWING<n>drill_guide, drill_drawingVirtual per-drill-pair guide and drawing films
PROFILEprofileVirtual board outline film
ROUTroutVirtual board-edge rout toolpaths
CUTOUTS, PIN1_*, DIODES_*, CAPACITORS_*, INDUCTORS_*, RESISTORS_*, ASSEMBLY_OUTLINES_*, ASSEMBLY_DESIGNATORS_*, PAD_LABELS_*virtualOn-demand board-derived virtual layers (all 17 canonical keys, see Virtual Fab Layers); also queryable via view.layer(key) with defaults or view.virtual_layer(key, options)

Core Query Methods On FabView

QueryReturnsNotes
context()FabViewContextResolved switches, options, project, BOM/panel rules
board()FabBoardStep ID ("s0"), file identity + SHA-256, user origin (nm)
layers() / layer(key)tuple[FabLayer, ...] / FabLayerItemsLayer matrix and per-key lands, strokes, areas, clears, texts, routs (computes on-demand virtual keys with defaults)
virtual_layer(key, options=None)VirtualLayerResultCompute a virtual layer with explicit VirtualLayerOptions; call .to_fab_layer_items() for canonical FabLayerItems
holes() / counterholes() / drill_pairs()tuplesDrilled holes, counterbores/countersinks, drill-pair spans
profile()FabProfile | NoneBoard outer ring and cutouts (each with optional record source)
components() / placements() / packages()tuplesFull component+package view, or fast record-only placements() without package synthesis
owners() / padstacks()tuplesPer-pad/via owners and deduplicated padstack definitions
nets()tuple[FabNet, ...]Active nets, net classes, net-tie groups, optional merged names
stackup() / regions() / appearance()stackup / regions / coloursPhysical stackup + service substacks, board regions/cavities/bends
bodies() / models() / model_bytes(id)3D bodies & STEP bytesDecompressed STEP payloads (see also fab_step_model_bytes, fab_model_bytes)
repeats() / child(step)panel repeats & child viewsEmbedded board array repeats and per-child FabView
bom() / fonts()BOM lines / FabFontReportGrouped BOM lines and TrueType font resolution report
diagnostics(scope)tuple[FabDiagnostic, ...]Pass any layer key or board scope ("holes", "profile", "board", "fonts", "components", "packages", "bodies", "bom")
to_json(layers=None) / from_json(data) / from_file(path)bytes / FabViewValidated altium_monkey.fab_view.a0 dump serialization and reload

Practical Notes For Python Users

Runnable Examples

altium-monkey v2026.11.26 · gobblerito·Docs updated 2026.11.29 17:55 UTC (0665053)