PyPDF2:为什么 PdfFileWriter 会忘记我对文档所做的更改? [英] PyPDF2: Why does PdfFileWriter forget changes I made to a document?

查看:44
本文介绍了PyPDF2:为什么 PdfFileWriter 会忘记我对文档所做的更改?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

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

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

推荐答案

解决方案是将正在迭代的 ContentStream 分配给之后的页面,然后再将其传递给 PdfFileWriter:

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)

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

I found the solution reading this and this.

这篇关于PyPDF2:为什么 PdfFileWriter 会忘记我对文档所做的更改?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