Changing the objects in a PDF document is a non-trivial task. In this particular case, the references you can get via the dictionary access are suitable for reading, but not for assignment. Instead of page[NameObject("/Contents")] = contents
, you may use page.replace_contents(contents)
. I ran into the same problem when I first wrote https://github.com/hoehermann/pypdf_strreplace/.