首页 > 解决方案 > Python:PDF:如何读取复选框等表单元素

问题描述

我在 python 中使用 Reportlab API 创建了一个表单,例如带有一些复选框。

# simple_checkboxes.py

from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfform
from reportlab.lib.colors import magenta, pink, blue, green

def create_simple_checkboxes():
    c = canvas.Canvas('simple_checkboxes2.pdf')

    #c.setFont("Courier", 20)
    c.drawCentredString(300, 700, 'Pets')
    #c.setFont("Courier", 14)
    form = c.acroForm

    c.drawString(10, 650, 'Dog:')
    form.checkbox(name='cb1', tooltip='Field cb1',
                  x=110, y=645)

    c.drawString(10, 600, 'Cat:')
    form.checkbox(name='cb2', tooltip='Field cb2',
                  x=110, y=595)

    c.drawString(10, 550, 'Pony:')
    form.checkbox(name='cb3', tooltip='Field cb3',
                  x=110, y=545)

    c.drawString(10, 500, 'Python:')
    form.checkbox(name='cb4', tooltip='Field cb4',
                  x=110, y=495)

    c.drawString(10, 450, 'Hamster:')
    form.checkbox(name='cb5', tooltip='Field cb5',
                  x=110, y=445, checked=True)                  

    c.save()

if __name__ == '__main__':
    create_simple_checkboxes()

现在,我以后如何使用 Python 读取 PDF 中的输入,由用户填写?我没有找到关于 Reportlab API 的示例或文档。

还是有更好或更简单的方法来实现这一目标?

标签: pythonpdfreportlab

解决方案


我没有报告实验室的解决方案...
但是您可以使用 PyPDF2 :)

from PyPDF2 import PdfFileReader
import json

def getcheckboxes(filename):
    with open(filename, "rb") as pdf:
        pdfr = PdfFileReader(pdf)

        pdf_fields = pdfr.getFields() #get field content of PDF File
        rp = str(pdf_fields).replace("'", '"') #replace single quote with doudble to load string to dict
        boxes = json.loads(rp) # string -> dict
        for box in boxes: #loop over all checkboxes
            print("checkbox {0} value is {1}".format(boxes[box]["/T"], boxes[box]["/V"])) #print out name = /T attribute and checked attribite = /V


getcheckboxes("test.pdf")

推荐阅读