代码之家  ›  专栏  ›  技术社区  ›  Atinesh

如何使用Python填充PDF表单

  •  0
  • Atinesh  · 技术社区  · 6 年前

    我有一个 PDF form Adobe LiveCycle Designer ES 10.4 . 我需要用电脑来填 Python 这样我们就可以减少体力劳动。我在网上搜索了一下,读了一些文章,其中大部分都是我关注的 pdfrw PDF格式

    密码

    from pdfrw import PdfReader
    pdf = PdfReader('sample.pdf')
    print(pdf.keys())
    print(pdf.Info)
    print(pdf.Root.keys())
    print('PDF has {} pages'.format(len(pdf.pages)))
    

    输出

    ['/Root', '/Info', '/ID', '/Size']
    {'/CreationDate': "(D:20180822164509+05'30')", '/Creator': '(Adobe LiveCycle Designer ES 10.4)', '/ModDate': "(D:20180822165611+05'30')", '/Producer': '(Adobe XML Form Module Library)'}
    ['/AcroForm', '/MarkInfo', '/Metadata', '/Names', '/NeedsRendering', '/Pages', '/Perms', '/StructTreeRoot', '/Type']
    PDF has 1 pages
    

    pdfrw 从PDF表单访问可填充字段并使用 python 有可能吗。任何建议都会有帮助。

    2 回复  |  直到 6 年前
        1
  •  5
  •   Eddie    6 年前

    您可以在此处找到表单字段:

    pdf.Root.AcroForm.Fields
    

    还是在这里

    pdf.Root.Pages.Kids[page_index].Annots
    

    pdf.Root.AcroForm.Fields[field_index].T
    

    其他键包括值。五、

    我还没想出怎么解决这个问题。

        2
  •  1
  •   Asif Alam    5 年前

    template = PdfReader('template.pdf')
    page_c = 0
    while page_c < len(template.Root.Pages.Kids): #LOOP through pages
        annot_c = 0
        while annot_c < len(template.Root.Pages.Kids[page_c].Annots): #LOOP through fields
            template.Root.Pages.Kids[page_c].Annots[annot_c].update(PdfDict(V=str(annot_c)+'-'+str(page_c)))
            annot_c=annot_c+1
        page_c=page_c+1
    PdfWriter().write('output.pdf', template)
    
        3
  •  1
  •   Tyler Houssian    4 年前

    我编写了一个基于以下内容的库:“pdfrw”、“pdf2image”、“枕头”、“PyPDF2”,称为fillpdf( pip install fillpdf 和波普勒依赖 conda install -c conda-forge poppler )

    基本用法:

    from fillpdf import fillpdfs
    
    fillpdfs.get_form_fields("blank.pdf")
    
    # returns a dictionary of fields
    # Set the returned dictionary values a save to a variable
    # For radio boxes ('Off' = not filled, 'Yes' = filled)
    
    data_dict = {
    'Text2': 'Name',
    'Text4': 'LastName',
    'box': 'Yes',
    }
    
    fillpdfs.write_fillable_pdf('blank.pdf', 'new.pdf', data_dict)
    
    # If you want it flattened:
    fillpdfs.flatten_pdf('new.pdf', 'newflat.pdf')
    

    https://github.com/t-houssian/fillpdf

    如果某些字段未填充,可以使用fitz( pip install PyMuPDF pip install PyPDF2 )如以下所示,根据需要更改点:

    import fitz
    from PyPDF2 import PdfFileReader
    
    file_handle = fitz.open('blank.pdf')
    pdf = PdfFileReader(open('blank.pdf','rb'))
    box = pdf.getPage(0).mediaBox
    w = box.getWidth()
    h = box.getHeight()
    
    # For images
    image_rectangle = fitz.Rect((w/2)-200,h-255,(w/2)-100,h-118)
    pages = pdf.getNumPages() - 1
    last_page = file_handle[pages]
    last_page._wrapContents()
    last_page.insertImage(image_rectangle, filename=f'image.png')
    
    # For text
    last_page.insertText(fitz.Point((w/2)-247 , h-478), 'John Smith', fontsize=14, fontname="times-bold")
    file_handle.save(f'newpdf.pdf')
    
        4
  •  0
  •   paolo    6 年前

    PDFix SDK

    def SetFormFieldValue(email, key, open_path, save_path):
        pdfix  = GetPdfix()
        if pdfix is None:
            raise Exception('Pdfix Initialization fail')
        if not pdfix.Authorize(pdfix_email, pdfix_license):
            raise Exception('Authorization fail : ' + pdfix.GetError())
        doc = pdfix.OpenDoc(open_path, "")
        if doc is None:
            raise Exception('Unable to open pdf : ' + pdfix.GetError())
        field = doc.GetFormFieldByName("Text1")
        if field is not None:
            value = field.GetValue()
            value = "New Value"
            field.SetValue(value)
        if not doc.Save(save_path, kSaveFull):
            raise Exception(pdfix.GetError())
        doc.Close()
        pdfix.Destroy()
    
        5
  •  0
  •   Asensio    5 年前

    这里提供了完整的解决方案: How to edit editable pdf using the pdfrw library?

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