Use this file to discover Exa products, pricing, evaluations, comparisons, use cases, agent interfaces, and technical documentation before exploring further.
Python PowerPoint libraries create, read, and edit PowerPoint presentations from code. A file library edits the PPTX format directly rather than driving an installed copy of PowerPoint through COM automation. These libraries let report generators and AI agents turn data and drafts into slide decks.
Popularity
python-pptx has the most monthly downloads in this comparison, at 142.1M.
def _write_pptx_file(
self,
file_path: Path,
content: List[Dict[str, Any]],
template: Optional[str] = None,
) -> None:
r"""Write text content to a PPTX file with enhanced formatting.
Args:
file_path (Path): The target file path.
content (List[Dict[str, Any]]): The content to write to the PPTX
file. Must be a list of dictionaries where:
- First element: Title slide with keys 'title' and 'subtitle'
- Subsequent elements: Content slides with keys 'title', 'text'
template (Optional[str]): The name of the template to use. If not
provided, the default template will be used. (default: :obj:
`None`)
"""
from pptx import Presentation
# Use template if provided, otherwise create new presentation if template is not None:
template_path = Path(template).resolve()
if not template_path.exists():
logger.warning(
f"Template file not found: {template_path}, using "
"default template"
)
presentation = Presentation()
else:
presentation = Presentation(str(template_path))
# Clear all existing slides by removing them from the slide # list while len(presentation.slides) > 0:
rId = presentation.slides._sldIdLst[-1].rId
presentation.part.drop_rel(rId)
del presentation.slides._sldIdLst[-1]
else:
presentation = Presentation()
slide_width_inch, slide_height_inch = (
self._get_slide_width_height_inches(presentation)
)
# Process slides if content:
# Title slide (first element) title_slide_data = content.pop(0) if content else {}
title_layout = presentation.slide_layouts[0]
title_slide = presentation.slides.add_slide(title_layout)
# Set title and subtitle if title_slide.shapes.title:
title_slide.shapes.title.text_frame.clear()
self._format_text(
title_slide.shapes.title.text_frame.paragraphs[0],
title_slide_data.get("title", ""),
)
if len(title_slide.placeholders) > 1:
subtitle = title_slide.placeholders[1]
subtitle.text_frame.clear()
self._format_text(
subtitle.text_frame.paragraphs[0],
title_slide_data.get("subtitle", ""),
)
# Content slides for slide_data in content:
if not isinstance(slide_data, dict):
continue
# Handle different slide types if 'table' in slide_data:
self._handle_table(
presentation,
slide_data,
)
elif 'bullet_points' in slide_data:
if any(
step.startswith(STEP_BY_STEP_PROCESS_MARKER)
for step in slide_data['bullet_points']
):
self._handle_step_by_step_process(
presentation,
slide_data,
slide_width_inch,
slide_height_inch,
)
else:
self._handle_default_display(
presentation,
slide_data,
)
# Save the presentation presentation.save(str(file_path))
logger.debug(f"Wrote PPTX to {file_path} with enhanced formatting")
async def handle_call_tool(
name: str, arguments: dict | None
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
"""Handle tool execution requests.
Tools can modify server state and notify clients of changes.
"""
if name not in ["convert-contents"]:
raise ValueError(f"Unknown tool: {name}")
if not arguments:
raise ValueError("Missing arguments")
# Extract all possible arguments contents = arguments.get("contents")
input_file = arguments.get("input_file")
output_file = arguments.get("output_file")
output_format = arguments.get("output_format", "markdown").lower()
input_format = arguments.get("input_format", "markdown").lower()
# The public MCP schema uses "txt"; Pandoc names the equivalent writer "plain". pandoc_output_format = "plain" if output_format == "txt" else output_format
reference_doc = arguments.get("reference_doc")
filters = arguments.get("filters", [])
defaults_file = arguments.get("defaults_file")
# Validate input parameters if not contents and not input_file:
raise ValueError("Either 'contents' or 'input_file' must be provided")
# Validate reference_doc if provided if reference_doc:
if output_format not in REFERENCE_DOC_FORMATS:
raise ValueError(
f"reference_doc is not supported for '{output_format}' output format. "
f"Supported formats: {_join_with_and(REFERENCE_DOC_FORMATS)}"
)
if not os.path.exists(reference_doc):
raise ValueError(f"Reference document not found: {reference_doc}")
if not os.path.isfile(reference_doc):
raise ValueError(f"Reference document is not a file: {reference_doc}")
# Pandoc does not verify that the reference document matches the writer. A # mismatch is silently ignored for docx output, and produces an unreadable # file for odt output. Both exit 0 with no warning, so we reject it here. expected_extension = f".{output_format}"
actual_extension = os.path.splitext(reference_doc)[1].lower()
if actual_extension != expected_extension:
raise ValueError(
f"reference_doc must be a '{expected_extension}' file when output_format is "
f"'{output_format}', but '{os.path.basename(reference_doc)}' was given. Pandoc "
f"does not reject a mismatched reference document; it silently produces an "
f"unstyled or unreadable file. Create a matching template with: "
f"pandoc -o reference{expected_extension} "
f"--print-default-data-file reference{expected_extension}"
)
# Validate defaults_file if provided if defaults_file:
if not os.path.exists(defaults_file):
raise ValueError(f"Defaults file not found: {defaults_file}")
# Check if it's a valid YAML file and readable try:
with open(defaults_file) as f:
yaml_content = yaml.safe_load(f)
# Validate the YAML structure if not isinstance(yaml_content, dict):
raise ValueError(f"Invalid defaults file format: {defaults_file} - must be a YAML dictionary")
# Check if the defaults file specifies an output format that conflicts with the requested format if 'to' in yaml_content and yaml_content['to'] != output_format:
print(
f"Warning: Defaults file specifies output format '{yaml_content['to']}' "
f"but requested format is '{output_format}'. Using requested format."
)
except yaml.YAMLError as e:
raise ValueError(f"Error parsing defaults file {defaults_file}: {str(e)}") from e
except PermissionError as e:
raise ValueError(f"Permission denied when reading defaults file: {defaults_file}") from e
except Exception as e:
raise ValueError(f"Error reading defaults file {defaults_file}: {str(e)}") from e
# Validate the output format against the single list the schema also advertises, so # the runtime check and the enum cannot drift apart. if output_format not in OUTPUT_FORMATS:
raise ValueError(
f"Unsupported output format: '{output_format}'. Supported formats are: {', '.join(OUTPUT_FORMATS)}"
)
if input_format not in INPUT_FORMATS:
raise ValueError(
f"Unsupported input format: '{input_format}'. Supported input formats are: "
f"{', '.join(INPUT_FORMATS)}. Pandoc writes some formats it cannot read, so the "
f"input list is shorter than the output list."
)
# Validate output_file requirement for advanced formats if output_format in ADVANCED_FORMATS and not output_file:
raise ValueError(f"output_file path is required for {output_format} format")
# Validate filters if provided if filters:
if not isinstance(filters, list):
raise ValueError("filters parameter must be an array of strings")
for filter_path in filters:
if not isinstance(filter_path, str):
raise ValueError("Each filter must be a string path")
def resolve_filter_path(filter_path, defaults_file=None):
"""Resolve a filter path by trying multiple possible locations.
Args:
---- filter_path: The original filter path (absolute or relative)
defaults_file: Optional path to the defaults file for context
Returns:
------- Resolved absolute path to the filter if found, or None if not found
"""
# If it's already an absolute path, just use it if os.path.isabs(filter_path):
paths = [filter_path]
else:
# Try multiple locations for relative paths paths = [
# 1. Relative to current working directory os.path.abspath(filter_path),
# 2. Relative to the defaults file directory (if provided) os.path.join(os.path.dirname(os.path.abspath(defaults_file)), filter_path) if defaults_file else None,
# 3. Relative to the .pandoc/filters directory os.path.join(os.path.expanduser("~"), ".pandoc", "filters", os.path.basename(filter_path))
]
# Remove None entries paths = [p for p in paths if p]
# Try each path for path in paths:
if os.path.exists(path):
# Check if executable and try to make it executable if not if not os.access(path, os.X_OK):
try:
os.chmod(path, os.stat(path).st_mode | 0o111)
print(f"Made filter executable: {path}")
except Exception as e:
print(f"Warning: Could not make filter executable: {path} - {str(e)}")
continue
print(f"Using filter: {path}")
return path
return None
def validate_filters(filters, defaults_file=None):
"""Validate filter paths and ensure they exist and are executable."""
validated_filters = []
for filter_path in filters:
resolved_path = resolve_filter_path(filter_path, defaults_file)
if resolved_path:
validated_filters.append(resolved_path)
else:
raise ValueError(f"Filter not found in any of the searched locations: {filter_path}")
return validated_filters
def format_result_info(filters=None, defaults_file=None, validated_filters=None):
"""Format filter and defaults file information for result messages."""
filter_info = ""
defaults_info = ""
if filters and validated_filters:
filter_names = [os.path.basename(f) for f in validated_filters]
filter_info = f" with filters: {', '.join(filter_names)}"
if defaults_file:
defaults_basename = os.path.basename(defaults_file)
defaults_info = f" using defaults file: {defaults_basename}"
return filter_info, defaults_info
try:
# Prepare conversion arguments extra_args = []
# Add defaults file if provided - ensure it's properly formatted for Pandoc if defaults_file:
# Make sure the path is absolute defaults_file_abs = os.path.abspath(defaults_file)
extra_args.extend(["--defaults", defaults_file_abs])
# Set environment variables for filters env = os.environ.copy()
if output_file:
# Set PANDOC_OUTPUT_DIR to the directory of the output file output_dir = os.path.dirname(os.path.abspath(output_file))
env["PANDOC_OUTPUT_DIR"] = output_dir
else:
output_dir = None
# Validate filters once and reuse the result validated_filters = validate_filters(filters, defaults_file) if filters else []
# Handle filter arguments for filter_path in validated_filters:
extra_args.extend(["--filter", filter_path])
# Handle PDF-specific conversion if needed if output_format == "pdf":
extra_args.extend([
"--pdf-engine=xelatex",
"-V", "geometry:margin=1in"
])
# Handle reference doc for the formats pandoc accepts --reference-doc for if reference_doc and output_format in REFERENCE_DOC_FORMATS:
extra_args.extend(["--reference-doc", reference_doc])
# No special processing needed for content # Convert content using pypandoc if input_file:
if not os.path.exists(input_file):
raise ValueError(f"Input file not found: {input_file}")
if output_file:
# Convert file to file converted_output = pypandoc.convert_file(
input_file,
pandoc_output_format,
outputfile=output_file,
extra_args=extra_args
)
# Create result message with filter and defaults information filter_info, defaults_info = format_result_info(filters, defaults_file, validated_filters)
result_message = f"File successfully converted{filter_info}{defaults_info} and saved to: {output_file}"
else:
# Convert file to string converted_output = pypandoc.convert_file(
input_file,
pandoc_output_format,
extra_args=extra_args
)
else:
# No special processing needed for content if output_file:
# Convert content to file pypandoc.convert_text(
contents,
pandoc_output_format,
format=input_format,
outputfile=output_file,
extra_args=extra_args
)
# Create result message with filter and defaults information filter_info, defaults_info = format_result_info(filters, defaults_file, validated_filters)
result_message = (
f"Content successfully converted{filter_info}{defaults_info} and saved to: {output_file}"
)
else:
# Convert content to string converted_output = pypandoc.convert_text(
contents,
pandoc_output_format,
format=input_format,
extra_args=extra_args
)
if output_file:
notify_with_result = result_message
else:
if not converted_output:
raise ValueError("Conversion resulted in empty output")
# Add filter and defaults information to the notification filter_info, defaults_info = format_result_info(filters, defaults_file, validated_filters)
# Adjust format for inline display if filter_info:
filter_info = f" (with filters: {', '.join([os.path.basename(f) for f in validated_filters])})"
if defaults_info:
defaults_info = f" (using defaults file: {os.path.basename(defaults_file)})"
notify_with_result = (
f'Following are the converted contents in {output_format} format{filter_info}{defaults_info}.\n'
f'Ask user if they expect to save this file. If so, provide the output_file parameter with '
f'complete path.\n'
f'Converted Contents:\n\n{converted_output}'
)
return [
types.TextContent(
type="text",
text=notify_with_result
)
]
except Exception as e:
# Handle Pandoc conversion errors error_prefix = "Error converting"
error_details = str(e)
if "Filter not found" in error_details or "Filter is not executable" in error_details:
error_prefix = "Filter error during conversion"
elif "defaults" in error_details and defaults_file:
error_prefix = "Defaults file error during conversion"
# Add more context about the defaults file error_details += f" (defaults file: {defaults_file})"
elif "pandoc" in error_details.lower() and "not found" in error_details.lower():
error_prefix = "Pandoc executable not found"
error_details = "Please ensure Pandoc is installed and available in your PATH"
error_msg = (
f"{error_prefix} {'file' if input_file else 'contents'} from {input_format} to "
f"{output_format}: {error_details}"
)
raise ValueError(error_msg) from e
import aspose.slides as slides
# Instantiates a Presentation object that represents a presentation filewith slides.Presentation() as presentation:
slide = presentation.slides[0]
# Adds an autoshape with type set to line slide.shapes.add_auto_shape(slides.ShapeType.LINE, 50, 150, 300, 0)
presentation.save("NewPresentation_out.pptx", slides.export.SaveFormat.PPTX)
python-pptx suits creating and editing PPTX files on any platform. Aspose.Slides and Spire.Presentation suit teams that need a commercial SDK that also renders slides as images. pywin32 suits Windows machines that automate an installed copy of PowerPoint.
python-pptx creates, reads, and updates PowerPoint files through slide and shape objects. It does not render slides as images.
python-pptx builds a presentation from slide layouts and adds text boxes, pictures, and shapes to each slide before saving the file.
python-pptx cannot render slides. Aspose.Slides and Spire.Presentation export slide images through their own renderers. On Windows, pywin32 can call the export function of an installed copy of PowerPoint.
For coding agents
Found your PowerPoint library? Help your agent use it.
Connect Exa so your coding agent can find the library’s documentation, check its API, and look up implementations while you build.