pptx_create.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228
  1. #!/usr/bin/env python3
  2. """Create a .pptx presentation from a JSON deck spec.
  3. Spec format (all positions/sizes in inches, colors as RRGGBB hex):
  4. {
  5. "slide_size": "16:9", // or "4:3" (default "16:9")
  6. "slides": [
  7. {"layout": "title", "title": "My Deck", "subtitle": "Q3 review"},
  8. {"layout": "title_content", "title": "Agenda",
  9. "bullets": ["Top item",
  10. {"text": "Sub item", "level": 1, "bold": true,
  11. "size": 18, "color": "CC0000", "font": "Arial",
  12. "italic": false,
  13. "link": "https://example.com/agenda"}],
  14. "background": "1F2937", // solid slide background (hex)
  15. "footer": "Confidential", // footer placeholder text
  16. "slide_number": true, // enable slide-number placeholder
  17. "notes": "Speaker notes for this slide"},
  18. {"layout": "blank", "title": "Widgets",
  19. "images": [{"path": "logo.png", "left": 1, "top": 1, "width": 3}],
  20. "tables": [{"left": 1, "top": 2, "width": 6, "height": 2,
  21. "rows": [["H1", "H2"], ["a", "b"]]}],
  22. "shapes": [{"type": "rounded_rectangle", "left": 8, "top": 1,
  23. "width": 3, "height": 1, "fill": "4472C4",
  24. "text": "Callout", "text_color": "FFFFFF"}],
  25. "charts": [{"type": "bar", "left": 1, "top": 3, "width": 6,
  26. "height": 3.5, "title": "Sales",
  27. "categories": ["Q1", "Q2"],
  28. "series": {"North": [10, 20], "South": [7, 13]}}]}
  29. ]
  30. }
  31. Layouts: title, title_content, section, two_content, title_only, blank
  32. Chart types: bar, bar_h, line, pie Shape types: rectangle,
  33. rounded_rectangle, oval, diamond, right_arrow, chevron
  34. """
  35. import argparse
  36. import copy
  37. import json
  38. import sys
  39. from pptx import Presentation
  40. from pptx.chart.data import CategoryChartData
  41. from pptx.dml.color import RGBColor
  42. from pptx.enum.chart import XL_CHART_TYPE
  43. from pptx.enum.shapes import MSO_SHAPE
  44. from pptx.util import Inches, Pt
  45. LAYOUTS = {"title": 0, "title_content": 1, "section": 2,
  46. "two_content": 3, "title_only": 5, "blank": 6}
  47. CHART_TYPES = {"bar": XL_CHART_TYPE.COLUMN_CLUSTERED,
  48. "bar_h": XL_CHART_TYPE.BAR_CLUSTERED,
  49. "line": XL_CHART_TYPE.LINE_MARKERS,
  50. "pie": XL_CHART_TYPE.PIE}
  51. SHAPE_TYPES = {"rectangle": MSO_SHAPE.RECTANGLE,
  52. "rounded_rectangle": MSO_SHAPE.ROUNDED_RECTANGLE,
  53. "oval": MSO_SHAPE.OVAL, "diamond": MSO_SHAPE.DIAMOND,
  54. "right_arrow": MSO_SHAPE.RIGHT_ARROW,
  55. "chevron": MSO_SHAPE.CHEVRON}
  56. def style_run(run, spec):
  57. """Apply font styling from a bullet/text spec dict to a run."""
  58. font = run.font
  59. if spec.get("size"):
  60. font.size = Pt(spec["size"])
  61. if spec.get("bold") is not None:
  62. font.bold = spec["bold"]
  63. if spec.get("italic") is not None:
  64. font.italic = spec["italic"]
  65. if spec.get("font"):
  66. font.name = spec["font"]
  67. if spec.get("color"):
  68. font.color.rgb = RGBColor.from_string(spec["color"])
  69. if spec.get("link"):
  70. run.hyperlink.address = spec["link"]
  71. def add_bullets(text_frame, bullets):
  72. text_frame.clear()
  73. for i, item in enumerate(bullets):
  74. if isinstance(item, str):
  75. item = {"text": item}
  76. para = text_frame.paragraphs[0] if i == 0 else text_frame.add_paragraph()
  77. para.level = int(item.get("level", 0))
  78. run = para.add_run()
  79. run.text = item.get("text", "")
  80. style_run(run, item)
  81. def copy_layout_placeholder(slide, ph_idx):
  82. """Copy a layout placeholder (footer=11, slide number=12) onto the
  83. slide so it actually renders; returns the shape or None if the layout
  84. does not provide it."""
  85. for ph in slide.slide_layout.placeholders:
  86. if ph.placeholder_format.idx == ph_idx:
  87. slide.shapes._spTree.append(copy.deepcopy(ph._element))
  88. for shape in slide.placeholders:
  89. if shape.placeholder_format.idx == ph_idx:
  90. return shape
  91. return None
  92. def set_slide_title(slide, text, slide_width):
  93. """Set a layout title or add a conventional title box as fallback."""
  94. if slide.shapes.title is not None:
  95. slide.shapes.title.text = text
  96. return slide.shapes.title
  97. shape = slide.shapes.add_textbox(
  98. Inches(0.5), Inches(0.3), slide_width - Inches(1), Inches(0.8))
  99. run = shape.text_frame.paragraphs[0].add_run()
  100. run.text = text
  101. run.font.size = Pt(28)
  102. run.font.bold = True
  103. return shape
  104. def build_slide(prs, spec):
  105. layout_idx = LAYOUTS.get(spec.get("layout", "title_content"), 1)
  106. slide = prs.slides.add_slide(prs.slide_layouts[layout_idx])
  107. if spec.get("background"):
  108. fill = slide.background.fill
  109. fill.solid()
  110. fill.fore_color.rgb = RGBColor.from_string(spec["background"])
  111. if spec.get("slide_number"):
  112. copy_layout_placeholder(slide, 12)
  113. if spec.get("footer"):
  114. shape = copy_layout_placeholder(slide, 11)
  115. if shape is not None:
  116. shape.text_frame.text = spec["footer"]
  117. if spec.get("title") is not None:
  118. set_slide_title(slide, spec["title"], prs.slide_width)
  119. if spec.get("subtitle") is not None:
  120. for ph in slide.placeholders:
  121. if ph.placeholder_format.idx == 1:
  122. ph.text = spec["subtitle"]
  123. break
  124. if spec.get("bullets"):
  125. body = next((ph for ph in slide.placeholders
  126. if ph.placeholder_format.idx != 0), None)
  127. if body is None:
  128. body = slide.shapes.add_textbox(Inches(0.5), Inches(1.5),
  129. Inches(9), Inches(5))
  130. add_bullets(body.text_frame, spec["bullets"])
  131. for img in spec.get("images", []):
  132. kwargs = {}
  133. if img.get("width"):
  134. kwargs["width"] = Inches(img["width"])
  135. if img.get("height"):
  136. kwargs["height"] = Inches(img["height"])
  137. slide.shapes.add_picture(img["path"], Inches(img.get("left", 1)),
  138. Inches(img.get("top", 1)), **kwargs)
  139. for tbl in spec.get("tables", []):
  140. rows = tbl["rows"]
  141. shape = slide.shapes.add_table(
  142. len(rows), len(rows[0]), Inches(tbl.get("left", 1)),
  143. Inches(tbl.get("top", 2)), Inches(tbl.get("width", 6)),
  144. Inches(tbl.get("height", 2)))
  145. for r, row in enumerate(rows):
  146. for c, val in enumerate(row):
  147. shape.table.cell(r, c).text = str(val)
  148. for shp in spec.get("shapes", []):
  149. shape = slide.shapes.add_shape(
  150. SHAPE_TYPES.get(shp.get("type", "rectangle"), MSO_SHAPE.RECTANGLE),
  151. Inches(shp.get("left", 1)), Inches(shp.get("top", 1)),
  152. Inches(shp.get("width", 2)), Inches(shp.get("height", 1)))
  153. if shp.get("fill"):
  154. shape.fill.solid()
  155. shape.fill.fore_color.rgb = RGBColor.from_string(shp["fill"])
  156. if shp.get("text"):
  157. shape.text_frame.text = shp["text"]
  158. if shp.get("text_color"):
  159. run = shape.text_frame.paragraphs[0].runs[0]
  160. run.font.color.rgb = RGBColor.from_string(shp["text_color"])
  161. for cht in spec.get("charts", []):
  162. data = CategoryChartData()
  163. data.categories = cht["categories"]
  164. for name, values in cht["series"].items():
  165. data.add_series(name, values)
  166. frame = slide.shapes.add_chart(
  167. CHART_TYPES.get(cht.get("type", "bar"),
  168. XL_CHART_TYPE.COLUMN_CLUSTERED),
  169. Inches(cht.get("left", 1)), Inches(cht.get("top", 2)),
  170. Inches(cht.get("width", 6)), Inches(cht.get("height", 4)), data)
  171. if cht.get("title"):
  172. frame.chart.has_title = True
  173. frame.chart.chart_title.text_frame.text = cht["title"]
  174. if spec.get("notes"):
  175. slide.notes_slide.notes_text_frame.text = spec["notes"]
  176. return slide
  177. def main(argv=None):
  178. if hasattr(sys.stdout, "reconfigure"):
  179. sys.stdout.reconfigure(encoding="utf-8", errors="replace")
  180. parser = argparse.ArgumentParser(
  181. description="Create a .pptx deck from a JSON spec.",
  182. epilog=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
  183. parser.add_argument("spec", help="path to JSON deck spec")
  184. parser.add_argument("output", help="output .pptx path")
  185. args = parser.parse_args(argv)
  186. with open(args.spec, encoding="utf-8") as fh:
  187. spec = json.load(fh)
  188. prs = Presentation()
  189. if spec.get("slide_size", "16:9") == "16:9":
  190. prs.slide_width, prs.slide_height = Inches(13.333), Inches(7.5)
  191. else:
  192. prs.slide_width, prs.slide_height = Inches(10), Inches(7.5)
  193. for slide_spec in spec.get("slides", []):
  194. build_slide(prs, slide_spec)
  195. prs.save(args.output)
  196. print(json.dumps({"ok": True, "output": args.output,
  197. "slides": len(prs.slides._sldIdLst)}))
  198. return 0
  199. if __name__ == "__main__":
  200. sys.exit(main())