"""Parse a PDF page content stream (already inflated) into painted shapes. For every painted path it records: fill/stroke colour, the CTM translation, the bounding box in page coordinates, the centre, and a shape signature (operators and rounded relative coordinates), so that repeated markers in a vector chart can be found and counted. Pure Python; reads data only. Usage: python3 -I vector_shapes.py """ import json import re import sys TOK = re.compile(rb"\((?:\\.|[^\\)])*\)|<[0-9A-Fa-f\s]*>|/[^\s/\[\]()<>]+|\[|\]|[-+]?\d*\.\d+|[-+]?\d+|[A-Za-z'\"*]+[0-9]?\*?") def mul(a, b): # 2D affine [a b c d e f] multiply: 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]) def parse(buf): toks = TOK.findall(buf) stack = [] ctm = [1, 0, 0, 1, 0, 0] gstack = [] fill = None stroke = None path = [] # list of (op, [points in user space]) shapes = [] in_text = False for t in toks: if re.fullmatch(rb"[-+]?\d*\.\d+|[-+]?\d+", t): stack.append(float(t)) continue if t.startswith(b"/") or t.startswith(b"(") or t.startswith(b"<") or t in (b"[", b"]"): stack.append(t) continue op = t if op == b"BT": in_text = True elif op == b"ET": in_text = False elif op == b"q": gstack.append((ctm[:], fill, stroke)) elif op == b"Q": if gstack: ctm, fill, stroke = gstack.pop() elif op == b"cm": m = [float(v) for v in stack[-6:]] ctm = mul(m, ctm) elif op in (b"scn", b"sc"): fill = tuple(round(float(v), 4) for v in stack if isinstance(v, float)) elif op in (b"SCN", b"SC"): stroke = tuple(round(float(v), 4) for v in stack if isinstance(v, float)) elif op == b"rg" or op == b"g" or op == b"k": fill = (op.decode(),) + tuple(round(float(v), 4) for v in stack if isinstance(v, float)) elif op == b"RG" or op == b"G" or op == b"K": stroke = (op.decode(),) + tuple(round(float(v), 4) for v in stack if isinstance(v, float)) elif op == b"m": path.append(("m", [tuple(stack[-2:])])) elif op == b"l": path.append(("l", [tuple(stack[-2:])])) elif op == b"c": v = stack[-6:] path.append(("c", [(v[0], v[1]), (v[2], v[3]), (v[4], v[5])])) elif op in (b"v", b"y"): v = stack[-4:] path.append((op.decode(), [(v[0], v[1]), (v[2], v[3])])) elif op == b"re": x, y, w, h = stack[-4:] path.append(("re", [(x, y), (x + w, y + h)])) elif op == b"h": path.append(("h", [])) elif op in (b"f", b"F", b"f*", b"S", b"s", b"B", b"B*", b"b", b"b*", b"n"): if path and op != b"n": pts = [apply(ctm, *p) for _, ps in path for p in ps] xs = [p[0] for p in pts] ys = [p[1] for p in pts] sig = " ".join(o + ":" + ",".join(f"{a:.2f},{b:.2f}" for a, b in ps) for o, ps in path) shapes.append({ "paint": op.decode(), "fill": fill, "stroke": stroke, "tx": round(ctm[4], 3), "ty": round(ctm[5], 3), "bbox": [round(min(xs), 3), round(min(ys), 3), round(max(xs), 3), round(max(ys), 3)], "cx": round((min(xs) + max(xs)) / 2, 3), "cy": round((min(ys) + max(ys)) / 2, 3), "nseg": len(path), "sig": sig, }) path = [] stack = [] return shapes def main(): buf = open(sys.argv[1], "rb").read() shapes = parse(buf) with open(sys.argv[2], "w", encoding="utf-8", newline="\n") as f: json.dump(shapes, f, indent=0) print(len(shapes), "painted paths") if __name__ == "__main__": main()