#4127·pypdf

`PdfReader` 无法打开文件,其 `%%EOF` 标记不在行的开头 (`startxref <offset>%%EOF`)

作者: dexters1创建于 2026年9月23日更新于 2026年9月24日
标签is-robustness-issue

import io import re from pypdf import PdfReader, PdfWriter writer = PdfWriter() writer.add_blank_page(200, 200) buffer = io.BytesIO() writer.write(buffer) data = buffer.getvalue() # ends with b">>\nstartxref\n\n%%EOF\n"

Same bytes, only the whitespace in the last line changed: "%%EOF" follows the offset directly.

compact = re.sub(b"startxref\s+(\d+)\s+%%EOF\s*$", b"startxref \1%%EOF", data) print(data[-25:], "->", compact[-25:]) for strict in (True, False): print(len(PdfReader(io.BytesIO(data), strict=strict).pages)) # 1 for strict in (True, False): try: PdfReader(io.BytesIO(compact), strict=strict) except Exception as exc: print(f"strict={strict}: {type(exc).name}: {exc}") Output: b'R\n>>\nstartxref\n256\n%%EOF\n' -> b'0 R\n>>\nstartxref 256%%EOF' 1 1 strict=True: PdfReadError: EOF marker not found strict=False: PdfStreamError: Stream has ended unexpectedly