pptx_edit.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436
  1. #!/usr/bin/env python3
  2. """Edit a .pptx in place (or save to --output).
  3. Operations (repeatable / combinable):
  4. --replace-text OLD NEW Replace text everywhere (slides, tables, notes).
  5. Adjacent runs with identical formatting are
  6. merged first, so matches PowerPoint split across
  7. identically-formatted runs keep their formatting.
  8. Only a match spanning genuinely different
  9. formats falls back to a paragraph rewrite with
  10. the first run's font (documented caveat).
  11. --chart-data SPEC.json Update a chart. Full replace spec:
  12. {"slide": 0, "chart": 0,
  13. "categories": ["Q1", "Q2"],
  14. "series": {"North": [1, 2], "South": [3, 4]}}
  15. Or surgical ops (existing data is read, modified,
  16. and written back via replace_data):
  17. {"slide": 0, "chart": 0, "ops": [
  18. {"op": "update_series", "name": "North",
  19. "values": [5, 6]},
  20. {"op": "add_series", "name": "East",
  21. "values": [1, 2]},
  22. {"op": "remove_series", "name": "South"},
  23. {"op": "rename_category", "from": "Q1",
  24. "to": "Q1 FY26"},
  25. {"op": "set_title", "title": "New title"}]}
  26. --swap-image SLIDE SHAPE_NAME NEW_IMAGE
  27. Replace a picture's bits, keeping position/size.
  28. --remove-slide N Delete slide at index N (0-based).
  29. --move-slide FROM TO Reorder: move slide FROM to position TO.
  30. --duplicate-slide N Append an independent deep copy of slide N
  31. (text, images, tables, shapes, notes). Refuses
  32. slides containing charts (a chart embeds an XLSX
  33. workbook part that cannot be cloned reliably).
  34. --set-background N HEX Solid background color for slide N.
  35. --hyperlink N TEXT URL Make runs containing TEXT on slide N links.
  36. --enable-slide-number N Copy the layout's slide-number placeholder in.
  37. --set-footer N TEXT Enable the layout's footer placeholder with TEXT.
  38. --set-notes N TEXT Replace slide N's speaker notes.
  39. --append-notes N TEXT Append a paragraph to slide N's speaker notes.
  40. """
  41. import argparse
  42. import copy
  43. import json
  44. import sys
  45. from lxml import etree
  46. from pptx import Presentation
  47. from pptx.chart.data import CategoryChartData
  48. from pptx.dml.color import RGBColor
  49. from pptx.enum.shapes import MSO_SHAPE_TYPE
  50. from pptx.oxml.ns import qn
  51. R_EMBED = "{http://schemas.openxmlformats.org/officeDocument/2006/relationships}"
  52. def _run_format_key(r):
  53. """Canonical string for a run's <a:rPr>; None when absent."""
  54. rPr = r.find(qn("a:rPr"))
  55. if rPr is None:
  56. return None
  57. return etree.tostring(rPr)
  58. def normalize_runs(para):
  59. """Merge adjacent runs whose formatting is byte-identical.
  60. PowerPoint splits paragraph text into runs at spell-check and edit
  61. boundaries even when formatting never changes; merging them back makes
  62. cross-run text replacement lossless for the common case.
  63. """
  64. runs = list(para.runs)
  65. i = 0
  66. while i + 1 < len(runs):
  67. a, b = runs[i], runs[i + 1]
  68. if (_run_format_key(a._r) == _run_format_key(b._r)
  69. and a._r.getnext() is b._r):
  70. a.text = a.text + b.text
  71. b._r.getparent().remove(b._r)
  72. runs.pop(i + 1)
  73. else:
  74. i += 1
  75. def replace_in_text_frame(text_frame, old, new):
  76. count = 0
  77. for para in text_frame.paragraphs:
  78. joined = "".join(run.text for run in para.runs)
  79. if old not in joined:
  80. continue
  81. if not any(old in run.text for run in para.runs):
  82. # Match spans runs: merge identically-formatted neighbours
  83. # first, which resolves pure spell-check splits losslessly.
  84. normalize_runs(para)
  85. if any(old in run.text for run in para.runs):
  86. # Run-level replace: preserves each run's formatting exactly.
  87. for run in para.runs:
  88. if old in run.text:
  89. count += run.text.count(old)
  90. run.text = run.text.replace(old, new)
  91. else:
  92. # Match spans genuinely differently-formatted runs -> rewrite
  93. # paragraph, keeping only the first run's formatting (caveat).
  94. joined = "".join(run.text for run in para.runs)
  95. count += joined.count(old)
  96. first = para.runs[0]
  97. first.text = joined.replace(old, new)
  98. for run in para.runs[1:]:
  99. run._r.getparent().remove(run._r)
  100. return count
  101. def iter_text_frames(slide):
  102. for shape in slide.shapes:
  103. if shape.has_text_frame:
  104. yield shape.text_frame
  105. if shape.has_table:
  106. for row in shape.table.rows:
  107. for cell in row.cells:
  108. yield cell.text_frame
  109. if slide.has_notes_slide:
  110. yield slide.notes_slide.notes_text_frame
  111. def replace_text(prs, old, new):
  112. total = 0
  113. for slide in prs.slides:
  114. for tf in iter_text_frames(slide):
  115. total += replace_in_text_frame(tf, old, new)
  116. return total
  117. def _read_chart_data(chart):
  118. """Current categories and ordered (name, values) pairs of a chart."""
  119. categories = [str(c) for c in chart.plots[0].categories]
  120. series = []
  121. for plot in chart.plots:
  122. for s in plot.series:
  123. try:
  124. name = s.name
  125. except (AttributeError, KeyError):
  126. name = ""
  127. series.append([name, list(s.values)])
  128. return categories, series
  129. def update_chart(prs, spec_path):
  130. """Full replace ("categories"+"series") or surgical "ops".
  131. python-pptx can only swap a chart's entire dataset (replace_data), so
  132. surgical ops are implemented as read-existing -> modify -> replace.
  133. """
  134. with open(spec_path, encoding="utf-8") as fh:
  135. spec = json.load(fh)
  136. slide = prs.slides[spec.get("slide", 0)]
  137. charts = [s.chart for s in slide.shapes if s.has_chart]
  138. if not charts:
  139. raise SystemExit(f"no chart on slide {spec.get('slide', 0)}")
  140. chart = charts[spec.get("chart", 0)]
  141. if "ops" in spec:
  142. categories, series = _read_chart_data(chart)
  143. dirty = False
  144. for op in spec["ops"]:
  145. kind = op["op"]
  146. if kind == "update_series":
  147. match = [s for s in series if s[0] == op["name"]]
  148. if not match:
  149. raise SystemExit(f"no series named {op['name']!r}")
  150. match[0][1] = op["values"]
  151. dirty = True
  152. elif kind == "add_series":
  153. series.append([op["name"], op["values"]])
  154. dirty = True
  155. elif kind == "remove_series":
  156. before = len(series)
  157. series = [s for s in series if s[0] != op["name"]]
  158. if len(series) == before:
  159. raise SystemExit(f"no series named {op['name']!r}")
  160. dirty = True
  161. elif kind == "rename_category":
  162. if "index" in op:
  163. idx = int(op["index"])
  164. else:
  165. if op["from"] not in categories:
  166. raise SystemExit(
  167. f"no category named {op['from']!r}")
  168. idx = categories.index(op["from"])
  169. categories[idx] = op["to"]
  170. dirty = True
  171. elif kind == "set_title":
  172. chart.has_title = True
  173. chart.chart_title.text_frame.text = op["title"]
  174. else:
  175. raise SystemExit(f"unknown chart op {kind!r}")
  176. if dirty:
  177. data = CategoryChartData()
  178. data.categories = categories
  179. for name, values in series:
  180. data.add_series(name, values)
  181. chart.replace_data(data)
  182. return
  183. data = CategoryChartData()
  184. data.categories = spec["categories"]
  185. for name, values in spec["series"].items():
  186. data.add_series(name, values)
  187. chart.replace_data(data)
  188. def swap_image(prs, slide_idx, shape_name, new_path):
  189. slide = prs.slides[int(slide_idx)]
  190. for shape in slide.shapes:
  191. if (shape.shape_type == MSO_SHAPE_TYPE.PICTURE
  192. and shape.name == shape_name):
  193. _image_part, rid = slide.part.get_or_add_image_part(new_path)
  194. blip = shape._element.blipFill.blip
  195. blip.set(R_EMBED + "embed", rid)
  196. return True
  197. raise SystemExit(f"no picture named {shape_name!r} on slide {slide_idx}")
  198. def remove_slide(prs, index):
  199. sldIdLst = prs.slides._sldIdLst
  200. slide_id = list(sldIdLst)[int(index)]
  201. rid = slide_id.get(R_EMBED + "id")
  202. prs.part.drop_rel(rid)
  203. sldIdLst.remove(slide_id)
  204. def move_slide(prs, src, dst):
  205. """Reorder by moving the <p:sldId> element inside <p:sldIdLst>."""
  206. sldIdLst = prs.slides._sldIdLst
  207. ids = list(sldIdLst)
  208. element = ids[int(src)]
  209. sldIdLst.remove(element)
  210. sldIdLst.insert(int(dst), element)
  211. def duplicate_slide(prs, index):
  212. """Append an independent deep copy of slide `index`.
  213. Copies the shape tree XML and re-creates image/media relationships on
  214. the new slide part, remapping rIds. Charts are refused: each chart
  215. relationship embeds a separate XLSX workbook part, and cloning that
  216. graph reliably is not supported — better to refuse than corrupt.
  217. """
  218. source = prs.slides[int(index)]
  219. if any(sh.has_chart for sh in source.shapes):
  220. raise SystemExit(
  221. f"slide {index} contains a chart; duplication of chart slides "
  222. "is not supported (chart XML embeds a workbook part that "
  223. "cannot be cloned safely). Rebuild the chart on a new slide "
  224. "with pptx_create.py / pptx_from_template.py instead.")
  225. dest = prs.slides.add_slide(source.slide_layout)
  226. # drop the placeholders add_slide seeded from the layout
  227. for shape in list(dest.shapes):
  228. shape._element.getparent().remove(shape._element)
  229. for shape in source.shapes:
  230. dest.shapes._spTree.append(copy.deepcopy(shape._element))
  231. # re-create the source slide's part relationships on the copy
  232. rid_map = {}
  233. for rel in list(source.part.rels.values()):
  234. if rel.reltype.endswith(("/slideLayout", "/notesSlide")):
  235. continue
  236. if rel.is_external:
  237. new_rid = dest.part.rels.get_or_add_ext_rel(
  238. rel.reltype, rel.target_ref)
  239. else:
  240. new_rid = dest.part.relate_to(rel.target_part, rel.reltype)
  241. rid_map[rel.rId] = new_rid
  242. for el in dest.shapes._spTree.iter():
  243. for attr, val in el.attrib.items():
  244. if attr.startswith(R_EMBED) and val in rid_map:
  245. el.set(attr, rid_map[val])
  246. if source.has_notes_slide:
  247. dest.notes_slide.notes_text_frame.text = (
  248. source.notes_slide.notes_text_frame.text)
  249. return len(prs.slides._sldIdLst) - 1
  250. def set_background(slide, hex_color):
  251. fill = slide.background.fill
  252. fill.solid()
  253. fill.fore_color.rgb = RGBColor.from_string(hex_color)
  254. def add_hyperlink(prs, slide_idx, text, url):
  255. """Turn every run containing `text` on the slide into a hyperlink.
  256. The link applies to the whole run (python-pptx links whole runs).
  257. """
  258. slide = prs.slides[int(slide_idx)]
  259. hits = 0
  260. for shape in slide.shapes:
  261. if not shape.has_text_frame:
  262. continue
  263. for para in shape.text_frame.paragraphs:
  264. for run in para.runs:
  265. if text in run.text:
  266. run.hyperlink.address = url
  267. hits += 1
  268. if not hits:
  269. raise SystemExit(f"no run containing {text!r} on slide {slide_idx}")
  270. return hits
  271. def _copy_layout_placeholder(slide, ph_idx):
  272. """Copy the layout placeholder with idx `ph_idx` onto the slide.
  273. Slide-number (idx 12) and footer (idx 11) placeholders exist on the
  274. layout but are not inherited by a slide until the slide carries its
  275. own copy — this enables them. Returns the new shape, or None when the
  276. layout does not provide that placeholder.
  277. """
  278. for ph in slide.slide_layout.placeholders:
  279. if ph.placeholder_format.idx == ph_idx:
  280. el = copy.deepcopy(ph._element)
  281. slide.shapes._spTree.append(el)
  282. for shape in slide.placeholders:
  283. if shape.placeholder_format.idx == ph_idx:
  284. return shape
  285. return None
  286. return None
  287. def enable_slide_number(slide):
  288. if any(ph.placeholder_format.idx == 12 for ph in slide.placeholders):
  289. return True
  290. return _copy_layout_placeholder(slide, 12) is not None
  291. def set_footer(slide, text):
  292. shape = next((ph for ph in slide.placeholders
  293. if ph.placeholder_format.idx == 11), None)
  294. if shape is None:
  295. shape = _copy_layout_placeholder(slide, 11)
  296. if shape is None:
  297. raise SystemExit("layout provides no footer placeholder; add a "
  298. "textbox instead")
  299. shape.text_frame.text = text
  300. return True
  301. def set_notes(slide, text, append=False):
  302. tf = slide.notes_slide.notes_text_frame
  303. if append and tf.text:
  304. para = tf.add_paragraph()
  305. para.text = text
  306. else:
  307. tf.text = text
  308. def main(argv=None):
  309. if hasattr(sys.stdout, "reconfigure"):
  310. sys.stdout.reconfigure(encoding="utf-8", errors="replace")
  311. parser = argparse.ArgumentParser(
  312. description="Edit a .pptx: replace text, update chart data, swap "
  313. "images, duplicate/remove/reorder slides, backgrounds, "
  314. "hyperlinks, footers, slide numbers, speaker notes.",
  315. epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  316. parser.add_argument("pptx", help="path to the .pptx file")
  317. parser.add_argument("--output", help="save to this path instead of "
  318. "overwriting the input")
  319. parser.add_argument("--replace-text", nargs=2, action="append",
  320. metavar=("OLD", "NEW"), default=[])
  321. parser.add_argument("--chart-data", metavar="SPEC_JSON")
  322. parser.add_argument("--swap-image", nargs=3,
  323. metavar=("SLIDE", "SHAPE_NAME", "IMAGE"))
  324. parser.add_argument("--remove-slide", type=int, metavar="N")
  325. parser.add_argument("--move-slide", nargs=2, type=int,
  326. metavar=("FROM", "TO"))
  327. parser.add_argument("--duplicate-slide", type=int, metavar="N")
  328. parser.add_argument("--set-background", nargs=2,
  329. metavar=("SLIDE", "HEX"))
  330. parser.add_argument("--hyperlink", nargs=3,
  331. metavar=("SLIDE", "TEXT", "URL"))
  332. parser.add_argument("--enable-slide-number", type=int, metavar="N")
  333. parser.add_argument("--set-footer", nargs=2, metavar=("SLIDE", "TEXT"))
  334. parser.add_argument("--set-notes", nargs=2, metavar=("SLIDE", "TEXT"))
  335. parser.add_argument("--append-notes", nargs=2, metavar=("SLIDE", "TEXT"))
  336. args = parser.parse_args(argv)
  337. prs = Presentation(args.pptx)
  338. report = {"ok": True, "replacements": 0}
  339. for old, new in args.replace_text:
  340. report["replacements"] += replace_text(prs, old, new)
  341. if args.chart_data:
  342. update_chart(prs, args.chart_data)
  343. report["chart_updated"] = True
  344. if args.swap_image:
  345. swap_image(prs, *args.swap_image)
  346. report["image_swapped"] = True
  347. if args.duplicate_slide is not None:
  348. report["duplicated_to"] = duplicate_slide(prs, args.duplicate_slide)
  349. if args.set_background:
  350. set_background(prs.slides[int(args.set_background[0])],
  351. args.set_background[1])
  352. report["background_set"] = True
  353. if args.hyperlink:
  354. report["hyperlinked_runs"] = add_hyperlink(prs, *args.hyperlink)
  355. if args.enable_slide_number is not None:
  356. report["slide_number_enabled"] = enable_slide_number(
  357. prs.slides[args.enable_slide_number])
  358. if args.set_footer:
  359. set_footer(prs.slides[int(args.set_footer[0])], args.set_footer[1])
  360. report["footer_set"] = True
  361. if args.set_notes:
  362. set_notes(prs.slides[int(args.set_notes[0])], args.set_notes[1])
  363. report["notes_set"] = True
  364. if args.append_notes:
  365. set_notes(prs.slides[int(args.append_notes[0])],
  366. args.append_notes[1], append=True)
  367. report["notes_appended"] = True
  368. if args.remove_slide is not None:
  369. remove_slide(prs, args.remove_slide)
  370. report["slide_removed"] = args.remove_slide
  371. if args.move_slide:
  372. move_slide(prs, *args.move_slide)
  373. report["slide_moved"] = args.move_slide
  374. out = args.output or args.pptx
  375. prs.save(out)
  376. report["output"] = out
  377. print(json.dumps(report))
  378. return 0
  379. if __name__ == "__main__":
  380. sys.exit(main())