Skip to content

Renderers API

build123d_techdraw.renderers.svg

Vector SVG renderer with CSS custom variables and theme switching.

SVGRenderer

Renders DrawingSheet instances to interactive and print-ready SVG vector graphics.

Source code in src/build123d_techdraw/renderers/svg.py
class SVGRenderer:
    """Renders DrawingSheet instances to interactive and print-ready SVG vector graphics."""

    @classmethod
    def render_sheet(cls, sheet: "DrawingSheet", theme: Theme = Theme.DARK_BLUEPRINT) -> str:
        """Render sheet to SVG XML string."""
        return sheet.to_svg(theme=theme)

    @classmethod
    def save(
        cls, sheet: "DrawingSheet", output_path: str, theme: Theme = Theme.DARK_BLUEPRINT
    ) -> None:
        """Save rendered sheet to an SVG file."""
        os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
        svg_content = cls.render_sheet(sheet, theme=theme)
        with open(output_path, "w", encoding="utf-8") as f:
            f.write(svg_content)

render_sheet(sheet, theme=Theme.DARK_BLUEPRINT) classmethod

Render sheet to SVG XML string.

Source code in src/build123d_techdraw/renderers/svg.py
@classmethod
def render_sheet(cls, sheet: "DrawingSheet", theme: Theme = Theme.DARK_BLUEPRINT) -> str:
    """Render sheet to SVG XML string."""
    return sheet.to_svg(theme=theme)

save(sheet, output_path, theme=Theme.DARK_BLUEPRINT) classmethod

Save rendered sheet to an SVG file.

Source code in src/build123d_techdraw/renderers/svg.py
@classmethod
def save(
    cls, sheet: "DrawingSheet", output_path: str, theme: Theme = Theme.DARK_BLUEPRINT
) -> None:
    """Save rendered sheet to an SVG file."""
    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    svg_content = cls.render_sheet(sheet, theme=theme)
    with open(output_path, "w", encoding="utf-8") as f:
        f.write(svg_content)

build123d_techdraw.renderers.pdf

High-precision multi-page vector PDF export with native PDF 1.4 streaming and raster image support.

PDFRenderer

Renders vector technical drawings and embedded raster views to multi-page PDF documents.

Source code in src/build123d_techdraw/renderers/pdf.py
class PDFRenderer:
    """Renders vector technical drawings and embedded raster views to multi-page PDF documents."""

    @classmethod
    def _render_svg_to_ax(
        cls,
        ax: Any,
        svg_code: str,
        width_mm: float,
        height_mm: float,
        colors: ThemeColors,
    ) -> None:
        """Render parsed SVG vector paths, text, and embedded raster images onto a Matplotlib Axes."""
        ax.set_xlim(0, width_mm)
        ax.set_ylim(0, height_mm)
        ax.axis("off")

        # Explicit background canvas
        ax.add_patch(
            patches.Rectangle((0, 0), width_mm, height_mm, facecolor=colors.bg, edgecolor="none")
        )

        scene_items = _parse_svg_scene(svg_code, height_mm, colors)
        for item in scene_items:
            if isinstance(item, _VectorItem):
                mpl_path = _path_cmds_to_mpl_path(item.commands)
                if mpl_path is None:
                    continue
                ls: Any = (0, item.dash_pt) if item.dash_pt else "-"
                patch = patches.PathPatch(
                    mpl_path,
                    facecolor=item.fill or "none",
                    edgecolor=item.stroke or "none",
                    linewidth=item.linewidth_pt,
                    linestyle=ls,
                    hatch=item.hatch,
                    alpha=item.fill_alpha if item.fill_alpha is not None else item.stroke_alpha,
                )
                ax.add_patch(patch)
                if item.clip_paths:
                    cp_path = _path_cmds_to_mpl_path(item.clip_paths[-1])
                    if cp_path is not None:
                        patch.set_clip_path(cp_path, transform=ax.transData)

            elif isinstance(item, _ImageItem):
                decoded = _decode_image_href(item.href)
                if decoded is None:
                    continue
                _, img = decoded
                rgba = img.convert("RGBA")
                px_w, px_h = rgba.size
                fx, fy, fw, fh = _fit_image_rect(
                    item.x,
                    item.y,
                    item.width,
                    item.height,
                    px_w,
                    px_h,
                    item.preserve_aspect_ratio,
                )
                bl_sx, bl_sy = _mat_apply(item.transform, fx, fy + fh)
                br_sx, br_sy = _mat_apply(item.transform, fx + fw, fy + fh)
                tl_sx, tl_sy = _mat_apply(item.transform, fx, fy)

                bl_x, bl_y = bl_sx, height_mm - bl_sy
                br_x, br_y = br_sx, height_mm - br_sy
                tl_x, tl_y = tl_sx, height_mm - tl_sy

                if abs(br_y - bl_y) < 1e-6 and abs(tl_x - bl_x) < 1e-6:
                    im_artist = ax.imshow(
                        np.asarray(rgba),
                        extent=(bl_x, br_x, bl_y, tl_y),
                        origin="upper",
                        interpolation="antialiased",
                        alpha=item.opacity,
                        clip_on=True,
                        zorder=1,
                    )
                else:
                    affine = mtransforms.Affine2D.from_values(
                        br_x - bl_x,
                        br_y - bl_y,
                        tl_x - bl_x,
                        tl_y - bl_y,
                        bl_x,
                        bl_y,
                    )
                    im_artist = ax.imshow(
                        np.asarray(rgba),
                        extent=(0.0, 1.0, 0.0, 1.0),
                        origin="upper",
                        interpolation="antialiased",
                        transform=affine + ax.transData,
                        alpha=item.opacity,
                        clip_on=True,
                        zorder=1,
                    )
                if item.clip_paths:
                    cp_path = _path_cmds_to_mpl_path(item.clip_paths[-1])
                    if cp_path is not None:
                        im_artist.set_clip_path(cp_path, transform=ax.transData)

            elif isinstance(item, _TextItem):
                bbox_props = (
                    {
                        "boxstyle": "square,pad=0.15",
                        "facecolor": item.knockout_bg,
                        "edgecolor": "none",
                    }
                    if item.knockout_bg
                    else None
                )
                txt_artist = ax.text(
                    item.x_mm,
                    item.y_mm,
                    item.text,
                    color=item.color,
                    fontsize=item.fontsize_pt,
                    fontweight="bold" if item.bold else "normal",
                    ha=item.ha,
                    va=item.va,
                    rotation=item.rotation_deg,
                    rotation_mode="anchor",
                    bbox=bbox_props,
                )
                if item.clip_paths:
                    cp_path = _path_cmds_to_mpl_path(item.clip_paths[-1])
                    if cp_path is not None:
                        txt_artist.set_clip_path(cp_path, transform=ax.transData)

    @staticmethod
    def _parse_svg_length_mm(raw: str) -> float | None:
        """Convert an SVG length attribute (mm/cm/in/pt/px/unitless) to mm, rejecting '%'."""
        m = re.match(r"^\s*([-+]?\d*\.?\d+)\s*([a-zA-Z%]*)\s*$", raw)
        if not m:
            return None
        val = float(m.group(1))
        unit = m.group(2).lower()
        if unit == "%":
            return None
        unit_scale = {
            "": 1.0,
            "mm": 1.0,
            "cm": 10.0,
            "in": 25.4,
            "pt": 25.4 / 72.0,
            "pc": 25.4 / 6.0,
            "px": 25.4 / 96.0,
        }
        factor = unit_scale.get(unit)
        return val * factor if factor is not None else None

    @classmethod
    def _parse_svg_dimensions_mm(cls, svg_code: str) -> tuple[float, float]:
        """Extract (width_mm, height_mm) from the root <svg> tag or viewBox, defaulting to A4."""
        root_m = re.search(r"<svg\b([^>]*)>", svg_code, re.IGNORECASE)
        if root_m:
            attrs = root_m.group(1)
            w_m = re.search(r'\bwidth\s*=\s*["\']([^"\']+)["\']', attrs, re.IGNORECASE)
            h_m = re.search(r'\bheight\s*=\s*["\']([^"\']+)["\']', attrs, re.IGNORECASE)
            if w_m and h_m:
                w_mm = cls._parse_svg_length_mm(w_m.group(1))
                h_mm = cls._parse_svg_length_mm(h_m.group(1))
                if w_mm is not None and h_mm is not None:
                    return w_mm, h_mm
            vb_m = re.search(
                r'\bviewBox\s*=\s*["\']\s*[-+]?\d*\.?\d+[\s,]+[-+]?\d*\.?\d+[\s,]+([-+]?\d*\.?\d+)[\s,]+([-+]?\d*\.?\d+)',
                attrs,
                re.IGNORECASE,
            )
            if vb_m:
                return float(vb_m.group(1)), float(vb_m.group(2))
        return (297.0, 210.0)

    @classmethod
    def _coerce_sheet_input(
        cls,
        item: SheetInput,
        theme: Theme,
    ) -> tuple[float, float, str]:
        """Normalize a tuple, DrawingSheet, SVG path, or SVG string into (width_mm, height_mm, svg_str)."""
        # Runtime import: core.sheet imports this module lazily for export_pdf().
        from build123d_techdraw.core.sheet import DrawingSheet

        if isinstance(item, tuple) and len(item) == 3:
            return (float(item[0]), float(item[1]), str(item[2]))
        if isinstance(item, DrawingSheet):
            return (item.width_mm, item.height_mm, item.to_svg(theme=theme))
        if isinstance(item, (str, os.PathLike)):
            path_or_svg = os.fspath(item)
            if os.path.isfile(path_or_svg):
                with open(path_or_svg, encoding="utf-8") as f:
                    svg_code = f.read()
            else:
                svg_code = path_or_svg
            w_mm, h_mm = cls._parse_svg_dimensions_mm(svg_code)
            return (w_mm, h_mm, svg_code)
        raise TypeError(
            f"Expected (width_mm, height_mm, svg_str), DrawingSheet, or SVG path/string; got {type(item).__name__}"
        )

    @classmethod
    def render_sheets_to_pdf(
        cls,
        sheets_data: Sequence[SheetInput],
        output_path: str,
        theme: Theme = Theme.DARK_BLUEPRINT,
        bookmarks: bool = False,
        booklet_title: str = "ENGINEERING DRAWINGS",
        sheet_titles: list[str] | None = None,
    ) -> None:
        """Render multiple sheets (tuples, DrawingSheets, or SVG paths/strings) to a multi-page PDF."""
        os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
        colors = THEME_COLORS[theme]

        writer = _NativePdfWriter(
            bookmarks=bookmarks,
            booklet_title=booklet_title,
            sheet_titles=sheet_titles,
        )
        for item in sheets_data:
            width_mm, height_mm, svg_code = cls._coerce_sheet_input(item, theme)
            writer.add_page(width_mm, height_mm, svg_code, colors)

        pdf_bytes = writer.to_bytes()
        with open(output_path, "wb") as f:
            f.write(pdf_bytes)

