python-3.x 如何使用pdfrw库编辑可编辑pdf?

pcww981p  于 2023-01-27  发布在  Python
关注(0)|答案(5)|浏览(147)

我一直在研究如何使用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)
jobtbby3

jobtbby31#

我发现,如果添加NeedAppearances参数,就可以解决问题:

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

oymdgrw72#

更新写功能,使AP和V键为我修复了预览中的问题

pdfrw.PdfDict(AP=data_dict[key], V=data_dict[key])
mw3dktmi

mw3dktmi3#

错误原因是该字段没有关联出现流,但您创建方式错误,您刚刚将和流分配给AP字典,您需要做的是将一个间接Xobject分配给/AP字典中的/N;你需要从头创建Xobject,代码应该如下所示:

from pdfrw import PdfWriter, PdfReader, IndirectPdfDict, PdfName, PdfDict

INVOICE_TEMPLATE_PATH = 'untitled.pdf'
INVOICE_OUTPUT_PATH = 'untitled-output.pdf'

field1value = 'im field_1 value'

template_pdf = PdfReader(INVOICE_TEMPLATE_PATH)
template_pdf.Root.AcroForm.Fields[0].V = field1value

#this depends on page orientation
rct = template_pdf.Root.AcroForm.Fields[0].Rect
hight = round(float(rct[3]) - float(rct[1]),2)
width =(round(float(rct[2]) - float(rct[0]),2)

#create Xobject
xobj = IndirectPdfDict(
            BBox = [0, 0, width, hight],
            FormType = 1,
            Resources = PdfDict(ProcSet = [PdfName.PDF, PdfName.Text]),
            Subtype = PdfName.Form,
            Type = PdfName.XObject
            )

#assign a stream to it
xobj.stream = '''/Tx BMC
BT
 /Helvetica 8.0 Tf
 1.0 5.0 Td
 0 g
 (''' + field1value + ''') Tj
ET EMC'''

#put all together
template_pdf.Root.AcroForm.Fields[0].AP = PdfDict(N = xobj)

#output to new file
PdfWriter().write(INVOICE_OUTPUT_PATH, template_pdf)

注意:仅供参考:/Type、/FormType、/Resorce是可选的(强烈建议使用/Resources)。

gfttwv5a

gfttwv5a4#

为了扩展塞尔吉奥上面的回答,下面一行:

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

在OP的示例代码中,应将放在此行的之后:

template_pdf = pdfrw.PdfReader(input_pdf_path)
jucafojl

jucafojl5#

如果有人在表单上有下拉字段,您可以使用下面的代码填充数据。(可能会保存别人的麻烦,我经历了)

if key in data_dict.keys():
    #see if its a dropdown
    if('/I' in annotation.keys()):
        #field is a dropdown
        #Check if value is in preset list of dropdown, and at what value
        if data_dict[key] in annotation['/Opt']:
            #Value is in dropdown list,select value from list
            annotation.update(pdfrw.PdfDict(I='[{}]'.format(annotation['/Opt'].index(data_dict[key]))))
        else:
            #Value is not in dropdown list, add as 'free input'
            annotation.update(pdfrw.PdfDict(I='{}'.format(None)))
            annotation.update(pdfrw.PdfDict(V='{}'.format(data_dict[key])))
    else:
        #update the textfieldvalue
        annotation.update(pdfrw.PdfDict(V='{}'.format(data_dict[key])))

也不是说OP代码只对第一页起作用,因为

template_pdf.pages[0]

相关问题