pdf_split.py 3.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. #!/usr/bin/env python3
  2. """Extract page ranges from a PDF, optionally rotating and/or compressing pages."""
  3. from __future__ import annotations
  4. import argparse
  5. import json
  6. import sys
  7. def parse_pages(spec: str, page_count: int) -> list[int]:
  8. """Parse a 1-based page spec like '1-3,5,9-' into 0-based indices."""
  9. indices: list[int] = []
  10. for part in spec.split(","):
  11. part = part.strip()
  12. if not part:
  13. continue
  14. if "-" in part:
  15. start_s, _, end_s = part.partition("-")
  16. start = int(start_s) if start_s else 1
  17. end = int(end_s) if end_s else page_count
  18. else:
  19. start = end = int(part)
  20. if start < 1 or end > page_count or start > end:
  21. raise ValueError(f"Page range {part!r} out of bounds (1-{page_count})")
  22. indices.extend(range(start - 1, end))
  23. return indices
  24. def main() -> int:
  25. for stream in (sys.stdout, sys.stderr):
  26. try:
  27. stream.reconfigure(encoding="utf-8")
  28. except Exception:
  29. pass
  30. parser = argparse.ArgumentParser(
  31. description="Split/extract pages from a PDF (pypdf). Pages are 1-based: '1-3,5,9-'.")
  32. parser.add_argument("pdf", help="Input PDF path")
  33. parser.add_argument("--pages", required=True, help="1-based page spec, e.g. '1-3,5,9-'")
  34. parser.add_argument("-o", "--output", required=True, help="Output PDF path")
  35. parser.add_argument("--rotate", type=int, default=0,
  36. help="Rotate extracted pages clockwise (multiple of 90)")
  37. parser.add_argument("--compress", action="store_true",
  38. help="Deflate content streams (modest savings; does not recompress images)")
  39. parser.add_argument("--password", help="Password if the input is encrypted")
  40. args = parser.parse_args()
  41. if args.rotate % 90 != 0:
  42. print("Error: --rotate must be a multiple of 90", file=sys.stderr)
  43. return 2
  44. try:
  45. from pypdf import PdfReader, PdfWriter
  46. except ImportError:
  47. 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)
  48. return 2
  49. reader = PdfReader(args.pdf)
  50. if reader.is_encrypted:
  51. if args.password is None or not reader.decrypt(args.password):
  52. print("Error: input is encrypted; pass --password", file=sys.stderr)
  53. return 3
  54. try:
  55. indices = parse_pages(args.pages, len(reader.pages))
  56. except ValueError as exc:
  57. print(f"Error: {exc}", file=sys.stderr)
  58. return 2
  59. writer = PdfWriter()
  60. for idx in indices:
  61. page = reader.pages[idx]
  62. if args.rotate:
  63. page.rotate(args.rotate)
  64. writer.add_page(page)
  65. if args.compress:
  66. for page in writer.pages:
  67. page.compress_content_streams()
  68. with open(args.output, "wb") as fh:
  69. writer.write(fh)
  70. print(json.dumps({"output": args.output, "page_count": len(indices), "rotated": args.rotate}))
  71. return 0
  72. if __name__ == "__main__":
  73. sys.exit(main())