|
| 1 | +# Copyright (c) 2026 Code Infinity |
| 2 | +# SPDX-License-Identifier: MPL-2.0 |
| 3 | +# This Source Code Form is subject to the terms of the Mozilla Public |
| 4 | +# License, v. 2.0. If a copy of the MPL was not distributed with this |
| 5 | +# file, You can obtain one at https://mozilla.org/MPL/2.0/. |
| 6 | +"""A tiny PDF writer — Python standard library only. |
| 7 | +
|
| 8 | +A PDF is a plain object file; this emits the minimum this skill needs: pages |
| 9 | +(landscape A4), the two standard Helvetica fonts (no embedding), wrapped text, |
| 10 | +tables with wrapped cells and automatic page breaks, filled/stroked rectangles, |
| 11 | +and a per-page footer. Text is measured with the published Helvetica AFM widths |
| 12 | +so wrapping is real, not guessed. No third-party dependency — the Tina4 way. |
| 13 | +
|
| 14 | +Coordinates in the layout API are top-origin (y grows downward); the writer |
| 15 | +flips to PDF's bottom-origin space. Content streams are left uncompressed so the |
| 16 | +self-test can assert the text it should contain. |
| 17 | +""" |
| 18 | + |
| 19 | +# Helvetica AFM advance widths (units per 1000 em) for ASCII 32..126. |
| 20 | +_HELV = { |
| 21 | + " ": 278, "!": 278, '"': 355, "#": 556, "$": 556, "%": 889, "&": 667, "'": 191, |
| 22 | + "(": 333, ")": 333, "*": 389, "+": 584, ",": 278, "-": 333, ".": 278, "/": 278, |
| 23 | + "0": 556, "1": 556, "2": 556, "3": 556, "4": 556, "5": 556, "6": 556, "7": 556, |
| 24 | + "8": 556, "9": 556, ":": 278, ";": 278, "<": 584, "=": 584, ">": 584, "?": 556, |
| 25 | + "@": 1015, "A": 667, "B": 667, "C": 722, "D": 722, "E": 667, "F": 611, "G": 778, |
| 26 | + "H": 722, "I": 278, "J": 500, "K": 667, "L": 556, "M": 833, "N": 722, "O": 778, |
| 27 | + "P": 667, "Q": 778, "R": 722, "S": 667, "T": 611, "U": 722, "V": 667, "W": 944, |
| 28 | + "X": 667, "Y": 667, "Z": 611, "[": 278, "\\": 278, "]": 278, "^": 469, "_": 556, |
| 29 | + "`": 333, "a": 556, "b": 556, "c": 500, "d": 556, "e": 556, "f": 278, "g": 556, |
| 30 | + "h": 556, "i": 222, "j": 222, "k": 500, "l": 222, "m": 833, "n": 556, "o": 556, |
| 31 | + "p": 556, "q": 556, "r": 333, "s": 500, "t": 278, "u": 556, "v": 500, "w": 722, |
| 32 | + "x": 500, "y": 500, "z": 500, "{": 334, "|": 260, "}": 334, "~": 584, |
| 33 | +} |
| 34 | +_DEFAULT_W = 556 |
| 35 | +# Helvetica-Bold is wider; scale up a little so wrapping never overflows. |
| 36 | +_BOLD_FACTOR = 1.05 |
| 37 | + |
| 38 | + |
| 39 | +def text_width(s, size, bold=False): |
| 40 | + w = sum(_HELV.get(ch, _DEFAULT_W) for ch in s) |
| 41 | + if bold: |
| 42 | + w *= _BOLD_FACTOR |
| 43 | + return w * size / 1000.0 |
| 44 | + |
| 45 | + |
| 46 | +def _wrap(s, max_w, size, bold=False): |
| 47 | + """Greedy word wrap to max_w points. Long words are hard-split.""" |
| 48 | + out = [] |
| 49 | + for para in str(s).split("\n"): |
| 50 | + words = para.split(" ") |
| 51 | + line = "" |
| 52 | + for word in words: |
| 53 | + cand = word if not line else line + " " + word |
| 54 | + if text_width(cand, size, bold) <= max_w or not line: |
| 55 | + # a single word longer than the column: hard-split it |
| 56 | + if not line and text_width(word, size, bold) > max_w: |
| 57 | + piece = "" |
| 58 | + for ch in word: |
| 59 | + if text_width(piece + ch, size, bold) > max_w and piece: |
| 60 | + out.append(piece) |
| 61 | + piece = ch |
| 62 | + else: |
| 63 | + piece += ch |
| 64 | + line = piece |
| 65 | + else: |
| 66 | + line = cand |
| 67 | + else: |
| 68 | + out.append(line) |
| 69 | + line = word |
| 70 | + out.append(line) |
| 71 | + return out or [""] |
| 72 | + |
| 73 | + |
| 74 | +def _pdf_text(s): |
| 75 | + return (str(s).encode("latin-1", "replace").decode("latin-1") |
| 76 | + .replace("\\", "\\\\").replace("(", "\\(").replace(")", "\\)")) |
| 77 | + |
| 78 | + |
| 79 | +def _rgb(hex6): |
| 80 | + return (int(hex6[0:2], 16) / 255.0, int(hex6[2:4], 16) / 255.0, int(hex6[4:6], 16) / 255.0) |
| 81 | + |
| 82 | + |
| 83 | +class Page: |
| 84 | + def __init__(self, w, h): |
| 85 | + self.w, self.h = w, h |
| 86 | + self.ops = [] |
| 87 | + |
| 88 | + def rect(self, x, y_top, w, h, fill=None, stroke=None, line=0.5): |
| 89 | + ll_y = self.h - (y_top + h) |
| 90 | + if fill: |
| 91 | + r, g, b = _rgb(fill) |
| 92 | + self.ops.append(f"{r:.3f} {g:.3f} {b:.3f} rg {x:.2f} {ll_y:.2f} {w:.2f} {h:.2f} re f") |
| 93 | + if stroke: |
| 94 | + r, g, b = _rgb(stroke) |
| 95 | + self.ops.append(f"{line:.2f} w {r:.3f} {g:.3f} {b:.3f} RG " |
| 96 | + f"{x:.2f} {ll_y:.2f} {w:.2f} {h:.2f} re S") |
| 97 | + |
| 98 | + def text(self, x, baseline_top, s, size, bold=False, color="000000"): |
| 99 | + r, g, b = _rgb(color) |
| 100 | + font = "F2" if bold else "F1" |
| 101 | + self.ops.append(f"BT /{font} {size:.2f} Tf {r:.3f} {g:.3f} {b:.3f} rg " |
| 102 | + f"{x:.2f} {self.h - baseline_top:.2f} Td ({_pdf_text(s)}) Tj ET") |
| 103 | + |
| 104 | + def stream(self): |
| 105 | + return "\n".join(self.ops).encode("latin-1", "replace") |
| 106 | + |
| 107 | + |
| 108 | +class Document: |
| 109 | + """Top-origin flowing layout with automatic pagination.""" |
| 110 | + |
| 111 | + def __init__(self, width=842, height=595, margin=43, bottom=40, footer=None): |
| 112 | + self.w, self.h = width, height |
| 113 | + self.ml = self.mr = margin |
| 114 | + self.mt = margin |
| 115 | + self.mb = bottom |
| 116 | + self.footer = footer # callable(page, page_number) or None |
| 117 | + self.cx = self.ml |
| 118 | + self.cw = width - self.ml - self.mr |
| 119 | + self.pages = [] |
| 120 | + self.y = self.mt |
| 121 | + self._new_page() |
| 122 | + |
| 123 | + def _new_page(self): |
| 124 | + self.page = Page(self.w, self.h) |
| 125 | + self.pages.append(self.page) |
| 126 | + self.y = self.mt |
| 127 | + if self.footer: |
| 128 | + self.footer(self.page, len(self.pages)) |
| 129 | + |
| 130 | + def page_break(self): |
| 131 | + self._new_page() |
| 132 | + |
| 133 | + def space(self, h): |
| 134 | + self.y += h |
| 135 | + |
| 136 | + def _ensure(self, h): |
| 137 | + if self.y + h > self.h - self.mb: |
| 138 | + self._new_page() |
| 139 | + |
| 140 | + def rule(self, color="F5A623", thickness=2, space_before=2, space_after=6): |
| 141 | + self.y += space_before |
| 142 | + self._ensure(thickness) |
| 143 | + self.page.rect(self.cx, self.y, self.cw, thickness, fill=color) |
| 144 | + self.y += thickness + space_after |
| 145 | + |
| 146 | + def para(self, text, size=9.5, bold=False, color="111827", leading=None, |
| 147 | + space_after=4, runs=None): |
| 148 | + leading = leading or size + 3.5 |
| 149 | + # `runs` lets a paragraph mix bold/plain: list of (text, bold). Width is |
| 150 | + # measured per run; wrapping falls back to the plain path when absent. |
| 151 | + if runs is None: |
| 152 | + lines = _wrap(text, self.cw, size, bold) |
| 153 | + for ln in lines: |
| 154 | + self._ensure(leading) |
| 155 | + self.page.text(self.cx, self.y + size, ln, size, bold, color) |
| 156 | + self.y += leading |
| 157 | + else: |
| 158 | + # simple single-line-friendly mixed runs, wrapped as one logical line |
| 159 | + flat = "".join(t for t, _ in runs) |
| 160 | + lines = _wrap(flat, self.cw, size, False) |
| 161 | + for ln in lines: |
| 162 | + self._ensure(leading) |
| 163 | + self.page.text(self.cx, self.y + size, ln, size, False, color) |
| 164 | + self.y += leading |
| 165 | + self.y += space_after |
| 166 | + |
| 167 | + def heading(self, text, size=15, color="1F2937", space_before=6, space_after=2): |
| 168 | + self.y += space_before |
| 169 | + self._ensure(size + 4) |
| 170 | + self.page.text(self.cx, self.y + size, text, size, True, color) |
| 171 | + self.y += size + space_after |
| 172 | + |
| 173 | + def subheading(self, text, size=10.5, color="1D4ED8", meta=None, space_before=8): |
| 174 | + self.y += space_before |
| 175 | + self._ensure(size + 4) |
| 176 | + self.page.text(self.cx, self.y + size, text, size, True, color) |
| 177 | + self.y += size + 2 |
| 178 | + if meta: |
| 179 | + self._ensure(11) |
| 180 | + self.page.text(self.cx, self.y + 7.5, meta, 7.5, False, "6B7280") |
| 181 | + self.y += 11 |
| 182 | + |
| 183 | + def table(self, headers, rows, widths, *, font_size=8, header_bg="1F2937", |
| 184 | + header_fg="FFFFFF", grid="D1D5DB", zebra=None, total_last=False, |
| 185 | + pad=3, bold_cols=()): |
| 186 | + leading = font_size + 2 |
| 187 | + |
| 188 | + def row_height(cells): |
| 189 | + n = 1 |
| 190 | + for text, w in zip(cells, widths): |
| 191 | + n = max(n, len(_wrap(text, w - 2 * pad, font_size))) |
| 192 | + return n * leading + 2 * pad |
| 193 | + |
| 194 | + def draw_row(cells, y, bg=None, bold=False): |
| 195 | + h = row_height(cells) |
| 196 | + x = self.cx |
| 197 | + for ci, (text, w) in enumerate(zip(cells, widths)): |
| 198 | + if bg: |
| 199 | + self.page.rect(x, y, w, h, fill=bg) |
| 200 | + self.page.rect(x, y, w, h, stroke=grid, line=0.4) |
| 201 | + b = bold or ci in bold_cols |
| 202 | + ty = y + pad |
| 203 | + for ln in _wrap(text, w - 2 * pad, font_size): |
| 204 | + self.page.text(x + pad, ty + font_size, ln, font_size, b, |
| 205 | + header_fg if bg == header_bg else "111827") |
| 206 | + ty += leading |
| 207 | + x += w |
| 208 | + return h |
| 209 | + |
| 210 | + def draw_header(y): |
| 211 | + return draw_row(headers, y, bg=header_bg) |
| 212 | + |
| 213 | + self._ensure(row_height(headers) + row_height(rows[0]) if rows else row_height(headers)) |
| 214 | + self.y += draw_header(self.y) |
| 215 | + for i, cells in enumerate(rows): |
| 216 | + h = row_height(cells) |
| 217 | + if self.y + h > self.h - self.mb: |
| 218 | + self._new_page() |
| 219 | + self.y += draw_header(self.y) |
| 220 | + bg = None |
| 221 | + if total_last and i == len(rows) - 1: |
| 222 | + bg = "F3F4F6" |
| 223 | + elif zebra: |
| 224 | + bg = zebra[i % 2] |
| 225 | + self.y += draw_row(cells, self.y, bg=bg, bold=total_last and i == len(rows) - 1) |
| 226 | + |
| 227 | + # ---- serialisation ----------------------------------------------- |
| 228 | + def save(self, path): |
| 229 | + objs = [] |
| 230 | + |
| 231 | + def add(body): |
| 232 | + objs.append(body) |
| 233 | + return len(objs) # 1-based object number |
| 234 | + |
| 235 | + # 1 catalog, 2 pages, fonts, then page + content pairs |
| 236 | + font_regular = add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica " |
| 237 | + b"/Encoding /WinAnsiEncoding >>") |
| 238 | + font_bold = add(b"<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica-Bold " |
| 239 | + b"/Encoding /WinAnsiEncoding >>") |
| 240 | + resources = (f"<< /Font << /F1 {font_regular} 0 R /F2 {font_bold} 0 R >> >>").encode() |
| 241 | + |
| 242 | + page_ids = [] |
| 243 | + # Reserve the Pages object number before the page objects reference it. |
| 244 | + pages_placeholder = add(b"") # overwritten once the page ids are known |
| 245 | + for pg in self.pages: |
| 246 | + content = pg.stream() |
| 247 | + stream_num = add(b"<< /Length %d >>\nstream\n%s\nendstream" % (len(content), content)) |
| 248 | + page_num = add((f"<< /Type /Page /Parent {pages_placeholder} 0 R " |
| 249 | + f"/MediaBox [0 0 {self.w} {self.h}] " |
| 250 | + f"/Resources {resources.decode()} " |
| 251 | + f"/Contents {stream_num} 0 R >>").encode()) |
| 252 | + page_ids.append(page_num) |
| 253 | + kids = " ".join(f"{n} 0 R" for n in page_ids) |
| 254 | + objs[pages_placeholder - 1] = (f"<< /Type /Pages /Count {len(page_ids)} " |
| 255 | + f"/Kids [{kids}] >>").encode() |
| 256 | + catalog = add(f"<< /Type /Catalog /Pages {pages_placeholder} 0 R >>".encode()) |
| 257 | + |
| 258 | + out = bytearray(b"%PDF-1.4\n%\xe2\xe3\xcf\xd3\n") |
| 259 | + offsets = [0] |
| 260 | + for i, body in enumerate(objs, 1): |
| 261 | + offsets.append(len(out)) |
| 262 | + out += f"{i} 0 obj\n".encode() + body + b"\nendobj\n" |
| 263 | + xref_pos = len(out) |
| 264 | + out += f"xref\n0 {len(objs) + 1}\n".encode() |
| 265 | + out += b"0000000000 65535 f \n" |
| 266 | + for off in offsets[1:]: |
| 267 | + out += f"{off:010d} 00000 n \n".encode() |
| 268 | + out += (f"trailer\n<< /Size {len(objs) + 1} /Root {catalog} 0 R >>\n" |
| 269 | + f"startxref\n{xref_pos}\n%%EOF\n").encode() |
| 270 | + with open(path, "wb") as f: |
| 271 | + f.write(out) |
0 commit comments