我正在嘗試使用Python來處理一些使用Adobe Acrobat Reader填寫並簽名的PDF表單。如何從Python中填寫的表單中提取PDF字段?
我已經試過:
- 的pdfminer演示:它沒有任何傾倒在填寫數據。
- pyPdf:當我嘗試使用PdfFileReader(f)加載文件時,它最大化了一個核心2分鐘,我放棄並殺死了它。
- Jython和PDFBox:得到了很好的工作,但啓動時間過長,如果這是我唯一的選擇,我將直接在Java中編寫外部實用程序。
我可以繼續尋找圖書館並嘗試它們,但我希望有人已經有一個有效的解決方案。
更新:根據史蒂芬的答案,我看着pdfminer和它很好的伎倆。
from argparse import ArgumentParser
import pickle
import pprint
from pdfminer.pdfparser import PDFParser, PDFDocument
from pdfminer.pdftypes import resolve1, PDFObjRef
def load_form(filename):
"""Load pdf form contents into a nested list of name/value tuples"""
with open(filename, 'rb') as file:
parser = PDFParser(file)
doc = PDFDocument()
parser.set_document(doc)
doc.set_parser(parser)
doc.initialize()
return [load_fields(resolve1(f)) for f in
resolve1(doc.catalog['AcroForm'])['Fields']]
def load_fields(field):
"""Recursively load form fields"""
form = field.get('Kids', None)
if form:
return [load_fields(resolve1(f)) for f in form]
else:
# Some field types, like signatures, need extra resolving
return (field.get('T').decode('utf-16'), resolve1(field.get('V')))
def parse_cli():
"""Load command line arguments"""
parser = ArgumentParser(description='Dump the form contents of a PDF.')
parser.add_argument('file', metavar='pdf_form',
help='PDF Form to dump the contents of')
parser.add_argument('-o', '--out', help='Write output to file',
default=None, metavar='FILE')
parser.add_argument('-p', '--pickle', action='store_true', default=False,
help='Format output for python consumption')
return parser.parse_args()
def main():
args = parse_cli()
form = load_form(args.file)
if args.out:
with open(args.out, 'w') as outfile:
if args.pickle:
pickle.dump(form, outfile)
else:
pp = pprint.PrettyPrinter(indent=2)
file.write(pp.pformat(form))
else:
if args.pickle:
print pickle.dumps(form)
else:
pp = pprint.PrettyPrinter(indent=2)
pp.pprint(form)
if __name__ == '__main__':
main()
作爲一個說明,我也嘗試使用pdftk作爲外部工具,它沒有超過所有者密碼。 – Olson 2010-10-21 03:09:47