#!/usr/bin/env python3 """List and save the raster images embedded in a PDF, so that its figures can be read by eye. Pure Python plus Pillow; the PDF is read as data and nothing in it is executed. Run with `python3 -I`. Usage: python3 -I extract_pdf_images.py """ import re import sys import zlib from pathlib import Path from PIL import Image pdf = Path(sys.argv[1]).read_bytes() out = Path(sys.argv[2]) out.mkdir(parents=True, exist_ok=True) OBJ = re.compile(rb"(\d+) (\d+) obj\b") count = 0 pos = 0 while True: i = pdf.find(b"/Subtype", pos) if i < 0: break pos = i + 8 if not re.match(rb"/Subtype\s*/Image", pdf[i:i + 24]): continue start = pdf.rfind(b" obj", 0, i) stream = pdf.find(b"stream", i) if start < 0 or stream < 0: continue head = pdf[start:stream] data_start = stream + 6 if pdf[data_start:data_start + 2] == b"\r\n": data_start += 2 elif pdf[data_start:data_start + 1] in (b"\n", b"\r"): data_start += 1 length_match = re.search(rb"/Length (\d+)(?! \d+ R)", head) if length_match: data_end = data_start + int(length_match.group(1)) else: data_end = pdf.find(b"endstream", data_start) data = pdf[data_start:data_end] width = int(re.search(rb"/Width (\d+)", head).group(1)) height = int(re.search(rb"/Height (\d+)", head).group(1)) bits = re.search(rb"/BitsPerComponent (\d+)", head) bits = int(bits.group(1)) if bits else 0 space = re.search(rb"/ColorSpace\s*(/\w+|\[[^\]]*\]|\d+ \d+ R)", head) space = space.group(1).decode("latin1") if space else "?" flt = re.search(rb"/Filter\s*(\[[^\]]*\]|/\w+)", head) flt = flt.group(1).decode("latin1") if flt else "none" is_smask = b"/SMask" not in head and space == "/DeviceGray" and width > 0 name = f"img{count:03d}_{width}x{height}" count += 1 print(name, "bits", bits, "space", space, "filter", flt, "bytes", len(data)) target = None if "DCT" in flt: target = out / (name + ".jpg") target.write_bytes(data) elif "JPX" in flt: target = out / (name + ".jp2") target.write_bytes(data) elif "Flate" in flt and bits == 8: raw = zlib.decompress(data) # The colour space may be an indirect reference; the raw length tells the channels. channels = len(raw) // (width * height) if channels in (1, 3, 4) and len(raw) == width * height * channels: mode = {3: "RGB", 1: "L", 4: "CMYK"}[channels] Image.frombytes(mode, (width, height), raw).convert("RGB").save(out / (name + ".png")) target = out / (name + ".png") else: print(" (not decoded: colour space or predictor needs more handling; raw length", len(raw), ")") if target is not None: print(" saved", target.name) print("images found:", count)