python - 为什么 PyPDF2.PdfFileWriter 会忘记我对文档所做的更改?

标签 python python-3.x pdf pdf-generation pypdf

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

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

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

reader = PdfFileReader("some.pdf")
writer = PdfFileWriter()

for page_idx in range(0, 1):

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

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

    for operands, operator in content.operations:

        if operator == b_("BDC"):

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

        if operator == b_("Tj"):

            operands[0] = TextStringObject("xyz")

    writer.addPage(page)


# Write the stream
with open("output.pdf", "wb") as fp:
    writer.write(fp)

最佳答案

解决方法是将正在迭代更改的ContentStream赋值给之后的页面,再传给PdfFileWriter:

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

我找到了阅读 this 的解决方案和 this .

关于python - 为什么 PyPDF2.PdfFileWriter 会忘记我对文档所做的更改?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52499339/

相关文章:

html - 打印或转换为 PDF 时不显示 CSS 边框

Python:以最有效的方式合并许多数据框

python - 如何使用 Matplotlib 在对数刻度上显示次要刻度标签

python - 如何根据字符串列表中的数字对字符串列表进行排序?

python - 使用 Python 中的反汇编程序停止打印函数?

pdf - 如何使用 ColdFusion (&iText) 设置 PDF 版权元数据

php - CODEIGNITER:使用 readfile() 从 Controller 返回 PDF 文件

python:奇怪的列表元素组合

python - 如何在 pandas 中按 user_id 按组从列表列中获取唯一值

python - 如何创建一个 python 字典来存储多个帐户的用户名和密码