【问题标题】:NeedAppearances=pdfrw.PdfObject('true') forces manual pdf save in Acrobat ReaderNeedAppearances=pdfrw.PdfObject('true') 强制在 Acrobat Reader 中手动保存 pdf
【发布时间】:2022-06-30 17:07:53
【问题描述】:

我们有一个 pdf 格式文件 example.pdf,它有 3 列:

名称_1, company_1,和 客户端_1

我们要填写的数据是希伯来语和英语。 我们的目标是拥有一个可以在浏览器和 Acrobat Reader 中打开 RTL 的文件。 当我们从以下代码手动保存导出的文件时,我们的目标就达到了,但是我们 希望不必手动保存,如果没有其他选择,请以编程方式保存。

import pdfrw


INVOICE_TEMPLATE_PATH = 'example.pdf'
INVOICE_OUTPUT_PATH = 'output.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)
    template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    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(AP=data_dict[key], V='{}'.format(data_dict[key]), Ff=1)
                    )
    pdfrw.PdfWriter().write(output_pdf_path, template_pdf)



data_dict = {
    'name_1': 'עידו',
    'company_1': 'IBM',
    'client_1': 'אסם'
}

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

我们认为NeedAppearances 与需要手动保存有关。 当导出的文件在 Acrobat Reader 中打开时,Acrobat Reader 会对文件应用特定的工作。出于这个原因,程序在退出时会询问我们是否要保存文件。 此操作对我们来说至关重要,但我们自动需要它。

这个操作是什么以及如何在我们的代码中以编程方式执行它?在导出之前或之后..

【问题讨论】:

    标签: python forms pdf pypdf2 hebrew


    【解决方案1】:

    使用pdfrw,您可以使用以下代码将 NeedAppearances 设置为 True:

    from pdfrw import PdfReader, PdfDict, PdfObject
    
    def set_need_appearances(pdf_reader: PdfReader):
       pdf_reader.Root.AcroForm.update(PdfDict(NeedAppearances=PdfObject("true")))
       return pdf_reader
    

    使用PyPDF2,您可以在PdfWriter 类上使用a built in method 设置需要的外观:

    pdf_writer = PdfWriter()
    pdf_writer.set_need_appearances_writer()
    

    【讨论】:

      猜你喜欢
      • 2011-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多