pdf_meta.py 4.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115
  1. #!/usr/bin/env python3
  2. """Document metadata and file attachments for PDFs (pypdf).
  3. Modes (one required):
  4. --set-meta set metadata keys given via --title/--author/...
  5. --clear-meta drop all document info metadata
  6. --attach FILE embed a file attachment
  7. --list-attachments list embedded attachment names
  8. --extract-attachments DIR write all attachments into DIR
  9. Metadata note: values are stored in the classic DocInfo dictionary
  10. (Title/Author/Subject/Keywords). XMP metadata, if present, is not
  11. rewritten and may disagree in sophisticated viewers.
  12. """
  13. from __future__ import annotations
  14. import argparse
  15. import json
  16. import os
  17. import sys
  18. from pathlib import Path
  19. def main() -> int:
  20. for stream in (sys.stdout, sys.stderr):
  21. try:
  22. stream.reconfigure(encoding="utf-8")
  23. except Exception:
  24. pass
  25. parser = argparse.ArgumentParser(description="Set/clear PDF metadata; manage attachments.")
  26. parser.add_argument("pdf", help="Input PDF path")
  27. mode = parser.add_mutually_exclusive_group(required=True)
  28. mode.add_argument("--set-meta", action="store_true", help="Set metadata fields")
  29. mode.add_argument("--clear-meta", action="store_true", help="Remove all DocInfo metadata")
  30. mode.add_argument("--attach", metavar="FILE", help="Embed FILE as an attachment")
  31. mode.add_argument("--list-attachments", action="store_true", help="List attachment names")
  32. mode.add_argument("--extract-attachments", metavar="DIR", help="Extract attachments into DIR")
  33. parser.add_argument("-o", "--output", help="Output PDF (required for write modes)")
  34. parser.add_argument("--title")
  35. parser.add_argument("--author")
  36. parser.add_argument("--subject")
  37. parser.add_argument("--keywords")
  38. parser.add_argument("--password", help="Password if the input is encrypted")
  39. args = parser.parse_args()
  40. try:
  41. from pypdf import PdfReader, PdfWriter
  42. except ImportError:
  43. print("Missing dependency: 'pypdf' is not importable here; rerun with the documents interpreter $PY from the pdf skill's Prerequisites setup block", file=sys.stderr)
  44. return 2
  45. reader = PdfReader(args.pdf)
  46. if reader.is_encrypted:
  47. if args.password is None or not reader.decrypt(args.password):
  48. print("Error: input is encrypted; pass --password", file=sys.stderr)
  49. return 3
  50. if args.list_attachments:
  51. names = list(reader.attachments.keys())
  52. json.dump({"attachment_count": len(names), "attachments": names}, sys.stdout,
  53. ensure_ascii=False, indent=2)
  54. print()
  55. return 0
  56. if args.extract_attachments:
  57. out_dir = Path(args.extract_attachments)
  58. out_dir.mkdir(parents=True, exist_ok=True)
  59. written = []
  60. for name, contents in reader.attachments.items():
  61. data = contents[0] if isinstance(contents, list) else contents
  62. safe = os.path.basename(name) or "attachment.bin"
  63. target = out_dir / safe
  64. with open(target, "wb") as fh:
  65. fh.write(bytes(data))
  66. written.append(str(target))
  67. json.dump({"extracted": written}, sys.stdout, ensure_ascii=False, indent=2)
  68. print()
  69. return 0
  70. if not args.output:
  71. print("Error: -o/--output is required for write modes", file=sys.stderr)
  72. return 4
  73. writer = PdfWriter()
  74. writer.append(reader)
  75. if args.set_meta:
  76. meta = {}
  77. for key, value in ((f"/{k.capitalize()}", getattr(args, k))
  78. for k in ("title", "author", "subject", "keywords")):
  79. if value is not None:
  80. meta[key] = value
  81. if not meta:
  82. print("Error: --set-meta needs at least one of --title/--author/--subject/--keywords",
  83. file=sys.stderr)
  84. return 4
  85. writer.add_metadata(meta)
  86. result = {"output": args.output, "set": {k.lstrip("/"): v for k, v in meta.items()}}
  87. elif args.clear_meta:
  88. writer.metadata = None
  89. result = {"output": args.output, "cleared": True}
  90. else: # --attach
  91. attach_path = Path(args.attach)
  92. with open(attach_path, "rb") as fh:
  93. writer.add_attachment(attach_path.name, fh.read())
  94. result = {"output": args.output, "attached": attach_path.name}
  95. with open(args.output, "wb") as fh:
  96. writer.write(fh)
  97. print(json.dumps(result, ensure_ascii=False))
  98. return 0
  99. if __name__ == "__main__":
  100. sys.exit(main())