python - 如何使用 pdfrw 库编辑可编辑的 pdf?

标签 python python-3.x pdf pdfrw

我一直在研究如何使用 Python 编辑 PDF,我发现了这篇文章:
How to Populate Fillable PDF's with Python

但是,一旦程序运行并打开 PDF,就会出现问题,只有当您单击显示数据的标签时才会填充文档,并且当您单击它时,它会再次消失。这是可以在网上找到的其他人编写的代码。

#! /usr/bin/python

import os
import pdfrw


INVOICE_TEMPLATE_PATH = 'invoice_template.pdf'
INVOICE_OUTPUT_PATH = 'invoice.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[0][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 = {
   'business_name_1': 'Bostata',
   'customer_name': 'company.io',
   'customer_email': 'joe@company.io',
   'invoice_number': '102394',
   'send_date': '2018-02-13',
   'due_date': '2018-03-13',
   'note_contents': 'Thank you for your business, Joe',
   'item_1': 'Data consulting services',
   'item_1_quantity': '10 hours',
   'item_1_price': '$200/hr',
   'item_1_amount': '$2000',
   'subtotal': '$2000',
   'tax': '0',
   'discounts': '0',
   'total': '$2000',
   'business_name_2': 'Bostata LLC',
   'business_email_address': 'hi@bostata.com',
   'business_phone_number': '(617) 930-4294'
}

if __name__ == '__main__':
    write_fillable_pdf(INVOICE_TEMPLATE_PATH, INVOICE_OUTPUT_PATH, data_dict)

最佳答案

我发现如果你添加 NeedAppearances 参数,你将解决你的问题:

template_pdf = pdfrw.PdfReader(TEMPLATE_PATH)
template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true'))) 

关于python - 如何使用 pdfrw 库编辑可编辑的 pdf?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54279950/

相关文章:

python - 从字典列表中创建非矛盾项的字典

python - UDP 消息太长

python-3.x - Python 异步 : Waiting for stdin input while doing other stuff

c# - 使用 javascript 或 C# 在 PDF 上绘图

python - 错误 : 'int' object is not subscriptable - Python

python - Keras多实例分类问题

python - 如何在 tkinter 中发出事件?

python - Django collectstatic 命令在 AWS Elastic Beanstalk Amazon Linux 2 Python 3 平台中失败

pdf - 可以在不安装嵌入字体的情况下编辑 PDF 吗?

iOS - 创建页面 pdf