render_sheets_to_pdf(sheets_data, output_path, theme=Theme.DARK_BLUEPRINT, bookmarks=False, booklet_title='ENGINEERING DRAWINGS', sheet_titles=None) classmethod

Render multiple sheets (tuples, DrawingSheets, or SVG paths/strings) to a multi-page PDF.

Source code in src/build123d_techdraw/renderers/pdf.py
@classmethod
def render_sheets_to_pdf(
    cls,
    sheets_data: Sequence[SheetInput],
    output_path: str,
    theme: Theme = Theme.DARK_BLUEPRINT,
    bookmarks: bool = False,
    booklet_title: str = "ENGINEERING DRAWINGS",
    sheet_titles: list[str] | None = None,
) -> None:
    """Render multiple sheets (tuples, DrawingSheets, or SVG paths/strings) to a multi-page PDF."""
    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    colors = THEME_COLORS[theme]

    writer = _NativePdfWriter(
        bookmarks=bookmarks,
        booklet_title=booklet_title,
        sheet_titles=sheet_titles,
    )
    for item in sheets_data:
        width_mm, height_mm, svg_code = cls._coerce_sheet_input(item, theme)
        writer.add_page(width_mm, height_mm, svg_code, colors)

    pdf_bytes = writer.to_bytes()
    with open(output_path, "wb") as f:
        f.write(pdf_bytes)

build123d_techdraw.renderers.dxf

1:1 DXF flat pattern and multi-layer full drawing sheet export using ezdxf.

DXFRenderer

Exports 2D CAD views and complete drawing sheets to standard multi-layer DXF files.

