Skip to content
Edit this page

ictdesigntools.draw.pdf

PDF output through reportlab, an optional dependency: pip install ictdesigntools[pdf].

to_reportlab gives a reportlab Drawing to place in a document of your own (a platypus flowable); pdf_file gives a one-page PDF of the drawing on its own.

to_reportlab

to_reportlab(
    drawing: Drawing,
    max_width: float,
    max_height: float,
    theme: dict[str, Style] | None = None,
)

A reportlab Drawing of drawing, scaled to fit max_width × max_height points.

Source code in src/ictdesigntools/draw/pdf.py
def to_reportlab(drawing: Drawing, max_width: float, max_height: float,
                 theme: dict[str, Style] | None = None):  # fmt: skip
    """A reportlab ``Drawing`` of ``drawing``, scaled to fit ``max_width`` × ``max_height``
    points."""
    _reportlab()
    from reportlab.graphics.shapes import Circle as RCircle
    from reportlab.graphics.shapes import Drawing as RDrawing
    from reportlab.graphics.shapes import Group as RGroup
    from reportlab.graphics.shapes import Line as RLine
    from reportlab.graphics.shapes import Path, String
    from reportlab.graphics.shapes import Rect as RRect
    from reportlab.lib import colors

    vx, vy, vw, vh = drawing.view
    k = min(max_width / vw, max_height / vh)
    out = RDrawing(vw * k, vh * k)
    root = RGroup()
    root.transform = (k, 0, 0, -k, -vx * k, (vh + vy) * k)  # y down, in drawing units
    out.add(root)
    sw = drawing.stroke
    dash = [sw * 6, sw * 4]

    def col(c):
        return colors.HexColor(hex6(c)) if c else None

    def stroked(shape, s: Style):
        shape.strokeColor = col(s.stroke)
        shape.strokeWidth = (s.width if s.width is not None else sw) if s.stroke else 0
        if s.dash and s.stroke:
            shape.strokeDashArray = dash
        return shape

    def text(group, x, y, s, size, color, anchor, rotate):
        place = Transform.translate(x, y) @ Transform.rotate(rotate) @ Transform.scale(1, -1)
        g = RGroup(String(0, -size * 0.35, s, fontName="Helvetica", fontSize=size,
                          fillColor=col(color), textAnchor=anchor))  # fmt: skip
        g.transform = _t(place)
        group.add(g)

    def path(points, closed, fill, s: Style | None, stroke=None, width=0.0):
        p = Path(fillColor=col(fill))
        (x0, y0), *rest = points
        p.moveTo(x0, y0)
        for x, y in rest:
            p.lineTo(x, y)
        if closed:
            p.closePath()
        if s is not None:
            stroked(p, s)
        else:
            p.strokeColor, p.strokeWidth = col(stroke), width if stroke else 0
        return p

    def segments(group, segs, color, width):
        p = Path(strokeColor=col(color), strokeWidth=width, fillColor=None)
        for a, b, c, e in segs:
            p.moveTo(a, b)
            p.lineTo(c, e)
        group.add(p)

    def build(items, group):
        for it in items:
            if isinstance(it, (Group, Use)):
                child = RGroup()
                child.transform = _t(it.transform)
                build(it.items if isinstance(it, Group) else it.component.items, child)
                group.add(child)
            elif isinstance(it, Earth):
                segments(group, earth_strokes(it), SOIL, sw * 0.5)
            elif isinstance(it, Rect):
                s = drawing.style(it, theme)
                group.add(stroked(RRect(it.x, it.y, it.w, it.h, rx=it.rx, ry=it.rx,
                                        fillColor=col(s.fill)), s))  # fmt: skip
            elif isinstance(it, Circle):
                s = drawing.style(it, theme)
                group.add(stroked(RCircle(it.cx, it.cy, it.r, fillColor=col(s.fill)), s))
            elif isinstance(it, Ring):
                mid, width = (it.r_outer + it.r_inner) / 2, it.r_outer - it.r_inner
                group.add(RCircle(it.cx, it.cy, it.r_inner, fillColor=col(it.bore),
                                  strokeColor=None, strokeWidth=0))  # fmt: skip
                group.add(RCircle(it.cx, it.cy, mid, fillColor=None, strokeColor=col(it.color),
                                  strokeWidth=width))  # fmt: skip
                if it.edge:
                    for r in (it.r_outer, it.r_inner):
                        edge = RCircle(it.cx, it.cy, r, fillColor=None)
                        edge.strokeColor, edge.strokeWidth = col(it.edge), sw * 0.6
                        group.add(edge)
            elif isinstance(it, Polygon):
                s = drawing.style(it, theme)
                group.add(path(it.points, True, s.fill, s))
            elif isinstance(it, Polyline):
                group.add(path(it.points, False, None, drawing.style(it, theme)))
            elif isinstance(it, Arc):
                group.add(path(arc_points(it), False, None, drawing.style(it, theme)))
            elif isinstance(it, Line):
                s = drawing.style(it, theme)
                group.add(stroked(RLine(it.x1, it.y1, it.x2, it.y2), s))
                width = s.width if s.width is not None else sw
                for head in arrowheads(it, max(width * 6, drawing.font * 0.6)):
                    group.add(path(head, True, s.stroke, None))
            elif isinstance(it, Text):
                s = drawing.style(it, theme)
                text(group, it.x, it.y, it.text, it.size, s.color, it.anchor, it.rotate)
            elif isinstance(it, Dim):
                line, ext, ticks, (tx, ty, rot) = dim_geometry(it, drawing.font)
                segments(group, [line, *ext, *ticks], MUTED, sw)
                text(group, tx, ty, it.text, drawing.font, MUTED, "middle", rot)
            else:
                raise TypeError(f"Cannot draw {type(it).__name__}.")

    build(drawing.items, root)
    return out

pdf_file

pdf_file(
    drawing: Drawing,
    page: tuple[float, float] = (612.0, 792.0),
    margin: float = 36.0,
    theme: dict[str, Style] | None = None,
) -> bytes

A one-page PDF (US letter unless page says otherwise, in points) with the drawing fitted inside the margins.

Source code in src/ictdesigntools/draw/pdf.py
def pdf_file(drawing: Drawing, page: tuple[float, float] = (612.0, 792.0), margin: float = 36.0,
             theme: dict[str, Style] | None = None) -> bytes:  # fmt: skip
    """A one-page PDF (US letter unless ``page`` says otherwise, in points) with the drawing
    fitted inside the margins."""
    _reportlab()
    import io

    from reportlab.graphics import renderPDF
    from reportlab.pdfgen.canvas import Canvas

    buffer = io.BytesIO()
    canvas = Canvas(buffer, pagesize=page)
    canvas.setTitle(drawing.title or "Drawing")
    rd = to_reportlab(drawing, page[0] - 2 * margin, page[1] - 2 * margin, theme)
    renderPDF.draw(rd, canvas, (page[0] - rd.width) / 2, page[1] - margin - rd.height)
    canvas.showPage()
    canvas.save()
    return buffer.getvalue()