pdfformfill/writetopdf.py
2018-05-07 16:26:36 +02:00

67 lines
2.4 KiB
Python

"""Functions for altering pdfs.
Uses pdftk.
"""
import subprocess as cmd
import fdfgen
from constants import NON_FORMFIELD, ConfigError
import stamps
def fillpdfform(fields, pdf, pdfout, fdf):
"""Fill a pdf form with data.
Attributes:
fields ([FormField]):
list of FormFields that already have values saved in ["Value"].
pdf (str): path to the pdf form that is to be filled
pdfout (str): path to the pdf form after it is filled with data
fdf (str): path to the temporarily created fdf file
"""
for field in fields:
try:
if field["Value"] not in field["FieldStateOption"]:
raise ConfigError("pdftk does not take values that are not " +
"allowed FieldStateOptions. Problem at" +
"'" + field.name + "' with value '" +
field["Value"] + "'.")
except KeyError:
pass # no value -> OK or no FieldStateOption -> OK
values = [(field["FieldName"], field["Value"]) for field in fields
if "Value" in field and NON_FORMFIELD not in field]
values = fdfgen.forge_fdf("", values, [], [], [])
with open(fdf, "wb") as fdf_file:
fdf_file.write(values)
pdfcreation = cmd.Popen(["pdftk", pdf, "fill_form", fdf, "output", pdfout],
stderr=cmd.PIPE)
# useless copyright warning ignored
exitcode = pdfcreation.wait(timeout=5)
if exitcode != 0: # todo: remove magical number
_, errortext = pdfcreation.communicate()
errortext = errortext.decode()
raise cmd.CalledProcessError(returncode=exitcode,
cmd=pdfcreation,
output="pdftk fillform reported an error."
+ " exit code: " + str(exitcode) +
". Error message\n" +
errortext)
# todo: suitable Error
# wait a maximum of 5 seconds for pdftk to finish
def fillpdf(fields, pdf, pdfout, fdf):
"""Fill a pdf with data.
Fills the form in the pdf and adds stamps.
Attributes: see fillpdfform()
Raises:
ConfigError: if fields are malformed (e.g. incomplete stamps)
"""
fillpdfform(fields, pdf, pdfout, fdf)
stamps.stampPdf(fields, pdfout, pdfout)