Source code in src/build123d_techdraw/renderers/dxf.py
class DXFRenderer:
    """Exports 2D CAD views and complete drawing sheets to standard multi-layer DXF files."""

    @classmethod
    def export_shape_to_dxf(
        cls,
        shape: Shape[Any],
        output_path: str,
        dxfversion: str = "R2010",
        plane: bd.Plane | None = None,
        tolerance: float = 0.05,  # noqa: ARG003
        strict: bool = False,
    ) -> None:
        """Export 2D cross-section, flat pattern, or 3D plate primary face to a 1:1 DXF file."""
        os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
        exporter = bd.ExportDXF(version=dxfversion, unit=bd.Unit.MM)
        exporter.add_layer("VISIBLE", color=ColorIndex.BLACK)
        exporter.add_layer("HIDDEN", color=ColorIndex.GRAY, line_type=bd.LineType.DASHED)
        exporter.add_layer("CENTER", color=ColorIndex.CYAN, line_type=bd.LineType.CENTER)

        target_shape = shape
        active_plane = plane
        if active_plane is None:
            target_shape, active_plane = _detect_primary_flat_face(shape)

        edges = target_shape.edges()
        for idx, edge in enumerate(edges):
            try:
                projected = active_plane.to_local_coords(edge) if active_plane is not None else edge
                if not isinstance(projected, Shape):
                    raise TypeError(f"Expected a projected Shape, got {type(projected).__name__}")
                exporter.add_shape(projected, layer="VISIBLE")
            except Exception as exc:
                if strict:
                    raise
                warnings.warn(
                    f"Failed to export edge {idx} to DXF: {exc}",
                    RuntimeWarning,
                    stacklevel=2,
                )

        exporter.write(output_path)

    @classmethod
    def export_sheet_to_dxf(
        cls,
        sheet: DrawingSheet,
        output_path: str,
        dxfversion: str = "R2010",
    ) -> None:
        """Export the complete composed drawing sheet with standard CAD layers to DXF."""
        os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
        doc: Drawing = new_dxf_document(dxfversion=dxfversion)
        msp = doc.modelspace()

        # Define standard CAD layers and colors (AutoCAD ACI colors)
        layers_cfg = [
            ("BORDER", 7, "CONTINUOUS"),  # White/Black
            ("TITLE_BLOCK", 7, "CONTINUOUS"),  # White/Black
            ("VISIBLE", 7, "CONTINUOUS"),  # White/Black
            ("HIDDEN", 8, "DASHED"),  # Gray
            ("CENTER", 4, "CENTER"),  # Cyan
            ("DIMENSIONS", 2, "CONTINUOUS"),  # Yellow
            ("ANNOTATIONS", 3, "CONTINUOUS"),  # Green
            ("HATCH", 9, "CONTINUOUS"),  # Light Gray
            ("THREADS", 6, "CONTINUOUS"),  # Magenta (ISO 6410-1 cosmetic threads)
            ("BEND_UP", 3, "DASHED"),  # Green
            ("BEND_DOWN", 2, "DASHED"),  # Yellow
            ("BEND_TANGENT", 8, "DASHED"),  # Gray
            ("PUNCH", 4, "CONTINUOUS"),  # Cyan
        ]
        for name, color, ltype in layers_cfg:
            with contextlib.suppress(Exception):
                doc.layers.new(name=name, dxfattribs={"color": color, "linetype": ltype})

        svg_code = sheet.to_svg()
        h_mm = sheet.height_mm

        doc_svg = se.SVG.parse(io.BytesIO(svg_code.encode("utf-8")))

        for el in doc_svg.elements():
            cls_str = el.values.get("class", "")
            cls_list = cls_str.split() if cls_str else []

            # Skip background fills and text knockouts
            if (
                "sheet-bg" in cls_list
                or "blueprint-grid" in cls_list
                or "bend-knockout" in cls_list
            ):
                continue

            # Layer mapping
            is_hidden = "line-hidden" in cls_list or "layer_hidden" in cls_list
            if not is_hidden:
                is_hidden = has_hidden_ancestor(el)

            if is_hidden:
                target_layer = "HIDDEN"
            elif any(
                c in cls_list
                for c in [
                    "title-bg",
                    "tb-title",
                    "tb-field-label",
                    "tb-field-val",
                    "tb-field-val-bold",
                    "tb-field-val-sm",
                    "template-title-block",
                ]
            ) or has_ancestor_class(el, frozenset({"template-title-block"})):
                target_layer = "TITLE_BLOCK"
            elif any(
                c in cls_list
                for c in ["border-main", "border-sub", "grid-ticks", "zone-text", "template-border"]
            ) or has_ancestor_class(el, frozenset({"template-border", "template-sheet"})):
                target_layer = "BORDER"
            elif any(c in cls_list for c in ["line-center"]):
                target_layer = "CENTER"
            elif any(c in cls_list for c in ["line-bend-up"]):
                target_layer = "BEND_UP"
            elif any(c in cls_list for c in ["line-bend-down"]):
                target_layer = "BEND_DOWN"
            elif any(c in cls_list for c in ["line-bend-tangent"]):
                target_layer = "BEND_TANGENT"
            elif any(c in cls_list for c in ["punch-marker", "punch-tag-text"]):
                target_layer = "PUNCH"
            elif any(c in cls_list for c in ["line-thread", "line-thread-dashed"]):
                target_layer = "THREADS"
            elif any(
                c in cls_list
                for c in [
                    "dim-line",
                    "dim-arrow",
                    "dim-text",
                    "radial-dim",
                    "diameter-dim",
                    "half-diameter-dim",
                    "angular-dim",
                    "ordinate-dim",
                ]
            ):
                target_layer = "DIMENSIONS"
            elif any(
                c in cls_list
                for c in [
                    "leader-note",
                    "leader-text",
                    "bom-balloon",
                    "balloon-text",
                    "gdt-fcf",
                    "datum-symbol",
                    "surface-finish-symbol",
                    "welding-symbol",
                    "notes-text",
                    "view-title",
                    "view-scale",
                    "bend-note-text",
                ]
            ):
                target_layer = "ANNOTATIONS"
            elif any(c in cls_list for c in ["section-hatch-fill", "sectionHatch"]):
                target_layer = "HATCH"
            else:
                target_layer = "VISIBLE"

            if isinstance(el, se.Shape):
                p = se.Path(el)
                p.reify()
                p.approximate_arcs_with_cubics()

                subpaths: list[ezdxf.path.Path] = []
                dxf_path: ezdxf.path.Path | None = None
                for seg in p:
                    if isinstance(seg, se.Move):
                        if dxf_path is not None and len(dxf_path):
                            subpaths.append(dxf_path)
                        dxf_path = ezdxf.path.Path(
                            start=(float(seg.end.x), float(h_mm - seg.end.y))
                        )
                    elif isinstance(seg, se.Line):
                        if dxf_path is None:
                            dxf_path = ezdxf.path.Path(
                                start=(float(seg.start.x), float(h_mm - seg.start.y))
                            )
                        dxf_path.line_to((float(seg.end.x), float(h_mm - seg.end.y)))
                    elif isinstance(seg, se.CubicBezier):
                        if dxf_path is None:
                            dxf_path = ezdxf.path.Path(
                                start=(float(seg.start.x), float(h_mm - seg.start.y))
                            )
                        dxf_path.curve4_to(
                            (float(seg.end.x), float(h_mm - seg.end.y)),
                            (float(seg.control1.x), float(h_mm - seg.control1.y)),
                            (float(seg.control2.x), float(h_mm - seg.control2.y)),
                        )
                    elif isinstance(seg, se.QuadraticBezier):
                        if dxf_path is None:
                            dxf_path = ezdxf.path.Path(
                                start=(float(seg.start.x), float(h_mm - seg.start.y))
                            )
                        dxf_path.curve3_to(
                            (float(seg.end.x), float(h_mm - seg.end.y)),
                            (float(seg.control.x), float(h_mm - seg.control.y)),
                        )
                    elif isinstance(seg, se.Close) and dxf_path is not None:
                        dxf_path.close()
                if dxf_path is not None and len(dxf_path):
                    subpaths.append(dxf_path)
                if subpaths:
                    ezdxf.path.render_splines_and_polylines(
                        msp, subpaths, dxfattribs={"layer": target_layer}
                    )

            elif isinstance(el, se.SVGText):
                txt = el.text
                if txt:
                    pt = se.Point(el.x or 0, el.y or 0) * el.transform
                    x = float(pt.x)
                    y = float(h_mm - pt.y)
                    fs_mm = float(el.font_size or 2.8) * (
                        math.hypot(el.transform.a, el.transform.b) or 1.0
                    )

                    # Extract rotation
                    a, b = el.transform.a, el.transform.b
                    angle_deg = math.degrees(math.atan2(b, a))

                    msp.add_text(
                        txt,
                        dxfattribs={
                            "layer": target_layer,
                            "height": fs_mm,
                            "rotation": angle_deg,
                            "insert": (x, y),
                        },
                    )

        doc.saveas(output_path)

    @classmethod
    def export_flat_pattern_to_dxf(
        cls,
        flat_pattern: FlatPattern,
        output_path: str,
        *,
        include_bend_tangents: bool = False,
        include_etch_labels: bool = True,
        layers: dict[str, str] | None = None,
        dxfversion: str = "R2010",
    ) -> None:
        """Export a 1:1 CNC/laser-cutter DXF from a sheet metal ``FlatPattern``."""
        from build123d_techdraw.recognizers.sheet_metal import BendDirection

        os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
        layer_map = {
            "outer_profile": "CUT_OUTER",
            "inner_holes": "CUT_INNER",
            "bend_up": "BEND_UP",
            "bend_down": "BEND_DOWN",
            "bend_tangent": "BEND_TANGENT",
            "punch": "PUNCH",
            "etch": "ETCH",
        }
        if layers:
            layer_map.update(layers)

        exporter = bd.ExportDXF(version=dxfversion, unit=bd.Unit.MM)
        exporter.add_layer(layer_map["outer_profile"], color=ColorIndex.BLACK)
        exporter.add_layer(layer_map["inner_holes"], color=ColorIndex.RED)
        exporter.add_layer(
            layer_map["bend_up"], color=ColorIndex.GREEN, line_type=bd.LineType.DASHED
        )
        exporter.add_layer(
            layer_map["bend_down"], color=ColorIndex.YELLOW, line_type=bd.LineType.DASHED
        )
        exporter.add_layer(
            layer_map["bend_tangent"], color=ColorIndex.GRAY, line_type=bd.LineType.DASHED
        )
        exporter.add_layer(layer_map["punch"], color=ColorIndex.CYAN)
        exporter.add_layer(layer_map["etch"], color=ColorIndex.MAGENTA)

        for ow in flat_pattern.outer_wires():
            for edge in ow.edges():
                exporter.add_shape(edge, layer=layer_map["outer_profile"])

        for iw in flat_pattern.inner_wires():
            for edge in iw.edges():
                exporter.add_shape(edge, layer=layer_map["inner_holes"])

        msp = exporter._modelspace
        for b in flat_pattern.bends:
            b_layer = (
                layer_map["bend_up"] if b.direction == BendDirection.UP else layer_map["bend_down"]
            )
            msp.add_line(b.start_2d, b.end_2d, dxfattribs={"layer": b_layer})
            if include_bend_tangents:
                msp.add_line(
                    b.tangent1_start_2d,
                    b.tangent1_end_2d,
                    dxfattribs={"layer": layer_map["bend_tangent"]},
                )
                msp.add_line(
                    b.tangent2_start_2d,
                    b.tangent2_end_2d,
                    dxfattribs={"layer": layer_map["bend_tangent"]},
                )
            if include_etch_labels:
                mx, my = b.midpoint_2d
                msp.add_text(
                    b.format_callout(include_tag=True),
                    dxfattribs={
                        "layer": layer_map["etch"],
                        "height": 2.5,
                        "rotation": b.angle_line_deg,
                        "insert": (mx, my),
                    },
                )

        for p in flat_pattern.punches:
            cx, cy = p.center_2d
            arm = 2.5
            msp.add_line((cx - arm, cy), (cx + arm, cy), dxfattribs={"layer": layer_map["punch"]})
            msp.add_line((cx, cy - arm), (cx, cy + arm), dxfattribs={"layer": layer_map["punch"]})
            if include_etch_labels and p.tag:
                msp.add_text(
                    p.tag,
                    dxfattribs={
                        "layer": layer_map["etch"],
                        "height": 2.2,
                        "insert": (cx + 2.0, cy + 1.5),
                    },
                )

        exporter.write(output_path)

