comparison make_template.py @ 0:b5a96b547b01

initial public version
author ark
date 2026-11-03 01:29 +0100
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:b5a96b547b01
1 #!/usr/bin/env python3
2 """Tile a drilling template exported from OpenSCAD onto printable pages.
3
4 Reads the SVG export of the template part of main.scad and writes a PDF at
5 1:1 scale, split over pages of the chosen paper size. Neighbouring pages
6 overlap. A dashed line runs through the middle of each overlap, with
7 crosses every 50 mm along it: trim one sheet along the line, lay it over
8 its neighbour so line and crosses match, and tape it. Each page names its
9 row and column.
10
11 Print at 100% (actual size) and check the 100 mm scale bar.
12
13 Only the Python standard library is used. The SVG must consist of path
14 elements with straight segments (M, L and z commands), which is what
15 OpenSCAD exports for 2D shapes.
16 """
17
18 import argparse
19 import math
20 import os
21 import re
22 import sys
23 import xml.etree.ElementTree as ET
24
25 MM = 72 / 25.4 # PDF points per mm
26 PAPER = {"a4": (210, 297), "a3": (297, 420), "letter": (215.9, 279.4),
27 "legal": (215.9, 355.6)}
28
29
30 def parse_args():
31 """Parse the command line."""
32 p = argparse.ArgumentParser(description=__doc__,
33 formatter_class=argparse.RawDescriptionHelpFormatter)
34 p.add_argument("svg", help="SVG export of the template part")
35 p.add_argument("-o", "--output", help="output PDF (default: the SVG name with .pdf)")
36 p.add_argument("--paper", choices=sorted(PAPER), default="a4",
37 help="paper size (default: %(default)s)")
38 p.add_argument("--margin", type=float, default=6,
39 help="unprintable margin along the paper edges in mm (default: %(default)s)")
40 p.add_argument("--overlap", type=float, default=10,
41 help="overlap between neighbouring pages in mm (default: %(default)s)")
42 p.add_argument("--line", type=float, default=.2,
43 help="line width in mm (default: %(default)s)")
44 return p.parse_args()
45
46
47 def read_svg(path):
48 """Read the polygons of an OpenSCAD SVG export.
49
50 Returns:
51 (polygons, width, height): polygons as lists of (x, y) in mm with
52 the origin at the lower left corner of the drawing and y up, and the
53 drawing size in mm.
54
55 Raises:
56 SystemExit: the file contains elements or path commands other than
57 those OpenSCAD writes for 2D shapes, or its units are not mm.
58 """
59 root = ET.parse(path).getroot()
60 ns = "{http://www.w3.org/2000/svg}"
61 vb = [float(v) for v in root.get("viewBox", "").replace(",", " ").split()]
62 if len(vb) != 4:
63 sys.exit(f"{path}: no viewBox")
64 minx, miny, w, h = vb
65 width = root.get("width", "")
66 if not width.endswith("mm") or not math.isclose(float(width[:-2]), w, rel_tol=1e-6):
67 sys.exit(f"{path}: width {width!r} does not match the viewBox in mm")
68 polygons = []
69 for el in root.iter():
70 tag = el.tag.replace(ns, "")
71 if tag in ("svg", "title"):
72 continue
73 if tag != "path":
74 sys.exit(f"{path}: unexpected element {tag!r}")
75 tokens = re.findall(r"[A-Za-z]|-?[\d.]+(?:[eE][-+]?\d+)?", el.get("d", ""))
76 cur, i = None, 0
77 while i < len(tokens):
78 t = tokens[i]
79 if t in ("M", "L"):
80 x, y = float(tokens[i + 1]), float(tokens[i + 2])
81 pt = (x - minx, miny + h - y)
82 if t == "M":
83 cur = [pt]
84 polygons.append(cur)
85 else:
86 cur.append(pt)
87 i += 3
88 elif t in ("z", "Z"):
89 i += 1
90 else:
91 sys.exit(f"{path}: unexpected path data {t!r}")
92 return polygons, w, h
93
94
95 def tiles(total, page, overlap):
96 """Start positions of pages covering a length.
97
98 Args:
99 total: length of the drawing.
100 page: printable length of a page.
101 overlap: overlap between neighbouring pages.
102
103 Returns:
104 list of start positions, the first at 0.
105 """
106 step = page - overlap
107 n = max(1, math.ceil((total - overlap) / step))
108 return [i * step for i in range(n)]
109
110
111 def layout(w, h, args):
112 """Choose portrait or landscape pages, whichever needs fewer.
113
114 Returns:
115 (paper width, paper height, x starts, y starts) in mm.
116 """
117 best = None
118 for pw, ph in (PAPER[args.paper], PAPER[args.paper][::-1]):
119 xs = tiles(w, pw - 2 * args.margin, args.overlap)
120 ys = tiles(h, ph - 2 * args.margin, args.overlap)
121 if best is None or len(xs) * len(ys) < len(best[2]) * len(best[3]):
122 best = (pw, ph, xs, ys)
123 return best
124
125
126 def fmt(v):
127 """Number for a PDF content stream."""
128 return f"{v:.3f}".rstrip("0").rstrip(".")
129
130
131 def page_content(polygons, x0, y0, pw, ph, w, h, cuts_x, cuts_y, label, args):
132 """Content stream of one page.
133
134 The drawing is shifted so that (x0, y0) lies at the lower left corner of
135 the printable area, and clipped to that area.
136
137 Args:
138 polygons, w, h: the drawing, see read_svg().
139 x0, y0: drawing position at the lower left of the printable area.
140 pw, ph: paper size in mm.
141 cuts_x, cuts_y: positions of the trim lines in the drawing.
142 label: page name for the bottom margin.
143 args: command line arguments.
144 """
145 m = args.margin
146 out = [f"q {fmt(m * MM)} {fmt(m * MM)} {fmt((pw - 2 * m) * MM)} {fmt((ph - 2 * m) * MM)} "
147 f"re W n",
148 f"1 0 0 1 {fmt((m - x0) * MM)} {fmt((m - y0) * MM)} cm",
149 f"{fmt(args.line * MM)} w 1 j 1 J 0 G"]
150 for poly in polygons:
151 out.append(f"{fmt(poly[0][0] * MM)} {fmt(poly[0][1] * MM)} m " +
152 " ".join(f"{fmt(x * MM)} {fmt(y * MM)} l" for x, y in poly[1:]) + " h S")
153 # guides: dashed trim lines through the overlaps, crosses every 50 mm
154 out.append(f"0.6 G {fmt(.15 * MM)} w")
155 out.append(f"[{fmt(3 * MM)} {fmt(2 * MM)}] 0 d")
156 for x in cuts_x:
157 out.append(f"{fmt(x * MM)} 0 m {fmt(x * MM)} {fmt(h * MM)} l S")
158 for y in cuts_y:
159 out.append(f"0 {fmt(y * MM)} m {fmt(w * MM)} {fmt(y * MM)} l S")
160 out.append("[] 0 d")
161 c = 3 # half cross size
162 for x in cuts_x:
163 for y in range(0, int(h) + 1, 50):
164 out.append(f"{fmt((x - c) * MM)} {fmt(y * MM)} m {fmt((x + c) * MM)} {fmt(y * MM)} l "
165 f"{fmt(x * MM)} {fmt((y - c) * MM)} m {fmt(x * MM)} {fmt((y + c) * MM)} l S")
166 for y in cuts_y:
167 for x in range(0, int(w) + 1, 50):
168 out.append(f"{fmt((x - c) * MM)} {fmt(y * MM)} m {fmt((x + c) * MM)} {fmt(y * MM)} l "
169 f"{fmt(x * MM)} {fmt((y - c) * MM)} m {fmt(x * MM)} {fmt((y + c) * MM)} l S")
170 out.append("Q")
171 # page name in the bottom margin
172 out.append(f"BT /F1 7 Tf 0 g {fmt(m * MM)} {fmt(m / 2 * MM)} Td "
173 f"({label}, print at 100%) Tj ET")
174 return "\n".join(out).encode("ascii")
175
176
177 def write_pdf(path, pages, pw, ph):
178 """Write a PDF with one page per content stream.
179
180 Args:
181 path: output file.
182 pages: list of content streams (bytes).
183 pw, ph: page size in mm.
184 """
185 n = len(pages)
186 # objects: 1 catalog, 2 page tree, 3 font, then page and content per page
187 objs = [b"<< /Type /Catalog /Pages 2 0 R >>",
188 ("<< /Type /Pages /Kids [" + " ".join(f"{4 + 2 * i} 0 R" for i in range(n))
189 + f"] /Count {n} >>").encode(),
190 b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>"]
191 for i, content in enumerate(pages):
192 objs.append((f"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {fmt(pw * MM)} "
193 f"{fmt(ph * MM)}] /Resources << /Font << /F1 3 0 R >> >> "
194 f"/Contents {5 + 2 * i} 0 R >>").encode())
195 objs.append(f"<< /Length {len(content)} >>\nstream\n".encode() + content
196 + b"\nendstream")
197 data = bytearray(b"%PDF-1.4\n")
198 offsets = []
199 for i, obj in enumerate(objs):
200 offsets.append(len(data))
201 data += f"{i + 1} 0 obj\n".encode() + obj + b"\nendobj\n"
202 xref = len(data)
203 data += f"xref\n0 {len(objs) + 1}\n0000000000 65535 f \n".encode()
204 for off in offsets:
205 data += f"{off:010d} 00000 n \n".encode()
206 data += (f"trailer\n<< /Size {len(objs) + 1} /Root 1 0 R >>\n"
207 f"startxref\n{xref}\n%%EOF\n").encode()
208 with open(path, "wb") as f:
209 f.write(data)
210
211
212 def main():
213 """Read the SVG, lay out the pages and write the PDF."""
214 args = parse_args()
215 polygons, w, h = read_svg(args.svg)
216 pw, ph, xs, ys = layout(w, h, args)
217 tile_h = ph - 2 * args.margin
218 ov = args.overlap
219 # ys count from the top of the drawing, so the pages come in reading order
220 cuts_x = [x + ov / 2 for x in xs[1:]]
221 cuts_y = [h - y - ov / 2 for y in ys[1:]]
222 pages = []
223 for row, y in enumerate(ys):
224 for col, x0 in enumerate(xs):
225 label = f"row {row + 1} of {len(ys)}, column {col + 1} of {len(xs)}"
226 pages.append(page_content(polygons, x0, h - y - tile_h, pw, ph, w, h,
227 cuts_x, cuts_y, label, args))
228 out = args.output or os.path.splitext(args.svg)[0] + ".pdf"
229 write_pdf(out, pages, pw, ph)
230 orient = "portrait" if pw < ph else "landscape"
231 print(f"{w:.0f} x {h:.0f} mm on {len(pages)} {args.paper} pages, {orient}, "
232 f"{len(ys)} rows of {len(xs)}: {out}")
233
234
235 if __name__ == "__main__":
236 main()