"""Render the vector drawing of a PDF Form XObject (a figure) to PNG and dump its polylines and text as JSON. Usage: python3 -I pdf_vector.py PDF OBJNUM OUTPREFIX [WIDTH_PX] Reads the PDF as data with pdf_objects.py's reader. Interprets the path, colour, transform and text operators of the form's content stream (and of nested forms), ignoring clipping and shading. Writes OUTPREFIX.png and OUTPREFIX.json: {"bbox": [...], "paths": [{"stroke": rgb, "fill": rgb, "lw": w, "op": op, "pts": [[x, y], ...]}], "texts": [{"x":, "y":, "s":, "size":}]} in the form's own coordinates (y up). Nothing in the PDF is executed. """ import json import math import os import re import sys sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) import pdf_objects as po # noqa: E402 TOKEN_RE = re.compile( rb"\s*(?:(%[^\r\n]*)|(\[|\]|<<|>>)|(/[^\s/\[\]()<>{}%]*)|(\((?:\\.|[^\\)])*\))|(<[0-9A-Fa-f\s]*>)|" rb"([+-]?(?:\d+\.?\d*|\.\d+))|([A-Za-z'\"*][A-Za-z0-9'\"*]*))", re.S, ) def unescape_pdf_string(b): out = bytearray() i = 0 while i < len(b): c = b[i] if c == 0x5C and i + 1 < len(b): n = b[i + 1] if n in b"nrtbf": out.append({ord("n"): 10, ord("r"): 13, ord("t"): 9, ord("b"): 8, ord("f"): 12}[n]) i += 2 elif 0x30 <= n <= 0x37: j = i + 1 k = j while k < len(b) and k < j + 3 and 0x30 <= b[k] <= 0x37: k += 1 out.append(int(b[j:k], 8) & 255) i = k else: out.append(n) i += 2 else: out.append(c) i += 1 return bytes(out) def tokenize(data): pos = 0 n = len(data) # handle nested parentheses in strings crudely: the regex handles escaped parens only while pos < n: m = TOKEN_RE.match(data, pos) if not m or m.end() == pos: pos += 1 continue pos = m.end() if m.group(1): continue if m.group(2): yield ("delim", m.group(2)) elif m.group(3): yield ("name", m.group(3)[1:].decode("latin-1")) elif m.group(4): yield ("str", unescape_pdf_string(m.group(4)[1:-1])) elif m.group(5): h = re.sub(rb"\s", b"", m.group(5)[1:-1]) if len(h) % 2: h += b"0" yield ("str", bytes.fromhex(h.decode())) elif m.group(6): yield ("num", float(m.group(6))) elif m.group(7): yield ("op", m.group(7).decode("latin-1")) def matmul(a, b): # a, b = [a b c d e f]; returns a*b (apply a then b) return [ a[0] * b[0] + a[1] * b[2], a[0] * b[1] + a[1] * b[3], a[2] * b[0] + a[3] * b[2], a[2] * b[1] + a[3] * b[3], a[4] * b[0] + a[5] * b[2] + b[4], a[4] * b[1] + a[5] * b[3] + b[5], ] def apply(m, x, y): return (m[0] * x + m[2] * y + m[4], m[1] * x + m[3] * y + m[5]) class Renderer: def __init__(self, parsed, objs): self.parsed = parsed self.objs = objs self.paths = [] self.texts = [] def resources_xobjects(self, d): """Map XObject names to object numbers for a form dict (resources may be indirect).""" res = {} rm = re.search(rb"/Resources\s*(\d+)\s+0\s+R", d) rd = self.parsed.get(int(rm.group(1)), (b"", None))[0] if rm else d xm = re.search(rb"/XObject\s*(\d+)\s+0\s+R", rd) xd = self.parsed.get(int(xm.group(1)), (b"", None))[0] if xm else rd blk = re.search(rb"/XObject\s*<<(.*?)>>", rd, re.S) src = blk.group(1) if blk else xd for nm, num in re.findall(rb"/([^\s/<>\[\]]+)\s+(\d+)\s+0\s+R", src): res[nm.decode("latin-1")] = int(num) return res def run_form(self, num, ctm, depth=0): d, s = self.parsed[num] content = po.decode_stream(d, s, self.objs) mm = re.search(rb"/Matrix\s*\[([^\]]*)\]", d) if mm: fm = [float(v) for v in mm.group(1).split()] ctm = matmul(fm, ctm) xobjs = self.resources_xobjects(d) self.run(content, ctm, xobjs, depth) def run(self, content, ctm, xobjs, depth): stack = [] gs = {"ctm": ctm, "stroke": (0, 0, 0), "fill": (0, 0, 0), "lw": 1.0} gstack = [] path = [] # list of subpaths, each a list of points (device coords) cur = None text = {"tm": [1, 0, 0, 1, 0, 0], "tlm": [1, 0, 0, 1, 0, 0], "size": 10, "lead": 0} arr_stack = [] for kind, val in tokenize(content): if kind == "delim": if val == b"[": arr_stack.append(stack) stack = [] elif val == b"]": arr = stack stack = arr_stack.pop() stack.append(("arr", arr)) elif val in (b"<<", b">>"): pass continue if kind != "op": stack.append((kind, val)) continue op = val nums = [v for k, v in stack if k == "num"] try: if op == "q": gstack.append(dict(gs)) elif op == "Q": if gstack: gs = gstack.pop() elif op == "cm" and len(nums) >= 6: gs["ctm"] = matmul(nums[-6:], gs["ctm"]) elif op == "w" and nums: gs["lw"] = nums[-1] elif op in ("RG", "SC", "SCN") and len(nums) >= 3: gs["stroke"] = tuple(nums[-3:]) elif op in ("rg", "sc", "scn") and len(nums) >= 3: gs["fill"] = tuple(nums[-3:]) elif op == "G" and nums: gs["stroke"] = (nums[-1],) * 3 elif op == "g" and nums: gs["fill"] = (nums[-1],) * 3 elif op in ("SC", "SCN") and len(nums) == 1: gs["stroke"] = (nums[-1],) * 3 elif op in ("sc", "scn") and len(nums) == 1: gs["fill"] = (nums[-1],) * 3 elif op == "K" and len(nums) >= 4: c, m_, y, k = nums[-4:] gs["stroke"] = ((1 - c) * (1 - k), (1 - m_) * (1 - k), (1 - y) * (1 - k)) elif op == "k" and len(nums) >= 4: c, m_, y, k = nums[-4:] gs["fill"] = ((1 - c) * (1 - k), (1 - m_) * (1 - k), (1 - y) * (1 - k)) elif op == "m" and len(nums) >= 2: cur = [apply(gs["ctm"], nums[-2], nums[-1])] path.append(cur) elif op == "l" and len(nums) >= 2: if cur is None: cur = [] path.append(cur) cur.append(apply(gs["ctm"], nums[-2], nums[-1])) elif op in ("c", "v", "y") and len(nums) >= 4: if cur is None: cur = [] path.append(cur) cur.append(apply(gs["ctm"], nums[-2], nums[-1])) elif op == "h": if cur: cur.append(cur[0]) elif op == "re" and len(nums) >= 4: x, y, w, h = nums[-4:] pts = [(x, y), (x + w, y), (x + w, y + h), (x, y + h), (x, y)] cur = [apply(gs["ctm"], px, py) for px, py in pts] path.append(cur) elif op in ("S", "s", "f", "F", "f*", "B", "B*", "b", "b*", "n"): if op != "n": for sp in path: if len(sp) >= 1: lw = gs["lw"] * math.sqrt(abs(gs["ctm"][0] * gs["ctm"][3] - gs["ctm"][1] * gs["ctm"][2])) self.paths.append({ "stroke": [round(c, 3) for c in gs["stroke"]] if op in ("S", "s", "B", "B*", "b", "b*") else None, "fill": [round(c, 3) for c in gs["fill"]] if op in ("f", "F", "f*", "B", "B*", "b", "b*") else None, "lw": round(lw, 3), "op": op, "pts": [[round(px, 3), round(py, 3)] for px, py in sp], }) path = [] cur = None elif op == "BT": text["tm"] = [1, 0, 0, 1, 0, 0] text["tlm"] = [1, 0, 0, 1, 0, 0] elif op == "Tf" and nums: text["size"] = nums[-1] elif op == "TL" and nums: text["lead"] = nums[-1] elif op in ("Td", "TD") and len(nums) >= 2: text["tlm"] = matmul([1, 0, 0, 1, nums[-2], nums[-1]], text["tlm"]) text["tm"] = list(text["tlm"]) if op == "TD": text["lead"] = -nums[-1] elif op == "Tm" and len(nums) >= 6: text["tlm"] = list(nums[-6:]) text["tm"] = list(nums[-6:]) elif op == "T*": text["tlm"] = matmul([1, 0, 0, 1, 0, -text["lead"]], text["tlm"]) text["tm"] = list(text["tlm"]) elif op in ("Tj", "'", '"', "TJ"): if op in ("'", '"'): text["tlm"] = matmul([1, 0, 0, 1, 0, -text["lead"]], text["tlm"]) text["tm"] = list(text["tlm"]) s = b"" if op == "TJ": for k, v in stack: if k == "arr": for k2, v2 in v: if k2 == "str": s += v2 else: for k, v in stack: if k == "str": s += v m = matmul(text["tm"], gs["ctm"]) x, y = m[4], m[5] size = text["size"] * math.sqrt(abs(m[0] * m[3] - m[1] * m[2])) self.texts.append({"x": round(x, 2), "y": round(y, 2), "s": s.decode("latin-1"), "size": round(size, 2), "angle": round(math.degrees(math.atan2(m[1], m[0])), 1)}) elif op == "Do": names = [v for k, v in stack if k == "name"] if names and names[-1] in xobjs and depth < 6: onum = xobjs[names[-1]] od = self.parsed.get(onum, (b"", None))[0] if re.search(rb"/Subtype\s*/Form", od): self.run_form(onum, gs["ctm"], depth + 1) except Exception as e: # keep going on odd operators print(f"warn: op {op}: {e}", file=sys.stderr) stack = [] def main(): pdf, objnum, outprefix = sys.argv[1], int(sys.argv[2]), sys.argv[3] width = int(sys.argv[4]) if len(sys.argv) > 4 else 2400 data, objs, parsed = po.read_pdf(pdf) r = Renderer(parsed, objs) d, _ = parsed[objnum] bb = [float(v) for v in re.search(rb"/BBox\s*\[([^\]]*)\]", d).group(1).split()] r.run_form(objnum, [1, 0, 0, 1, 0, 0]) json.dump({"bbox": bb, "paths": r.paths, "texts": r.texts}, open(outprefix + ".json", "w", encoding="utf-8", newline="\n")) from PIL import Image, ImageDraw x0, y0, x1, y1 = bb sc = width / (x1 - x0) H = int((y1 - y0) * sc) + 1 img = Image.new("RGB", (width, H), "white") dr = ImageDraw.Draw(img) def tr(p): return ((p[0] - x0) * sc, H - (p[1] - y0) * sc) for p in r.paths: pts = [tr(q) for q in p["pts"]] if p["fill"] is not None and len(pts) >= 3 and p["stroke"] is None: col = tuple(int(255 * c) for c in p["fill"]) dr.polygon(pts, fill=col) if p["stroke"] is not None and len(pts) >= 2: col = tuple(int(255 * c) for c in p["stroke"]) dr.line(pts, fill=col, width=max(1, int(p["lw"] * sc))) for t in r.texts: x, y = tr((t["x"], t["y"])) dr.text((x, y - t["size"] * sc), t["s"], fill=(0, 0, 160)) img.save(outprefix + ".png") print(outprefix + ".png", img.size, len(r.paths), "paths", len(r.texts), "texts") if __name__ == "__main__": main()