"""Minimal PDF object reader (standard library + Pillow), for looking at figures in PDFs we read as data. Usage: python3 -I pdf_objects.py list PDF # list image XObjects and form XObjects python3 -I pdf_objects.py images PDF OUTDIR # write each raster image as PNG (or JPEG as is) Handles classic xref objects and object streams (/ObjStm), FlateDecode with PNG predictors, DCTDecode, DeviceGray/DeviceRGB/DeviceCMYK/Indexed colour spaces at 8 bits, and 1-bit images. Nothing in the PDF is executed. """ import os import re import sys import zlib OBJ_RE = re.compile(rb"(\d+)\s+(\d+)\s+obj\b") def read_pdf(path): data = open(path, "rb").read() objs = {} for m in OBJ_RE.finditer(data): num = int(m.group(1)) start = m.end() end = data.find(b"endobj", start) if end < 0: continue body = data[start:end] objs[num] = body # later definitions (incremental updates) win # expand object streams parsed = {} for num, body in list(objs.items()): d, s = split_stream(body, objs) parsed[num] = (d, s) for num, (d, s) in list(parsed.items()): if s is not None and re.search(rb"/Type\s*/ObjStm", d): try: raw = decode_stream(d, s, objs) except Exception: continue n = int(re.search(rb"/N\s+(\d+)", d).group(1)) first = int(re.search(rb"/First\s+(\d+)", d).group(1)) header = raw[:first].split() pairs = [(int(header[2 * i]), int(header[2 * i + 1])) for i in range(n)] for i, (onum, off) in enumerate(pairs): a = first + off b = first + pairs[i + 1][1] if i + 1 < n else len(raw) if onum not in parsed: parsed[onum] = (raw[a:b], None) return data, objs, parsed def split_stream(body, objs): m = re.search(rb"stream\r?\n", body) if not m: return body, None d = body[: m.start()] rest = body[m.end():] # honour /Length when it is direct; else cut at endstream lm = re.search(rb"/Length\s+(\d+)(\s+(\d+)\s+R)?", d) length = None if lm and not lm.group(2): length = int(lm.group(1)) elif lm and lm.group(2): ref = int(lm.group(1)) if ref in objs: mm = re.search(rb"\d+", objs[ref]) if mm: length = int(mm.group(0)) if length is not None and length <= len(rest): s = rest[:length] else: e = rest.rfind(b"endstream") s = rest[:e].rstrip(b"\r\n") if e >= 0 else rest return d, s def png_unpredict(raw, colors, bpc, columns): bpp = max(1, colors * bpc // 8) rowlen = (columns * colors * bpc + 7) // 8 out = bytearray() prev = bytearray(rowlen) i = 0 while i < len(raw): ft = raw[i] row = bytearray(raw[i + 1: i + 1 + rowlen]) i += 1 + rowlen if len(row) < rowlen: break for x in range(rowlen): a = row[x - bpp] if x >= bpp else 0 b = prev[x] c = prev[x - bpp] if x >= bpp else 0 if ft == 1: row[x] = (row[x] + a) & 255 elif ft == 2: row[x] = (row[x] + b) & 255 elif ft == 3: row[x] = (row[x] + ((a + b) >> 1)) & 255 elif ft == 4: p = a + b - c pa, pb, pc = abs(p - a), abs(p - b), abs(p - c) pr = a if (pa <= pb and pa <= pc) else (b if pb <= pc else c) row[x] = (row[x] + pr) & 255 out += row prev = row return bytes(out) def decode_stream(d, s, objs): filters = re.findall(rb"/(FlateDecode|DCTDecode|ASCII85Decode|LZWDecode|JPXDecode|CCITTFaxDecode|RunLengthDecode)", d) raw = s for f in filters: if f == b"FlateDecode": raw = zlib.decompress(raw) pm = re.search(rb"/Predictor\s+(\d+)", d) if pm and int(pm.group(1)) >= 10: colors = int((re.search(rb"/Colors\s+(\d+)", d) or [0, b"1"])[1]) if re.search(rb"/Colors\s+(\d+)", d) else 1 bpc_m = re.search(rb"/BitsPerComponent\s+(\d+)", d) cols_m = re.search(rb"/Columns\s+(\d+)", d) bpc = int(bpc_m.group(1)) if bpc_m else 8 cols = int(cols_m.group(1)) if cols_m else 1 raw = png_unpredict(raw, colors, bpc, cols) elif f == b"DCTDecode": return raw # JPEG bytes else: raise ValueError(f"unsupported filter {f!r}") return raw def deref(val, parsed): m = re.fullmatch(rb"\s*(\d+)\s+0\s+R\s*", val) if m: return parsed.get(int(m.group(1)), (b"", None))[0] return val def list_objects(path): data, objs, parsed = read_pdf(path) for num in sorted(parsed): d, s = parsed[num] if re.search(rb"/Subtype\s*/Image", d): w = re.search(rb"/Width\s+(\d+)", d) h = re.search(rb"/Height\s+(\d+)", d) cs = re.search(rb"/ColorSpace\s*(/\w+|\[[^\]]*\]|\d+\s+0\s+R)", d) f = re.findall(rb"/(\w+Decode)", d) print(f"IMAGE obj {num}: {w.group(1).decode() if w else '?'}x{h.group(1).decode() if h else '?'} cs={cs.group(1)[:40] if cs else None} filters={f} bytes={len(s) if s else 0}") elif re.search(rb"/Subtype\s*/Form", d): bb = re.search(rb"/BBox\s*\[([^\]]*)\]", d) print(f"FORM obj {num}: bbox={bb.group(1).decode() if bb else None} bytes={len(s) if s else 0}") def write_images(path, outdir): from PIL import Image os.makedirs(outdir, exist_ok=True) data, objs, parsed = read_pdf(path) for num in sorted(parsed): d, s = parsed[num] if s is None or not re.search(rb"/Subtype\s*/Image", d): continue w = int(re.search(rb"/Width\s+(\d+)", d).group(1)) h = int(re.search(rb"/Height\s+(\d+)", d).group(1)) bpc_m = re.search(rb"/BitsPerComponent\s+(\d+)", d) bpc = int(bpc_m.group(1)) if bpc_m else 8 try: raw = decode_stream(d, s, objs) except Exception as e: # unsupported filter print(f"obj {num}: skipped ({e})") continue if b"/DCTDecode" in d: out = os.path.join(outdir, f"obj{num}.jpg") open(out, "wb").write(raw) print(out, w, h) continue csm = re.search(rb"/ColorSpace\s*(/\w+|\[[^\]]*\]|\d+\s+0\s+R)", d) cs = csm.group(1) if csm else b"/DeviceGray" if re.fullmatch(rb"\d+\s+0\s+R", cs): cs = deref(cs, parsed) mode = None if b"DeviceRGB" in cs or b"ICCBased" in cs and len(raw) >= w * h * 3: mode = "RGB" if b"DeviceGray" in cs or (b"ICCBased" in cs and len(raw) == w * h): mode = "L" if b"DeviceCMYK" in cs: mode = "CMYK" try: if bpc == 1: img = Image.frombytes("1", (w, h), raw) elif b"Indexed" in cs: # [/Indexed base hival lookup] lk = re.search(rb"<([0-9A-Fa-f\s]+)>", cs) lookup = bytes.fromhex(lk.group(1).decode().replace(" ", "").replace("\n", "")) if lk else None if lookup is None: rm = re.search(rb"(\d+)\s+0\s+R\s*\]\s*$", cs.strip()) if rm: ld, ls = parsed[int(rm.group(1))] lookup = decode_stream(ld, ls, objs) img = Image.frombytes("P", (w, h), raw[: w * h]) pal = list(lookup) + [0] * (768 - len(lookup)) img.putpalette(pal[:768]) img = img.convert("RGB") else: img = Image.frombytes(mode or "L", (w, h), raw[: w * h * {"RGB": 3, "L": 1, "CMYK": 4}[mode or "L"]]) if mode == "CMYK": img = img.convert("RGB") except Exception as e: print(f"obj {num}: could not build image ({e}); cs={cs[:60]!r}") continue out = os.path.join(outdir, f"obj{num}.png") img.save(out) print(out, w, h, mode, bpc) if __name__ == "__main__": if sys.argv[1] == "list": list_objects(sys.argv[2]) elif sys.argv[1] == "images": write_images(sys.argv[2], sys.argv[3])