【问题标题】:pdfrw - fill pdf with python, trouble using slice for multiple pagespdfrw - 用 python 填充 pdf,对多个页面使用 slice 时遇到问题
【发布时间】:2019-03-04 22:08:43
【问题描述】:

您好,我在将 pdfrw 用于 python 时遇到问题。我正在尝试用 pdfrw 填充 PDF,我可以填充一页。 obj.pages 只接受整数而不接受切片。目前它只会填满指定的一页。当我在 obj.page 中输入第二页时,它只填充第二页,依此类推。我需要填充四页。

import pdfrw

TEMPLATE_PATH = 'temppath.pdf'
OUTPUT_PATH = 'outpath.pdf'

ANNOT_KEY = '/Annots'
ANNOT_FIELD_KEY = '/T'
ANNOT_VAL_KEY = '/V'
ANNOT_RECT_KEY = '/Rect'
SUBTYPE_KEY = '/Subtype'
WIDGET_SUBTYPE_KEY = '/Widget'

def write_fillable_pdf(input_pdf_path, output_pdf_path, data_dict):
    template_pdf = pdfrw.PdfReader(input_pdf_path)
    annotations = template_pdf.pages[:3][ANNOT_KEY]
    for annotation in annotations:
        if annotation[SUBTYPE_KEY] == WIDGET_SUBTYPE_KEY:
            if annotation[ANNOT_FIELD_KEY]:
                key = annotation[ANNOT_FIELD_KEY][1:-1]
                if key in data_dict.keys():
                    annotation.update(
                        pdfrw.PdfDict(V='{}'.format(data_dict[key]))
                    )
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)

data_dict = {}

if __name__ == '__main__':
write_fillable_pdf(TEMPLATE_PATH, OUTPUT_PATH, data_dict)

当我使用切片时

annotations = template_pdf.pages[:3][ANNOT_KEY]

返回错误

TypeError: list indices must be integers or slices, not str

否则它只会在一页上运行

annotations = template_pdf.pages[0][ANNOT_KEY]

annotations = template_pdf.pages[1][ANNOT_KEY]

将运行指定的页面

我遇到了类似的问题: How to add text to the second page in pdf with Python, Reportlab and pdfrw?

从这篇文章开始 https://bostata.com/post/how_to_populate_fillable_pdfs_with_python/

【问题讨论】:

  • (1) 您希望pages[:3][ANNOT_KEY] 如何工作?这对我来说没有任何意义。 (2) 不要使用字符串作为 PdfDicts 的键。使用 PdfString 或,例如pages[0].Annots.V
  • @PatrickMaupin 我假设因为整数有效,并且适用于指示的页面,所以我要编辑的页面的切片可能有效。

标签: python pdfrw


【解决方案1】:

您看到的表达式 pages[:3][ANNOT_KEY] 的异常不会发生,因为在获取 slice pages[:3] 时出现问题——这工作正常。但是列表的一部分是一个列表,语法[ANNOT_KEY] 尝试使用ANNOT_KEY 来索引这个新列表,它是一个字符串。

但不要相信我的话;分割线:

    annotations = template_pdf.pages[:3][ANNOT_KEY]

分成两行:

    foobar = template_pdf.pages[:3]
    annotations = foobar[ANNOT_KEY]

看看哪里出错了。

无论如何,正如我在上面的评论中提到的,您也不应该使用字符串来索引 PdfDicts - 使用 PdfStrings,或者只是使用正确的属性访问它们。

我个人不使用注释,所以我不确定您要完成什么,但如果注释始终是一个列表(如果给出),您可以执行以下操作:

    annotations = []
    for page in template_pdf.pages[:3]:
        annotations.extend(page.Annots or [])

(上面or [] 表达式的目的是处理页面没有/Annots 的情况——因为pdfrw 将为不存在的dict 键返回None(以匹配PDF 字典的语义行为) 你想确保你没有尝试使用None 扩展列表。)

如果多个页面可以共享任何注释,您可能还想对列表进行重复数据删除。

免责声明:我是 pdfrw 的主要作者。

【讨论】:

  • 关键是从切片中创建一个列表,这就是错误的原因。感谢您使用 for 循环进行澄清,它立即清除了。我在分解如何循环时遇到了麻烦。
猜你喜欢
  • 2020-02-23
  • 1970-01-01
  • 2022-01-04
  • 2017-06-24
  • 2013-09-28
  • 1970-01-01
  • 2014-01-01
  • 2021-09-08
  • 2020-03-31
相关资源
最近更新 更多