PyPDF2:为什么PdfileWriter会忘记我对文档所做的更改?

2024-09-23 10:31:32 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图修改PDF文件中的文本。文本可以是TjBDC类型的对象。我找到了正确的对象,如果在更改后直接读取它们,它们会显示更新后的值。在

但是如果我把完整的页面传递给PdfFileWriter,更改就会丢失。我可能在更新一个副本,而不是真正的对象。我检查了id(),结果是不同的。有人知道怎么解决这个问题吗?在

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()

Tags: 对象from文本importsourceoutputpdfpage