Python:PDF:如何从复选框等表单元素中读取

问题描述 投票:0回答:1

我在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上找到任何示例或文档。

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

python pdf reportlab
1个回答
0
投票

我没有reportlab的解决方案...... 但你可以使用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")
© www.soinside.com 2019 - 2024. All rights reserved.