Created
April 15, 2018 08:18
-
-
Save muesliflyer/091a2f590019efbcf96f635b3315e5c4 to your computer and use it in GitHub Desktop.
Generate XFDF file for filling a PDF Form (Python 3.x)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def generateXFDF(valueMap, path): | |
# Convert map of values into a tree of values | |
valueTree = {} | |
for fieldPath, value in valueMap.items(): | |
tr = valueTree | |
segs = fieldPath.split('.') | |
for seg in segs[:-1]: | |
if seg not in tr: tr[seg] = {} | |
tr = tr[seg] | |
tr[segs[-1]] = value | |
with open(path, 'w', encoding='utf-8') as f: | |
def writeDict(d, indent): | |
for field, val in d.items(): | |
f.write('\t'*indent + '<field name="' + field + '">\n') | |
if isinstance(val, dict): | |
writeDict(val, indent+1) | |
else: | |
f.write('\t'*(indent+1) + '<value>' + val + '</value>\n') | |
f.write('\t'*indent + '</field>\n') | |
f.write('<?xml version="1.0" encoding="UTF-8"?>\n') | |
f.write('<xfdf xmlns="http://ns.adobe.com/xfdf/" xml:space="preserve">\n') | |
f.write('<fields>\n') | |
writeDict(valueTree, 0) | |
f.write('</fields>\n') | |
f.write('</xfdf>\n') | |
if __name__ == '__main__': | |
# Here is how to use the function: | |
valueMap = { | |
'topmostSubform[0].Page1[0].NameAndAddress1[0].f1_1[0]': 'Joe Doe', | |
'topmostSubform[0].Page1[0].NameAndAddress1[0].f1_2[0]': '1234 Main Street', | |
'topmostSubform[0].Page1[0].NameAndAddress1[0].f1_3[0]': 'Bluetown, BL', | |
'topmostSubform[0].Page1[0].f1_19[0]': 'Goldman Sachs US Equity', | |
'topmostSubform[0].Page1[0].f1_20[0]': '2018-04-15', | |
'topmostSubform[0].Page1[0].f1_21[0]': '200' | |
} | |
generateXFDF(valueMap, 'test.xfdf') | |
# Fill the form, if you want to do it from Python: | |
import subprocess | |
subprocess.run(['pdftk', 'form.pdf', | |
'fill_form', 'test.xfdf', | |
'output', 'filledForm.pdf']).check_returncode() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment