Skip to content

Escape carriage returns when writing PDF strings - #10733

Open
AresWei wants to merge 2 commits into
python-pillow:mainfrom
AresWei:pdf-escape-carriage-return
Open

AresWei wants to merge 2 commits into
python-pillow:mainfrom
AresWei:pdf-escape-carriage-return

Conversation

@AresWei

@AresWei AresWei commented Dec 4, 2026

Copy link
Copy Markdown

Origin: B) AI found a possible change because I asked it do so

My contribution includes AI-generated content, as disclosed below:

  • AI Tools: Claude Code
  • LLMs and versions: Claude Opus 5.5
  • Prompts: Asked it to look for small, verifiable bugs in Pillow; it pointed me at the closed Preserve carriage return bytes when writing PDF strings #10182. I then asked it to reproduce the corruption, locate the exact reader code, and write a minimal fix with tests. I reran the reproduction and reviewed the diff myself.

This is the same fix as #10182, which was closed after the question there went unanswered. To answer it:

Could you point to the part of PdfParser that performs this normalization?

PdfParser.get_literal_string(). In re_lit_str_token, group 5 is an unescaped \r\n, \r or \n, and

elif m.group(5):
    result.extend(b"\n")

turns each of them into a single \n. This follows PDF 32000-1:2008 section 7.3.4.2: an end-of-line marker in a literal string without a preceding backslash "shall be treated as a byte value of (0Ah), irrespective of whether the end-of-line marker was a CARRIAGE RETURN (0Dh), a LINE FEED (0Ah), or both". It only applies to (...) literal strings; hex strings are unaffected, and names already write \r as #0D.

It matters because pdf_repr() writes str values as UTF-16BE inside a literal string, without escaping \r. Any character with a 0x0D byte comes back different:

im.save("out.pdf", title="Mečiar", author="不")
# PdfParser reads back Title "MeĊiar", Author "上"

Every Malayalam and Sinhala character has 0x0D as its high byte, so a subject like "മലയാളം" comes back as "ਮਲਯਾਲ਼ਂ", and "ഊ" (U+0D0A) loses a byte and raises UnicodeDecodeError when read. qpdf shows the same corruption on files written before this change.

Changes proposed in this pull request:

  • Escape \r as \\r in pdf_repr() for bytes
  • Add a pdf_repr assertion, and a test that saves a PDF with these values and reads them back
  • Add a release note

@radarhere radarhere added fix-without-cause A bug fix or feature implementation without a reason to exist other than AI. 🤖-assisted AI-assisted labels Dec 4, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

🤖-assisted AI-assisted fix-without-cause A bug fix or feature implementation without a reason to exist other than AI.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants