python-pptx
python-pptx is a Python library for creating, reading, and updating PowerPoint (.pptx) files. A typical use would be generating a PowerPoint presentation from dynamic content such as a database query, analytics output, or a JSON payload. It is currently at version 1.0.2 and aims for industrial-grade reliability with a comprehensive testing regimen.
Warnings
- breaking Several API changes occurred around versions 0.6.x to 1.0.x, including enumeration renames (e.g., `pptx.enum.MSO_COLOR_TYPE` moved to `pptx.enum.dml.MSO_COLOR_TYPE`) and property renames (e.g., `SlideLayout.slidemaster` to `SlideLayout.slide_master`). Additionally, line-break encoding in `.text` properties changed from newline (\n) to vertical-tab (\v) in version 0.6.18 to better distinguish from paragraph boundaries.
- gotcha The library exclusively supports PowerPoint Open XML files (`.pptx` format, introduced with PowerPoint 2007). Older PowerPoint `.ppt` files (PowerPoint 2003 and earlier) are not supported.
- gotcha When saving a presentation, if you specify a filename that already exists, `python-pptx` will overwrite the file silently without any warning or prompt.
- gotcha Avoid directly instantiating internal classes (e.g., `pptx.presentation.Presentation`). Instead, use the `pptx.Presentation()` factory function to create a new presentation or load an existing one.
- gotcha While `pip install python-pptx` typically handles core dependencies, if you use the `setup.py` installation method, or encounter issues with charting, verify that `XlsxWriter` is installed, as it is required for charting features.
Install
-
pip install python-pptx
Imports
- Presentation
from pptx import Presentation
- Inches
from pptx.util import Inches
Quickstart
from pptx import Presentation
from pptx.util import Inches
# Create a new presentation
prs = Presentation()
# Add a title slide (layout index 0)
title_slide_layout = prs.slide_layouts[0]
slide = prs.slides.add_slide(title_slide_layout)
# Set title and subtitle
title = slide.shapes.title
subtitle = slide.placeholders[1]
title.text = "Hello, World!"
subtitle.text = "python-pptx was here!"
# Add a blank slide (layout index 6) and add a textbox
blank_slide_layout = prs.slide_layouts[6]
slide = prs.slides.add_slide(blank_slide_layout)
left = top = width = height = Inches(1.0)
textbox = slide.shapes.add_textbox(left, top, width, height)
textbox.text = "This is a custom textbox."
# Save the presentation
prs.save('test.pptx')
print("Presentation 'test.pptx' created successfully.")