export_shape_to_dxf(shape, output_path, dxfversion='R2010', plane=None, tolerance=0.05, strict=False) classmethod

Export 2D cross-section, flat pattern, or 3D plate primary face to a 1:1 DXF file.

Source code in src/build123d_techdraw/renderers/dxf.py
@classmethod
def export_shape_to_dxf(
    cls,
    shape: Shape[Any],
    output_path: str,
    dxfversion: str = "R2010",
    plane: bd.Plane | None = None,
    tolerance: float = 0.05,  # noqa: ARG003
    strict: bool = False,
) -> None:
    """Export 2D cross-section, flat pattern, or 3D plate primary face to a 1:1 DXF file."""
    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    exporter = bd.ExportDXF(version=dxfversion, unit=bd.Unit.MM)
    exporter.add_layer("VISIBLE", color=ColorIndex.BLACK)
    exporter.add_layer("HIDDEN", color=ColorIndex.GRAY, line_type=bd.LineType.DASHED)
    exporter.add_layer("CENTER", color=ColorIndex.CYAN, line_type=bd.LineType.CENTER)

    target_shape = shape
    active_plane = plane
    if active_plane is None:
        target_shape, active_plane = _detect_primary_flat_face(shape)

    edges = target_shape.edges()
    for idx, edge in enumerate(edges):
        try:
            projected = active_plane.to_local_coords(edge) if active_plane is not None else edge
            if not isinstance(projected, Shape):
                raise TypeError(f"Expected a projected Shape, got {type(projected).__name__}")
            exporter.add_shape(projected, layer="VISIBLE")
        except Exception as exc:
            if strict:
                raise
            warnings.warn(
                f"Failed to export edge {idx} to DXF: {exc}",
                RuntimeWarning,
                stacklevel=2,
            )

    exporter.write(output_path)

export_sheet_to_dxf(sheet, output_path, dxfversion='R2010') classmethod

Export the complete composed drawing sheet with standard CAD layers to DXF.

