【问题标题】:How to check a checkbox and a radio button in a PDF with Python?如何使用 Python 检查 PDF 中的复选框和单选按钮?
【发布时间】:2021-04-30 07:07:07
【问题描述】:

我需要使用 Python 来填充完整的 PDF 文件,但我已经搜索了 8 个小时,我只能找到如何仅在 PDF 文件中填充文本字段。我需要填写复选复选框并使用单选按钮,您可以在其中选中一个但不能选中另一个,例如是或否单选按钮或性别单选按钮。

这是我一直在使用 pdfrw python 模块的代码...

import pdfrw

template_pdf = pdfrw.PdfReader("template.pdf")

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

def fillPDF(data_dict):
    for page in template_pdf.pages:
        annotations = page[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():
                        if type(data_dict[key]) == bool:
                            if data_dict[key] == True:
                                annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('Yes')))
                        else:
                            annotation.update(pdfrw.PdfDict(V='{}'.format(data_dict[key])))
                        annotation.update(pdfrw.PdfDict(AP=''))
                    else:
                        print(key)

    template_pdf.Root.AcroForm.update(pdfrw.PdfDict(NeedAppearances=pdfrw.PdfObject('true')))
    pdfrw.PdfWriter().write("output.pdf", template_pdf)

此代码应该填充文本字段和复选框,但它不适用于复选框,甚至无法检测单选按钮。

如果你有办法用 python 检查单选按钮和复选框,请告诉我。谢谢。

【问题讨论】:

    标签: python pdf pdfrw


    【解决方案1】:

    我认为这很愚蠢。我的代码与您的代码非常相似,并且可以正常工作。

    if key in data_dict.keys():
        if type(data_dict[key]) is str:
            annotation.update(pdfrw.PdfDict(AP=data_dict[key], V=data_dict[key]))
        elif type(data_dict[key]) is bool:
            if data_dict[key] is True:
                annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('Yes')))
            elif data_dict[key] is False:
                annotation.update(pdfrw.PdfDict(AS=pdfrw.PdfName('')))
        else:
            pass
        annotation.update(pdfrw.PdfDict(Ff=1))  # Field non-editable.
    

    【讨论】:

    • 这应该是评论?即使是答案,它也不会提供解释。 “非常相似”不是您应该回答的问题。您应该回答正确的代码以及为什么会这样。
    猜你喜欢
    • 2019-05-29
    • 2019-02-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多