PyPDF2: Why does PdfFileWriter forget changes I made to a document?

末鹿安然 提交于 2019-12-10 20:08:37

问题


I am trying to modify text in a PDF file. The text can be in an object of type Tj or BDC. I find the correct objects and if I read them directly after changing them they show the updated values.

But if I pass the complete page to PdfFileWriter the change is lost. I might be updating a copy and not the real object. I checked the id() and it was different. Does someone have an idea how to fix this?

from PyPDF2 import PdfFileReader, PdfFileWriter
from PyPDF2.pdf import ContentStream
from PyPDF2.generic import TextStringObject, NameObject
from PyPDF2.utils import b_

source = PdfFileReader(open('some.pdf', "rb"))
output = PdfFileWriter()

for page_idx in range(0, 1):

    # Get the current page and it's contents
    page = source.getPage(page_idx)

    content_object = page["/Contents"].getObject()
    content = ContentStream(content_object, source)

    for operands, operator in content.operations:

        if operator == b_("BDC"):

            operands[1][NameObject('/Contents')] = TextStringObject('xyz')

        if operator == b_("Tj"):

            operands[0] = TextStringObject('xyz')

    output.addPage(page)


# Write the stream
outputStream = open("output.pdf", "wb")
output.write(outputStream)
outputStream.close()

回答1:


The solution is to assign the ContentStream that is being iterated and changed to the page afterwards before passing it to the PdfFileWriter:

page[NameObject('/Contents')] = content
output.addPage(page)

I found the solution reading this and this.



来源:https://stackoverflow.com/questions/52499339/pypdf2-why-does-pdffilewriter-forget-changes-i-made-to-a-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!