Source code in src/build123d_techdraw/renderers/dxf.py
@classmethod
def export_sheet_to_dxf(
    cls,
    sheet: DrawingSheet,
    output_path: str,
    dxfversion: str = "R2010",
) -> None:
    """Export the complete composed drawing sheet with standard CAD layers to DXF."""
    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    doc: Drawing = new_dxf_document(dxfversion=dxfversion)
    msp = doc.modelspace()

    # Define standard CAD layers and colors (AutoCAD ACI colors)
    layers_cfg = [
        ("BORDER", 7, "CONTINUOUS"),  # White/Black
        ("TITLE_BLOCK", 7, "CONTINUOUS"),  # White/Black
        ("VISIBLE", 7, "CONTINUOUS"),  # White/Black
        ("HIDDEN", 8, "DASHED"),  # Gray
        ("CENTER", 4, "CENTER"),  # Cyan
        ("DIMENSIONS", 2, "CONTINUOUS"),  # Yellow
        ("ANNOTATIONS", 3, "CONTINUOUS"),  # Green
        ("HATCH", 9, "CONTINUOUS"),  # Light Gray
        ("THREADS", 6, "CONTINUOUS"),  # Magenta (ISO 6410-1 cosmetic threads)
        ("BEND_UP", 3, "DASHED"),  # Green
        ("BEND_DOWN", 2, "DASHED"),  # Yellow
        ("BEND_TANGENT", 8, "DASHED"),  # Gray
        ("PUNCH", 4, "CONTINUOUS"),  # Cyan
    ]
    for name, color, ltype in layers_cfg:
        with contextlib.suppress(Exception):
            doc.layers.new(name=name, dxfattribs={"color": color, "linetype": ltype})

    svg_code = sheet.to_svg()
    h_mm = sheet.height_mm

    doc_svg = se.SVG.parse(io.BytesIO(svg_code.encode("utf-8")))

    for el in doc_svg.elements():
        cls_str = el.values.get("class", "")
        cls_list = cls_str.split() if cls_str else []

        # Skip background fills and text knockouts
        if (
            "sheet-bg" in cls_list
            or "blueprint-grid" in cls_list
            or "bend-knockout" in cls_list
        ):
            continue

        # Layer mapping
        is_hidden = "line-hidden" in cls_list or "layer_hidden" in cls_list
        if not is_hidden:
            is_hidden = has_hidden_ancestor(el)

        if is_hidden:
            target_layer = "HIDDEN"
        elif any(
            c in cls_list
            for c in [
                "title-bg",
                "tb-title",
                "tb-field-label",
                "tb-field-val",
                "tb-field-val-bold",
                "tb-field-val-sm",
                "template-title-block",
            ]
        ) or has_ancestor_class(el, frozenset({"template-title-block"})):
            target_layer = "TITLE_BLOCK"
        elif any(
            c in cls_list
            for c in ["border-main", "border-sub", "grid-ticks", "zone-text", "template-border"]
        ) or has_ancestor_class(el, frozenset({"template-border", "template-sheet"})):
            target_layer = "BORDER"
        elif any(c in cls_list for c in ["line-center"]):
            target_layer = "CENTER"
        elif any(c in cls_list for c in ["line-bend-up"]):
            target_layer = "BEND_UP"
        elif any(c in cls_list for c in ["line-bend-down"]):
            target_layer = "BEND_DOWN"
        elif any(c in cls_list for c in ["line-bend-tangent"]):
            target_layer = "BEND_TANGENT"
        elif any(c in cls_list for c in ["punch-marker", "punch-tag-text"]):
            target_layer = "PUNCH"
        elif any(c in cls_list for c in ["line-thread", "line-thread-dashed"]):
            target_layer = "THREADS"
        elif any(
            c in cls_list
            for c in [
                "dim-line",
                "dim-arrow",
                "dim-text",
                "radial-dim",
                "diameter-dim",
                "half-diameter-dim",
                "angular-dim",
                "ordinate-dim",
            ]
        ):
            target_layer = "DIMENSIONS"
        elif any(
            c in cls_list
            for c in [
                "leader-note",
                "leader-text",
                "bom-balloon",
                "balloon-text",
                "gdt-fcf",
                "datum-symbol",
                "surface-finish-symbol",
                "welding-symbol",
                "notes-text",
                "view-title",
                "view-scale",
                "bend-note-text",
            ]
        ):
            target_layer = "ANNOTATIONS"
        elif any(c in cls_list for c in ["section-hatch-fill", "sectionHatch"]):
            target_layer = "HATCH"
        else:
            target_layer = "VISIBLE"

        if isinstance(el, se.Shape):
            p = se.Path(el)
            p.reify()
            p.approximate_arcs_with_cubics()

            subpaths: list[ezdxf.path.Path] = []
            dxf_path: ezdxf.path.Path | None = None
            for seg in p:
                if isinstance(seg, se.Move):
                    if dxf_path is not None and len(dxf_path):
                        subpaths.append(dxf_path)
                    dxf_path = ezdxf.path.Path(
                        start=(float(seg.end.x), float(h_mm - seg.end.y))
                    )
                elif isinstance(seg, se.Line):
                    if dxf_path is None:
                        dxf_path = ezdxf.path.Path(
                            start=(float(seg.start.x), float(h_mm - seg.start.y))
                        )
                    dxf_path.line_to((float(seg.end.x), float(h_mm - seg.end.y)))
                elif isinstance(seg, se.CubicBezier):
                    if dxf_path is None:
                        dxf_path = ezdxf.path.Path(
                            start=(float(seg.start.x), float(h_mm - seg.start.y))
                        )
                    dxf_path.curve4_to(
                        (float(seg.end.x), float(h_mm - seg.end.y)),
                        (float(seg.control1.x), float(h_mm - seg.control1.y)),
                        (float(seg.control2.x), float(h_mm - seg.control2.y)),
                    )
                elif isinstance(seg, se.QuadraticBezier):
                    if dxf_path is None:
                        dxf_path = ezdxf.path.Path(
                            start=(float(seg.start.x), float(h_mm - seg.start.y))
                        )
                    dxf_path.curve3_to(
                        (float(seg.end.x), float(h_mm - seg.end.y)),
                        (float(seg.control.x), float(h_mm - seg.control.y)),
                    )
                elif isinstance(seg, se.Close) and dxf_path is not None:
                    dxf_path.close()
            if dxf_path is not None and len(dxf_path):
                subpaths.append(dxf_path)
            if subpaths:
                ezdxf.path.render_splines_and_polylines(
                    msp, subpaths, dxfattribs={"layer": target_layer}
                )

        elif isinstance(el, se.SVGText):
            txt = el.text
            if txt:
                pt = se.Point(el.x or 0, el.y or 0) * el.transform
                x = float(pt.x)
                y = float(h_mm - pt.y)
                fs_mm = float(el.font_size or 2.8) * (
                    math.hypot(el.transform.a, el.transform.b) or 1.0
                )

                # Extract rotation
                a, b = el.transform.a, el.transform.b
                angle_deg = math.degrees(math.atan2(b, a))

                msp.add_text(
                    txt,
                    dxfattribs={
                        "layer": target_layer,
                        "height": fs_mm,
                        "rotation": angle_deg,
                        "insert": (x, y),
                    },
                )

    doc.saveas(output_path)

export_flat_pattern_to_dxf(flat_pattern, output_path, *, include_bend_tangents=False, include_etch_labels=True, layers=None, dxfversion='R2010') classmethod

Export a 1:1 CNC/laser-cutter DXF from a sheet metal FlatPattern.

Source code in src/build123d_techdraw/renderers/dxf.py
@classmethod
def export_flat_pattern_to_dxf(
    cls,
    flat_pattern: FlatPattern,
    output_path: str,
    *,
    include_bend_tangents: bool = False,
    include_etch_labels: bool = True,
    layers: dict[str, str] | None = None,
    dxfversion: str = "R2010",
) -> None:
    """Export a 1:1 CNC/laser-cutter DXF from a sheet metal ``FlatPattern``."""
    from build123d_techdraw.recognizers.sheet_metal import BendDirection

    os.makedirs(os.path.dirname(os.path.abspath(output_path)), exist_ok=True)
    layer_map = {
        "outer_profile": "CUT_OUTER",
        "inner_holes": "CUT_INNER",
        "bend_up": "BEND_UP",
        "bend_down": "BEND_DOWN",
        "bend_tangent": "BEND_TANGENT",
        "punch": "PUNCH",
        "etch": "ETCH",
    }
    if layers:
        layer_map.update(layers)

    exporter = bd.ExportDXF(version=dxfversion, unit=bd.Unit.MM)
    exporter.add_layer(layer_map["outer_profile"], color=ColorIndex.BLACK)
    exporter.add_layer(layer_map["inner_holes"], color=ColorIndex.RED)
    exporter.add_layer(
        layer_map["bend_up"], color=ColorIndex.GREEN, line_type=bd.LineType.DASHED
    )
    exporter.add_layer(
        layer_map["bend_down"], color=ColorIndex.YELLOW, line_type=bd.LineType.DASHED
    )
    exporter.add_layer(
        layer_map["bend_tangent"], color=ColorIndex.GRAY, line_type=bd.LineType.DASHED
    )
    exporter.add_layer(layer_map["punch"], color=ColorIndex.CYAN)
    exporter.add_layer(layer_map["etch"], color=ColorIndex.MAGENTA)

    for ow in flat_pattern.outer_wires():
        for edge in ow.edges():
            exporter.add_shape(edge, layer=layer_map["outer_profile"])

    for iw in flat_pattern.inner_wires():
        for edge in iw.edges():
            exporter.add_shape(edge, layer=layer_map["inner_holes"])

    msp = exporter._modelspace
    for b in flat_pattern.bends:
        b_layer = (
            layer_map["bend_up"] if b.direction == BendDirection.UP else layer_map["bend_down"]
        )
        msp.add_line(b.start_2d, b.end_2d, dxfattribs={"layer": b_layer})
        if include_bend_tangents:
            msp.add_line(
                b.tangent1_start_2d,
                b.tangent1_end_2d,
                dxfattribs={"layer": layer_map["bend_tangent"]},
            )
            msp.add_line(
                b.tangent2_start_2d,
                b.tangent2_end_2d,
                dxfattribs={"layer": layer_map["bend_tangent"]},
            )
        if include_etch_labels:
            mx, my = b.midpoint_2d
            msp.add_text(
                b.format_callout(include_tag=True),
                dxfattribs={
                    "layer": layer_map["etch"],
                    "height": 2.5,
                    "rotation": b.angle_line_deg,
                    "insert": (mx, my),
                },
            )

    for p in flat_pattern.punches:
        cx, cy = p.center_2d
        arm = 2.5
        msp.add_line((cx - arm, cy), (cx + arm, cy), dxfattribs={"layer": layer_map["punch"]})
        msp.add_line((cx, cy - arm), (cx, cy + arm), dxfattribs={"layer": layer_map["punch"]})
        if include_etch_labels and p.tag:
            msp.add_text(
                p.tag,
                dxfattribs={
                    "layer": layer_map["etch"],
                    "height": 2.2,
                    "insert": (cx + 2.0, cy + 1.5),
                },
            )

    exporter.write(output_path)

