pptx_render.py 3.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. #!/usr/bin/env python3
  2. """Render every slide of a .pptx to per-slide PNG images.
  3. Pipeline: LibreOffice (soffice --headless --convert-to pdf) turns the deck
  4. into a PDF, then poppler (pdftoppm, or pdftocairo as an alternate) splits
  5. the PDF into one PNG per slide.
  6. Output is JSON. When both tools are present:
  7. {"rendered": true, "files": ["render/slide-1.png", ...]}
  8. When either tool is missing the script still exits 0 and reports:
  9. {"rendered": false, "missing": ["soffice"], "guidance": "..."}
  10. so callers can degrade gracefully (fall back to pptx_read.py --outline).
  11. """
  12. import argparse
  13. import glob
  14. import json
  15. import os
  16. import shutil
  17. import subprocess
  18. import sys
  19. import tempfile
  20. def find_tools():
  21. """Return (soffice, splitter, missing) using shutil.which."""
  22. soffice = shutil.which("soffice")
  23. splitter = shutil.which("pdftoppm") or shutil.which("pdftocairo")
  24. missing = []
  25. if not soffice:
  26. missing.append("soffice")
  27. if not splitter:
  28. missing.append("pdftoppm (or pdftocairo)")
  29. return soffice, splitter, missing
  30. def render(pptx_path, out_dir, prefix, dpi):
  31. soffice, splitter, missing = find_tools()
  32. if missing:
  33. return {
  34. "rendered": False, "missing": missing,
  35. "guidance": "Install LibreOffice (soffice) and poppler-utils "
  36. "(pdftoppm/pdftocairo) to render slides. Without "
  37. "them, verify decks with pptx_read.py --outline "
  38. "instead.",
  39. }
  40. os.makedirs(out_dir, exist_ok=True)
  41. with tempfile.TemporaryDirectory() as tmp:
  42. proc = subprocess.run(
  43. [soffice, "--headless", "--convert-to", "pdf",
  44. "--outdir", tmp, pptx_path],
  45. capture_output=True, text=True, encoding="utf-8",
  46. errors="replace", timeout=300, check=False)
  47. pdfs = glob.glob(os.path.join(tmp, "*.pdf"))
  48. if proc.returncode != 0 or not pdfs:
  49. raise SystemExit(f"soffice PDF conversion failed: {proc.stderr}")
  50. pdf = pdfs[0]
  51. out_prefix = os.path.join(out_dir, prefix)
  52. proc = subprocess.run(
  53. [splitter, "-png", "-r", str(dpi), pdf, out_prefix],
  54. capture_output=True, text=True, encoding="utf-8",
  55. errors="replace", timeout=300, check=False)
  56. if proc.returncode != 0:
  57. raise SystemExit(f"{os.path.basename(splitter)} failed: "
  58. f"{proc.stderr}")
  59. files = sorted(glob.glob(out_prefix + "*.png"))
  60. return {"rendered": True, "files": files}
  61. def main(argv=None):
  62. if hasattr(sys.stdout, "reconfigure"):
  63. sys.stdout.reconfigure(encoding="utf-8", errors="replace")
  64. parser = argparse.ArgumentParser(
  65. description="Render each slide of a .pptx to a PNG via "
  66. "soffice + pdftoppm/pdftocairo.",
  67. epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  68. parser.add_argument("pptx", help="path to the .pptx file")
  69. parser.add_argument("--outdir", default="render",
  70. help="directory for PNGs (default: ./render)")
  71. parser.add_argument("--prefix", default="slide",
  72. help="PNG filename prefix (default: slide)")
  73. parser.add_argument("--dpi", type=int, default=100,
  74. help="render resolution (default: 100)")
  75. args = parser.parse_args(argv)
  76. result = render(args.pptx, args.outdir, args.prefix, args.dpi)
  77. print(json.dumps(result, indent=2))
  78. return 0
  79. if __name__ == "__main__":
  80. sys.exit(main())