overlay_apply.py 3.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  1. """Lay text on top of a non-fillable PDF using FreeText annotations.
  2. Consumes the new-style ``fields.json`` produced by the operator (see
  3. docs/forms-guide.md, "Overlay schema") and writes a new PDF with each
  4. slot populated by a FreeText annotation. Coordinates can come from
  5. either the PDF (``pdf_w``/``pdf_h``) or a rasterised image
  6. (``img_w``/``img_h``); the script picks the right transform per page.
  7. Run from the skill root::
  8. python -m scripts.fill.overlay_apply input.pdf fields.json out.pdf
  9. """
  10. from __future__ import annotations
  11. import json
  12. import sys
  13. from pypdf import PdfReader, PdfWriter
  14. from pypdf.annotations import FreeText
  15. from scripts.lib.cli_utils import emit, fail, make_parser
  16. from scripts.lib.geometry import image_box_to_pdf_rect, pdf_box_to_pypdf_rect
  17. def apply_overlay_text(
  18. src_pdf: str,
  19. cfg_path: str,
  20. dst_pdf: str,
  21. *,
  22. quiet: bool = False,
  23. ) -> int:
  24. with open(cfg_path, "r") as handle:
  25. cfg = json.load(handle)
  26. pdf_doc = PdfReader(src_pdf)
  27. out_doc = PdfWriter()
  28. out_doc.append(pdf_doc)
  29. page_dim: dict[int, tuple[float, float]] = {}
  30. for idx, pg in enumerate(pdf_doc.pages):
  31. mb = pg.mediabox
  32. page_dim[idx + 1] = (float(mb.width), float(mb.height))
  33. written = 0
  34. for slot in cfg.get("slots", []):
  35. page_no = slot["page_no"]
  36. meta = next(p for p in cfg["pages"] if p["page_no"] == page_no)
  37. pdf_w, pdf_h = page_dim[page_no]
  38. if "pdf_w" in meta:
  39. pypdf_rect = pdf_box_to_pypdf_rect(slot["slot_box"], pdf_h)
  40. else:
  41. pypdf_rect = image_box_to_pdf_rect(
  42. slot["slot_box"],
  43. meta["img_w"],
  44. meta["img_h"],
  45. pdf_w,
  46. pdf_h,
  47. )
  48. glyph_spec = slot.get("value")
  49. if not glyph_spec or not glyph_spec.get("text"):
  50. continue
  51. text = glyph_spec["text"]
  52. face = glyph_spec.get("face", "Arial")
  53. size = f"{glyph_spec.get('size', 14)}pt"
  54. color = glyph_spec.get("color", "000000")
  55. annot = FreeText(
  56. text=text,
  57. rect=pypdf_rect,
  58. font=face,
  59. font_size=size,
  60. font_color=color,
  61. border_color=None,
  62. background_color=None,
  63. )
  64. out_doc.add_annotation(page_number=page_no - 1, annotation=annot)
  65. written += 1
  66. with open(dst_pdf, "wb") as handle:
  67. out_doc.write(handle)
  68. emit(f"Wrote overlaid PDF to {dst_pdf} ({written} annotations)", quiet=quiet)
  69. return written
  70. def main(argv: list[str] | None = None) -> int:
  71. parser = make_parser(
  72. "overlay_apply",
  73. "Stamp text annotations onto a PDF based on a fields.json config.",
  74. )
  75. parser.add_argument("src_pdf", help="Input PDF (any kind).")
  76. parser.add_argument("cfg_path", help="fields.json config (new schema).")
  77. parser.add_argument("dst_pdf", help="Output PDF path.")
  78. args = parser.parse_args(argv)
  79. try:
  80. apply_overlay_text(args.src_pdf, args.cfg_path, args.dst_pdf, quiet=args.quiet)
  81. except FileNotFoundError as exc:
  82. fail(f"File not found: {exc.filename}", code=2)
  83. except KeyError as exc:
  84. fail(f"fields.json missing required key: {exc}", code=2)
  85. return 0
  86. if __name__ == "__main__":
  87. sys.exit(main())