acroform_apply.py 4.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153
  1. """Apply user-supplied values to AcroForm fields.
  2. Reads the fillable PDF, validates the values against the schema
  3. discovered by ``scripts.pdf_inspect.acroform_inspect``, and writes a new
  4. PDF with the field values populated.
  5. The value-config JSON is an array of records::
  6. [
  7. {
  8. "qname": "person.last_name",
  9. "page_no": 1,
  10. "set_to": "Simpson"
  11. },
  12. {
  13. "qname": "is_adult",
  14. "page_no": 1,
  15. "set_to": "/On" # for checkboxes use the on_value
  16. }
  17. ]
  18. Run from the skill root::
  19. python -m scripts.fill.acroform_apply input.pdf values.json output.pdf
  20. """
  21. from __future__ import annotations
  22. import json
  23. import sys
  24. from pypdf import PdfReader, PdfWriter
  25. from scripts.lib.acroform_io import (
  26. enumerate_acroform_fields,
  27. patch_pypdf_inheritance,
  28. )
  29. from scripts.lib.cli_utils import emit, fail, make_parser
  30. def value_violation(known_record: dict, supplied_value) -> str | None:
  31. field_type = known_record["type"]
  32. qname = known_record["qname"]
  33. if field_type == "checkbox":
  34. on = known_record["on_value"]
  35. off = known_record["off_value"]
  36. if supplied_value != on and supplied_value != off:
  37. return (
  38. f'ERROR: invalid value "{supplied_value}" for checkbox "{qname}". '
  39. f'Use on_value="{on}" or off_value="{off}".'
  40. )
  41. elif field_type == "radio_group":
  42. valid = [opt["set_to"] for opt in known_record["radio_choices"]]
  43. if supplied_value not in valid:
  44. return (
  45. f'ERROR: invalid value "{supplied_value}" for radio "{qname}". '
  46. f"Valid values: {valid}"
  47. )
  48. elif field_type == "choice":
  49. valid = [opt["set_to"] for opt in known_record["choice_options"]]
  50. if supplied_value not in valid:
  51. return (
  52. f'ERROR: invalid value "{supplied_value}" for choice "{qname}". '
  53. f"Valid values: {valid}"
  54. )
  55. return None
  56. def apply_acroform_values(
  57. src_pdf: str,
  58. value_cfg: str,
  59. dst_pdf: str,
  60. *,
  61. quiet: bool = False,
  62. ) -> int:
  63. with open(value_cfg) as handle:
  64. supplied = json.load(handle)
  65. values_by_page: dict[int, dict[str, object]] = {}
  66. for entry in supplied:
  67. if "set_to" not in entry:
  68. continue
  69. page = entry["page_no"]
  70. values_by_page.setdefault(page, {})[entry["qname"]] = entry["set_to"]
  71. pdf_doc = PdfReader(src_pdf)
  72. record_by_qname = {r["qname"]: r for r in enumerate_acroform_fields(pdf_doc)}
  73. failed = False
  74. for entry in supplied:
  75. known_record = record_by_qname.get(entry["qname"])
  76. if not known_record:
  77. failed = True
  78. print(f"ERROR: `{entry['qname']}` is not a known field id")
  79. continue
  80. if entry["page_no"] != known_record["page_no"]:
  81. failed = True
  82. print(
  83. f"ERROR: page_no mismatch for `{entry['qname']}` "
  84. f"(supplied {entry['page_no']}, expected {known_record['page_no']})"
  85. )
  86. continue
  87. if "set_to" in entry:
  88. problem = value_violation(known_record, entry["set_to"])
  89. if problem:
  90. failed = True
  91. print(problem)
  92. if failed:
  93. sys.exit(1)
  94. out_doc = PdfWriter(clone_from=pdf_doc)
  95. for page_no, values in values_by_page.items():
  96. out_doc.update_page_form_field_values(
  97. out_doc.pages[page_no - 1],
  98. values,
  99. auto_regenerate=False,
  100. )
  101. out_doc.set_need_appearances_writer(True)
  102. with open(dst_pdf, "wb") as handle:
  103. out_doc.write(handle)
  104. emit(f"Wrote filled PDF to {dst_pdf}", quiet=quiet)
  105. return len(supplied)
  106. def main(argv: list[str] | None = None) -> int:
  107. parser = make_parser(
  108. "acroform_apply",
  109. "Fill AcroForm fields using a JSON config and write a new PDF.",
  110. )
  111. parser.add_argument("src_pdf", help="Input fillable PDF.")
  112. parser.add_argument("value_cfg", help="JSON file describing the values to set.")
  113. parser.add_argument("dst_pdf", help="Output PDF path.")
  114. args = parser.parse_args(argv)
  115. patch_pypdf_inheritance()
  116. try:
  117. apply_acroform_values(
  118. args.src_pdf,
  119. args.value_cfg,
  120. args.dst_pdf,
  121. quiet=args.quiet,
  122. )
  123. except FileNotFoundError as exc:
  124. fail(f"File not found: {exc.filename}", code=2)
  125. return 0
  126. if __name__ == "__main__":
  127. sys.exit(main())