Skip to content
Edit this page

ictdesigntools.draw.dxf

DXF output through ezdxf, an optional dependency: pip install ictdesigntools[dxf].

The drawing is written at full size in its units (AutoCAD 2018 format). Layers carry over, components become blocks placed by INSERTs, closed shapes with a Hatch style are hatched, dimensions are native DIMENSIONs and soil is a native EARTH hatch, so it stays editable in CAD. DXF has y up, so the drawing is flipped on the way out. Circles must not be scaled unevenly.

to_dxf

to_dxf(
    drawing: Drawing, theme: dict[str, Style] | None = None
) -> bytes

The drawing as DXF text, encoded UTF-8.

Source code in src/ictdesigntools/draw/dxf.py
def to_dxf(drawing: Drawing, theme: dict[str, Style] | None = None) -> bytes:
    """The drawing as DXF text, encoded UTF-8."""
    _ezdxf()
    import ezdxf
    from ezdxf import units
    from ezdxf.enums import TextEntityAlignment

    doc = ezdxf.new("R2018", setup=True)
    doc.units = units.MM if drawing.units == "mm" else units.IN
    doc.header["$MEASUREMENT"] = 1 if drawing.units == "mm" else 0
    for name, layer in drawing.layers.items():
        attribs = {"linetype": layer.linetype} if layer.linetype else {}
        doc.layers.add(name, color=layer.color, dxfattribs=attribs)

    def layer(name: str) -> str:
        if name not in doc.layers:
            doc.layers.add(name, color=7)
        return name

    font = drawing.font

    def emit(space, items, t: Transform, inherited: str, in_block: bool):
        """Add items to a layout or block. ``t`` maps item coordinates to the space's (y down);
        the flip to DXF's y up is applied last."""
        world = FLIP @ t
        k = t.scale_factor
        turn = -1.0 if world.mirrored else 1.0  # arcs run the other way once mirrored

        # Entities are written in world coordinates rather than transformed afterwards: a
        # mirrored transform (as the flip to y up is) would give circles and polylines a
        # downward extrusion, which CAD programs show with odd coordinates.
        def P(x, y):
            return world.apply(x, y)

        def xyb(pts):
            return [(*P(x, y), b * turn) for x, y, b in pts]

        def radius(r, it):
            if not t.is_similarity:
                raise ValueError(f"{type(it).__name__} cannot be scaled unevenly in DXF.")
            return r * k

        def attrs(it, s: Style | None = None, color: str | None = None):
            own = getattr(it, "layer", "0")
            a = {"layer": layer(own if own != "0" else inherited or "0")}
            if s is not None and s.dash:
                a["linetype"] = "DASHED"
            if color:
                a["true_color"] = int(hex6(color)[1:], 16)
            return a

        def hatch(it, s: Style, add_path):
            h = s.hatch
            if h is None:
                return
            entity = space.add_hatch(color=h.color if h.color is not None else 256,
                                     dxfattribs=attrs(it))  # fmt: skip
            if h.pattern.upper() == "SOLID":
                entity.set_solid_fill(color=h.color if h.color is not None else 256)
            else:
                entity.set_pattern_fill(h.pattern, scale=h.scale, angle=h.angle,
                                        color=h.color if h.color is not None else 256)  # fmt: skip
            add_path(entity)

        for it in items:
            if isinstance(it, Group):
                emit(space, it.items, t @ it.transform, it.layer or inherited, in_block)
            elif isinstance(it, Use):
                name = block_name(it.component)
                on = layer(it.layer or inherited or "0")
                ref = space.add_blockref(name, (0, 0), dxfattribs={"layer": on})
                place = FLIP @ t @ it.transform @ FLIP  # the block is already flipped inside
                if not place.is_identity:
                    ref.transform(_m44(place))
            elif isinstance(it, Earth):
                # One hatch per rectangle around the holes: hatch islands are read
                # inconsistently by CAD programs, plain rectangles are not.
                for rx, ry, rw, rh in earth_pieces(it):
                    e = space.add_hatch(color=52, dxfattribs=attrs(it))
                    e.set_pattern_fill("EARTH", scale=it.tile * 4)  # its tile is 1/4 unit
                    corners = [P(rx, ry), P(rx + rw, ry), P(rx + rw, ry + rh), P(rx, ry + rh)]
                    e.paths.add_polyline_path(corners, is_closed=True, flags=1)
            elif isinstance(it, (Rect, Polygon)):
                s = drawing.style(it, theme)
                local = _rect_xyb(it) if isinstance(it, Rect) else [(x, y, 0) for x, y in it.points]
                pts = xyb(local)
                if s.stroke or s.hatch is None or s.hatch.outline:
                    color = (s.stroke or s.fill) if s.cad_color else None
                    space.add_lwpolyline(pts, format="xyb", close=True,
                                         dxfattribs=attrs(it, s, color))  # fmt: skip
                hatch(it, s, lambda e, pts=pts: e.paths.add_polyline_path(pts, is_closed=True))
            elif isinstance(it, Circle):
                s = drawing.style(it, theme)
                if s.stroke or s.hatch is None or s.hatch.outline:
                    color = (s.stroke or s.fill) if s.cad_color else None
                    space.add_circle(P(it.cx, it.cy), radius(it.r, it),
                                     dxfattribs=attrs(it, s, color))  # fmt: skip

                def arc_path(e, it=it):
                    e.paths.add_edge_path().add_arc(P(it.cx, it.cy), radius(it.r, it), 0, 360)

                hatch(it, s, arc_path)
            elif isinstance(it, Ring):
                color = it.color if it.cad_color else None
                for r in (it.r_outer, it.r_inner):
                    space.add_circle(P(it.cx, it.cy), radius(r, it),
                                     dxfattribs=attrs(it, None, color))  # fmt: skip
            elif isinstance(it, (Polyline, Arc)):
                s = drawing.style(it, theme)
                pts = it.points if isinstance(it, Polyline) else arc_points(it)
                color = s.stroke if s.cad_color else None
                space.add_lwpolyline([P(x, y) for x, y in pts], dxfattribs=attrs(it, s, color))
            elif isinstance(it, Line):
                s = drawing.style(it, theme)
                color = s.stroke if s.cad_color else None
                space.add_line(P(it.x1, it.y1), P(it.x2, it.y2), dxfattribs=attrs(it, s, color))
                width = s.width if s.width is not None else drawing.stroke
                for head in arrowheads(it, max(width * 6, font * 0.6)):
                    e = space.add_hatch(dxfattribs=attrs(it))
                    e.paths.add_polyline_path([P(x, y) for x, y in head], is_closed=True)
            elif isinstance(it, Text):
                x, y = world.apply(it.x, it.y)
                rotation = (t @ Transform.rotate(it.rotate)).rotation
                e = space.add_text(it.text, height=it.size * 0.7 * k,
                                   dxfattribs=attrs(it) | {"rotation": rotation})  # fmt: skip
                e.set_placement((x, y), align=TextEntityAlignment[_ALIGN[it.anchor]])
            elif isinstance(it, Dim):
                if it.vertical:
                    base = (it.x1 + it.offset, (it.y1 + it.y2) / 2)
                    angle = 90.0
                else:
                    base = ((it.x1 + it.x2) / 2, it.y1 - it.offset)
                    angle = 0.0
                dim = space.add_linear_dim(
                    base=world.apply(*base), p1=world.apply(it.x1, it.y1),
                    p2=world.apply(it.x2, it.y2), angle=angle + t.rotation, text=it.text,
                    dxfattribs=attrs(it),
                    override={"dimtxt": font * 0.7 * k, "dimasz": font * 0.5 * k,
                              "dimexe": font * 0.3 * k, "dimexo": font * 0.2 * k,
                              "dimtsz": font * 0.4 * k, "dimgap": font * 0.2 * k},
                )  # fmt: skip
                dim.render()
            else:
                raise TypeError(f"Cannot draw {type(it).__name__}.")

    for c in drawing.components():
        block = doc.blocks.new(name=block_name(c))
        emit(block, c.items, Transform(), "0", True)
    emit(doc.modelspace(), drawing.items, Transform(), "0", False)
    stream = io.StringIO()
    doc.write(stream)
    return stream.getvalue().encode("utf-8")