build123d_techdraw.renderers.html

Interactive self-contained HTML5 blueprint renderer with live WebGL2 3D CAD viewport.

Combines a full dual-theme 2D DrawingSheet SVG with an embedded, zero-CDN WebGL2 3D CAD inspector synchronized to the sheet's theme, assembly BOM, and camera conventions.

HTMLRenderer

Renders DrawingSheet instances to self-contained interactive 3D-in-2D HTML5 blueprints.

Source code in src/build123d_techdraw/renderers/html.py
class HTMLRenderer:
    """Renders DrawingSheet instances to self-contained interactive 3D-in-2D HTML5 blueprints."""

    @classmethod
    def serialize_sheet_scene(
        cls,
        sheet: DrawingSheet,
        theme: Theme | str = Theme.DARK_BLUEPRINT,
        *,
        shape: Shape[Any] | None = None,
        linear_deflection: float = 0.08,
        angular_deflection: float = 0.25,
        crease_angle_deg: float = 20.0,
    ) -> dict[str, Any]:
        """Tessellate and serialize the sheet's 3D model, parts, BOM, and theme metadata."""
        resolved_theme = _coerce_theme(theme)
        target_shape, iso_bounds = _find_sheet_shape_and_iso_bounds(sheet, override_shape=shape)

        raw_parts: list[
            tuple[
                Shape[Any],
                NDArray[np.float32],
                NDArray[np.float32],
                NDArray[np.uint32],
                NDArray[np.float32],
                tuple[float, float, float],
                tuple[float, float, float],
            ]
        ] = []

        if target_shape is not None:
            components = _extract_components(target_shape)
            for comp in components:
                positions, normals, indices, edges = _tessellate_component(
                    comp,
                    linear_deflection=linear_deflection,
                    angular_deflection=angular_deflection,
                    crease_angle_deg=crease_angle_deg,
                )
                if positions.shape[0] == 0 or indices.size == 0:
                    continue
                p_min = positions.min(axis=0)
                p_max = positions.max(axis=0)
                bmin = (float(p_min[0]), float(p_min[1]), float(p_min[2]))
                bmax = (float(p_max[0]), float(p_max[1]), float(p_max[2]))
                raw_parts.append((comp, positions, normals, indices, edges, bmin, bmax))

        if raw_parts:
            asm_min = (
                min(p[5][0] for p in raw_parts),
                min(p[5][1] for p in raw_parts),
                min(p[5][2] for p in raw_parts),
            )
            asm_max = (
                max(p[6][0] for p in raw_parts),
                max(p[6][1] for p in raw_parts),
                max(p[6][2] for p in raw_parts),
            )
            asm_center = (
                0.5 * (asm_min[0] + asm_max[0]),
                0.5 * (asm_min[1] + asm_max[1]),
                0.5 * (asm_min[2] + asm_max[2]),
            )
            asm_radius = max(
                0.5 * math.dist(asm_min, asm_max),
                1.0,
            )
        else:
            asm_min = (-10.0, -10.0, -10.0)
            asm_max = (10.0, 10.0, 10.0)
            asm_center = (0.0, 0.0, 0.0)
            asm_radius = 15.0

        bboxes = [(p[5], p[6]) for p in raw_parts]
        explode_vectors = _compute_explode_vectors(bboxes, asm_min, asm_max)

        serialized_parts: list[SerializedPartMesh] = []
        total_parts = len(raw_parts)
        for idx, (comp, positions, normals, indices, edges, bmin, bmax) in enumerate(raw_parts):
            bom_item_no, part_no, name, material, qty = _match_component_bom(
                comp, sheet, idx, total_parts
            )
            center = (
                0.5 * (bmin[0] + bmax[0]),
                0.5 * (bmin[1] + bmax[1]),
                0.5 * (bmin[2] + bmax[2]),
            )
            serialized_parts.append(
                SerializedPartMesh(
                    part_id=idx,
                    name=name,
                    bom_item_no=bom_item_no,
                    part_no=part_no,
                    material=material,
                    qty=qty,
                    bbox_min=bmin,
                    bbox_max=bmax,
                    center=center,
                    explode_vector=explode_vectors[idx],
                    vertex_count=int(positions.shape[0]),
                    triangle_count=int(indices.size // 3),
                    edge_segment_count=int(edges.shape[0]),
                    positions_b64=base64.b64encode(positions.tobytes()).decode("ascii"),
                    normals_b64=base64.b64encode(normals.tobytes()).decode("ascii"),
                    indices_b64=base64.b64encode(indices.tobytes()).decode("ascii"),
                    edges_b64=base64.b64encode(edges.tobytes()).decode("ascii"),
                )
            )

        bom_list = [
            {
                "item_no": item.item_no,
                "qty": item.qty,
                "part_no": item.part_no,
                "description": item.description,
                "material": item.material,
            }
            for item in sheet.bom_items
        ]

        return {
            "version": "1.0",
            "title": sheet.title_info.drawing_title,
            "drawing_no": sheet.title_info.drawing_no,
            "rev": sheet.title_info.rev,
            "scale": sheet.title_info.scale,
            "initial_theme": resolved_theme.value,
            "sheet_width_mm": round(sheet.width_mm, 2),
            "sheet_height_mm": round(sheet.height_mm, 2),
            "iso_view_bounds": iso_bounds,
            "bbox_min": [round(v, 4) for v in asm_min],
            "bbox_max": [round(v, 4) for v in asm_max],
            "center": [round(v, 4) for v in asm_center],
            "radius": round(asm_radius, 4),
            "bom_items": bom_list,
            "parts": [p.to_dict() for p in serialized_parts],
            "themes": {
                Theme.DARK_BLUEPRINT.value: _theme_colors_dict(THEME_COLORS[Theme.DARK_BLUEPRINT]),
                Theme.ISO_WHITE.value: _theme_colors_dict(THEME_COLORS[Theme.ISO_WHITE]),
            },
        }

    @classmethod
    def render_sheet(
        cls,
        sheet: DrawingSheet,
        theme: Theme | str = Theme.DARK_BLUEPRINT,
        *,
        shape: Shape[Any] | None = None,
        linear_deflection: float = 0.08,
        angular_deflection: float = 0.25,
        crease_angle_deg: float = 20.0,
        title: str | None = None,
        initial_layout: str = "split",
    ) -> str:
        """Render a complete, self-contained HTML5 document string with 2D SVG + 3D WebGL2."""
        resolved_theme = _coerce_theme(theme)
        layout_mode = "inspector" if initial_layout == "inspector" else "split"
        svg_inline = _strip_xml_declaration(sheet.to_svg(theme=resolved_theme))
        scene_data = cls.serialize_sheet_scene(
            sheet,
            theme=resolved_theme,
            shape=shape,
            linear_deflection=linear_deflection,
            angular_deflection=angular_deflection,
            crease_angle_deg=crease_angle_deg,
        )
        scene_data["initial_layout"] = layout_mode

        page_title = title or f"{sheet.title_info.drawing_no} — {sheet.title_info.drawing_title}"
        doc_title_esc = html.escape(page_title)
        drawing_title_esc = html.escape(sheet.title_info.drawing_title)
        drawing_no_esc = html.escape(sheet.title_info.drawing_no)
        sheet_dim_badge = f"{sheet.width_mm:.0f} × {sheet.height_mm:.0f} mm"
        scene_json = _escape_json_for_html_script(scene_data)

        theme_attr = "iso-white" if resolved_theme == Theme.ISO_WHITE else "dark-blueprint"
        default_shading = "iso" if resolved_theme == Theme.ISO_WHITE else "blueprint"

        return _build_html_document(
            doc_title=doc_title_esc,
            drawing_title=drawing_title_esc,
            drawing_no=drawing_no_esc,
            sheet_dim_badge=sheet_dim_badge,
            theme_attr=theme_attr,
            layout_mode=layout_mode,
            default_shading=default_shading,
            svg_inline=svg_inline,
            scene_json=scene_json,
        )

    @classmethod
    def save(
        cls,
        sheet: DrawingSheet,
        output_path: str | os.PathLike[str],
        theme: Theme | str = Theme.DARK_BLUEPRINT,
        *,
        shape: Shape[Any] | None = None,
        linear_deflection: float = 0.08,
        angular_deflection: float = 0.25,
        crease_angle_deg: float = 20.0,
        title: str | None = None,
        initial_layout: str = "split",
    ) -> None:
        """Render and write a self-contained interactive 3D-in-2D HTML blueprint file."""
        abs_path = os.path.abspath(os.fspath(output_path))
        os.makedirs(os.path.dirname(abs_path), exist_ok=True)
        html_doc = cls.render_sheet(
            sheet,
            theme=theme,
            shape=shape,
            linear_deflection=linear_deflection,
            angular_deflection=angular_deflection,
            crease_angle_deg=crease_angle_deg,
            title=title,
            initial_layout=initial_layout,
        )
        with open(abs_path, "w", encoding="utf-8") as f:
            f.write(html_doc)

serialize_sheet_scene(sheet, theme=Theme.DARK_BLUEPRINT, *, shape=None, linear_deflection=0.08, angular_deflection=0.25, crease_angle_deg=20.0) classmethod

Tessellate and serialize the sheet's 3D model, parts, BOM, and theme metadata.

Source code in src/build123d_techdraw/renderers/html.py
@classmethod
def serialize_sheet_scene(
    cls,
    sheet: DrawingSheet,
    theme: Theme | str = Theme.DARK_BLUEPRINT,
    *,
    shape: Shape[Any] | None = None,
    linear_deflection: float = 0.08,
    angular_deflection: float = 0.25,
    crease_angle_deg: float = 20.0,
) -> dict[str, Any]:
    """Tessellate and serialize the sheet's 3D model, parts, BOM, and theme metadata."""
    resolved_theme = _coerce_theme(theme)
    target_shape, iso_bounds = _find_sheet_shape_and_iso_bounds(sheet, override_shape=shape)

    raw_parts: list[
        tuple[
            Shape[Any],
            NDArray[np.float32],
            NDArray[np.float32],
            NDArray[np.uint32],
            NDArray[np.float32],
            tuple[float, float, float],
            tuple[float, float, float],
        ]
    ] = []

    if target_shape is not None:
        components = _extract_components(target_shape)
        for comp in components:
            positions, normals, indices, edges = _tessellate_component(
                comp,
                linear_deflection=linear_deflection,
                angular_deflection=angular_deflection,
                crease_angle_deg=crease_angle_deg,
            )
            if positions.shape[0] == 0 or indices.size == 0:
                continue
            p_min = positions.min(axis=0)
            p_max = positions.max(axis=0)
            bmin = (float(p_min[0]), float(p_min[1]), float(p_min[2]))
            bmax = (float(p_max[0]), float(p_max[1]), float(p_max[2]))
            raw_parts.append((comp, positions, normals, indices, edges, bmin, bmax))

    if raw_parts:
        asm_min = (
            min(p[5][0] for p in raw_parts),
            min(p[5][1] for p in raw_parts),
            min(p[5][2] for p in raw_parts),
        )
        asm_max = (
            max(p[6][0] for p in raw_parts),
            max(p[6][1] for p in raw_parts),
            max(p[6][2] for p in raw_parts),
        )
        asm_center = (
            0.5 * (asm_min[0] + asm_max[0]),
            0.5 * (asm_min[1] + asm_max[1]),
            0.5 * (asm_min[2] + asm_max[2]),
        )
        asm_radius = max(
            0.5 * math.dist(asm_min, asm_max),
            1.0,
        )
    else:
        asm_min = (-10.0, -10.0, -10.0)
        asm_max = (10.0, 10.0, 10.0)
        asm_center = (0.0, 0.0, 0.0)
        asm_radius = 15.0

    bboxes = [(p[5], p[6]) for p in raw_parts]
    explode_vectors = _compute_explode_vectors(bboxes, asm_min, asm_max)

    serialized_parts: list[SerializedPartMesh] = []
    total_parts = len(raw_parts)
    for idx, (comp, positions, normals, indices, edges, bmin, bmax) in enumerate(raw_parts):
        bom_item_no, part_no, name, material, qty = _match_component_bom(
            comp, sheet, idx, total_parts
        )
        center = (
            0.5 * (bmin[0] + bmax[0]),
            0.5 * (bmin[1] + bmax[1]),
            0.5 * (bmin[2] + bmax[2]),
        )
        serialized_parts.append(
            SerializedPartMesh(
                part_id=idx,
                name=name,
                bom_item_no=bom_item_no,
                part_no=part_no,
                material=material,
                qty=qty,
                bbox_min=bmin,
                bbox_max=bmax,
                center=center,
                explode_vector=explode_vectors[idx],
                vertex_count=int(positions.shape[0]),
                triangle_count=int(indices.size // 3),
                edge_segment_count=int(edges.shape[0]),
                positions_b64=base64.b64encode(positions.tobytes()).decode("ascii"),
                normals_b64=base64.b64encode(normals.tobytes()).decode("ascii"),
                indices_b64=base64.b64encode(indices.tobytes()).decode("ascii"),
                edges_b64=base64.b64encode(edges.tobytes()).decode("ascii"),
            )
        )

    bom_list = [
        {
            "item_no": item.item_no,
            "qty": item.qty,
            "part_no": item.part_no,
            "description": item.description,
            "material": item.material,
        }
        for item in sheet.bom_items
    ]

    return {
        "version": "1.0",
        "title": sheet.title_info.drawing_title,
        "drawing_no": sheet.title_info.drawing_no,
        "rev": sheet.title_info.rev,
        "scale": sheet.title_info.scale,
        "initial_theme": resolved_theme.value,
        "sheet_width_mm": round(sheet.width_mm, 2),
        "sheet_height_mm": round(sheet.height_mm, 2),
        "iso_view_bounds": iso_bounds,
        "bbox_min": [round(v, 4) for v in asm_min],
        "bbox_max": [round(v, 4) for v in asm_max],
        "center": [round(v, 4) for v in asm_center],
        "radius": round(asm_radius, 4),
        "bom_items": bom_list,
        "parts": [p.to_dict() for p in serialized_parts],
        "themes": {
            Theme.DARK_BLUEPRINT.value: _theme_colors_dict(THEME_COLORS[Theme.DARK_BLUEPRINT]),
            Theme.ISO_WHITE.value: _theme_colors_dict(THEME_COLORS[Theme.ISO_WHITE]),
        },
    }

render_sheet(sheet, theme=Theme.DARK_BLUEPRINT, *, shape=None, linear_deflection=0.08, angular_deflection=0.25, crease_angle_deg=20.0, title=None, initial_layout='split') classmethod

Render a complete, self-contained HTML5 document string with 2D SVG + 3D WebGL2.

Source code in src/build123d_techdraw/renderers/html.py
@classmethod
def render_sheet(
    cls,
    sheet: DrawingSheet,
    theme: Theme | str = Theme.DARK_BLUEPRINT,
    *,
    shape: Shape[Any] | None = None,
    linear_deflection: float = 0.08,
    angular_deflection: float = 0.25,
    crease_angle_deg: float = 20.0,
    title: str | None = None,
    initial_layout: str = "split",
) -> str:
    """Render a complete, self-contained HTML5 document string with 2D SVG + 3D WebGL2."""
    resolved_theme = _coerce_theme(theme)
    layout_mode = "inspector" if initial_layout == "inspector" else "split"
    svg_inline = _strip_xml_declaration(sheet.to_svg(theme=resolved_theme))
    scene_data = cls.serialize_sheet_scene(
        sheet,
        theme=resolved_theme,
        shape=shape,
        linear_deflection=linear_deflection,
        angular_deflection=angular_deflection,
        crease_angle_deg=crease_angle_deg,
    )
    scene_data["initial_layout"] = layout_mode

    page_title = title or f"{sheet.title_info.drawing_no} — {sheet.title_info.drawing_title}"
    doc_title_esc = html.escape(page_title)
    drawing_title_esc = html.escape(sheet.title_info.drawing_title)
    drawing_no_esc = html.escape(sheet.title_info.drawing_no)
    sheet_dim_badge = f"{sheet.width_mm:.0f} × {sheet.height_mm:.0f} mm"
    scene_json = _escape_json_for_html_script(scene_data)

    theme_attr = "iso-white" if resolved_theme == Theme.ISO_WHITE else "dark-blueprint"
    default_shading = "iso" if resolved_theme == Theme.ISO_WHITE else "blueprint"

    return _build_html_document(
        doc_title=doc_title_esc,
        drawing_title=drawing_title_esc,
        drawing_no=drawing_no_esc,
        sheet_dim_badge=sheet_dim_badge,
        theme_attr=theme_attr,
        layout_mode=layout_mode,
        default_shading=default_shading,
        svg_inline=svg_inline,
        scene_json=scene_json,
    )

save(sheet, output_path, theme=Theme.DARK_BLUEPRINT, *, shape=None, linear_deflection=0.08, angular_deflection=0.25, crease_angle_deg=20.0, title=None, initial_layout='split') classmethod

Render and write a self-contained interactive 3D-in-2D HTML blueprint file.

Source code in src/build123d_techdraw/renderers/html.py
@classmethod
def save(
    cls,
    sheet: DrawingSheet,
    output_path: str | os.PathLike[str],
    theme: Theme | str = Theme.DARK_BLUEPRINT,
    *,
    shape: Shape[Any] | None = None,
    linear_deflection: float = 0.08,
    angular_deflection: float = 0.25,
    crease_angle_deg: float = 20.0,
    title: str | None = None,
    initial_layout: str = "split",
) -> None:
    """Render and write a self-contained interactive 3D-in-2D HTML blueprint file."""
    abs_path = os.path.abspath(os.fspath(output_path))
    os.makedirs(os.path.dirname(abs_path), exist_ok=True)
    html_doc = cls.render_sheet(
        sheet,
        theme=theme,
        shape=shape,
        linear_deflection=linear_deflection,
        angular_deflection=angular_deflection,
        crease_angle_deg=crease_angle_deg,
        title=title,
        initial_layout=initial_layout,
    )
    with open(abs_path, "w", encoding="utf-8") as f:
        f.write(html_doc)

render_interactive_html(sheet, theme=Theme.DARK_BLUEPRINT, *, shape=None, linear_deflection=0.08, angular_deflection=0.25, crease_angle_deg=20.0, title=None, initial_layout='split')

Render a DrawingSheet to a self-contained interactive HTML5 document string.

Source code in src/build123d_techdraw/renderers/html.py
def render_interactive_html(
    sheet: DrawingSheet,
    theme: Theme | str = Theme.DARK_BLUEPRINT,
    *,
    shape: Shape[Any] | None = None,
    linear_deflection: float = 0.08,
    angular_deflection: float = 0.25,
    crease_angle_deg: float = 20.0,
    title: str | None = None,
    initial_layout: str = "split",
) -> str:
    """Render a DrawingSheet to a self-contained interactive HTML5 document string."""
    return HTMLRenderer.render_sheet(
        sheet,
        theme=theme,
        shape=shape,
        linear_deflection=linear_deflection,
        angular_deflection=angular_deflection,
        crease_angle_deg=crease_angle_deg,
        title=title,
        initial_layout=initial_layout,
    )

export_interactive_html(sheet, output_path, theme=Theme.DARK_BLUEPRINT, *, shape=None, linear_deflection=0.08, angular_deflection=0.25, crease_angle_deg=20.0, title=None, initial_layout='split')

Export a DrawingSheet to a self-contained interactive HTML5 blueprint file.

Source code in src/build123d_techdraw/renderers/html.py
def export_interactive_html(
    sheet: DrawingSheet,
    output_path: str | os.PathLike[str],
    theme: Theme | str = Theme.DARK_BLUEPRINT,
    *,
    shape: Shape[Any] | None = None,
    linear_deflection: float = 0.08,
    angular_deflection: float = 0.25,
    crease_angle_deg: float = 20.0,
    title: str | None = None,
    initial_layout: str = "split",
) -> None:
    """Export a DrawingSheet to a self-contained interactive HTML5 blueprint file."""
    HTMLRenderer.save(
        sheet,
        output_path,
        theme=theme,
        shape=shape,
        linear_deflection=linear_deflection,
        angular_deflection=angular_deflection,
        crease_angle_deg=crease_angle_deg,
        title=title,
        initial_layout=initial_layout,
    )

build123d_techdraw.renderers.theme

Theme definitions and CSS custom property palettes for 2D technical drawings.

THEME_COLORS = {Theme.DARK_BLUEPRINT: ThemeColors(bg='#0B192C', grid='#38BDF812', border='#38BDF8', border_sub='#1E3A5F', title_bg='#0F172AE6', title_border='#38BDF8', text='#F8FAFC', text_muted='#94A3B8', text_accent='#38BDF8', line_visible='#FFFFFF', line_hidden='#475569', line_center='#38BDF8', line_section='#F43F5E', hatch='#0284C7', dim_line='#38BDF8', dim_text='#38BDF8', balloon_bg='#0F172A', balloon_border='#F43F5E', balloon_text='#FFFFFF', table_header_bg='#1E293B', table_row_alt='#1E293B99', line_bend_up='#34D399', line_bend_down='#F59E0B', line_bend_tangent='#64748B'), Theme.ISO_WHITE: ThemeColors(bg='#FFFFFF', grid='#00000008', border='#0F172A', border_sub='#CBD5E1', title_bg='#F8FAFC', title_border='#0F172A', text='#0F172A', text_muted='#475569', text_accent='#0284C7', line_visible='#000000', line_hidden='#94A3B8', line_center='#2563EB', line_section='#DC2626', hatch='#64748B', dim_line='#DC2626', dim_text='#DC2626', balloon_bg='#FFFFFF', balloon_border='#DC2626', balloon_text='#0F172A', table_header_bg='#E2E8F0', table_row_alt='#F1F5F9', line_bend_up='#047857', line_bend_down='#C2410C', line_bend_tangent='#94A3B8')} module-attribute

Theme

Bases: Enum

Source code in src/build123d_techdraw/renderers/theme.py
class Theme(Enum):
    DARK_BLUEPRINT = "dark_blueprint"
    ISO_WHITE = "iso_white"
    PRINT = "iso_white"

ThemeColors dataclass

Source code in src/build123d_techdraw/renderers/theme.py
@dataclass(frozen=True)
class ThemeColors:
    bg: str
    grid: str
    border: str
    border_sub: str
    title_bg: str
    title_border: str
    text: str
    text_muted: str
    text_accent: str
    line_visible: str
    line_hidden: str
    line_center: str
    line_section: str
    hatch: str
    dim_line: str
    dim_text: str
    balloon_bg: str
    balloon_border: str
    balloon_text: str
    table_header_bg: str
    table_row_alt: str
    line_bend_up: str
    line_bend_down: str
    line_bend_tangent: str