このプログラムは、PowerPointがインストールされたWindows環境で動作することを前提としています。 プログラムの主な特徴: 形式対応の拡充 PDF、PPTX、PPT、ODP、PNG、JPG、GIF形式に対応 列挙型を使用した型安全な実装 PDFオプションの詳細制御 品質設定(標準、最小、最高) プログラム中のコメント 非表示スライドの制御 ドキュメント構造タグの制御 エラー処理 適切な例外処理 リソースの確実な解放 エラーメッセージ シンプルなインターフェース 分かりやすい使用例 from enum import IntEnum import os import comtypes.client # 出力形式の定義 class OutputFormat(IntEnum): PDF = 32 PPTX = 11 PPT = 1 PNG = 18 JPG = 17 GIF = 16 def convert_presentation( input_path: str, output_path: str, format: str = "pdf", include_hidden: bool = False, optimize_size: bool = False ): """ PowerPointファイルを指定された形式に変換します。 Args: input_path (str): 入力ファイルのパス output_path (str): 出力ファイルのパス format (str): 出力形式 ("pdf", "pptx", "ppt", "png", "jpg", "gif") include_hidden (bool): 非表示スライドを含めるか optimize_size (bool): ファイルサイズを最適化するか """ format = format.lower() if not hasattr(OutputFormat, format.upper()): raise ValueError(f"未対応の形式です: {format}") format_code = getattr(OutputFormat, format.upper()) powerpoint = comtypes.client.CreateObject("Powerpoint.Application") powerpoint.Visible = False try: presentation = powerpoint.Presentations.Open(input_path) if format in ("png", "jpg", "gif"): # 画像形式の場合の処理 for i in range(1, presentation.Slides.Count + 1): slide_path = f"{os.path.splitext(output_path)[0]}_slide{i}.{format}" presentation.Slides(i).Export(slide_path, format.upper()) else: # PDF形式の場合の設定 if format == "pdf": presentation.ExportAsFixedFormat( output_path, 2, # ppFixedFormatTypePDF Intent=1, # ppFixedFormatIntentScreen PrintHiddenSlides=include_hidden, OpenAfterPublish=False, OptimizeForPrint=not optimize_size ) else: # その他の形式の場合 presentation.SaveAs(output_path, format_code) except Exception as e: raise RuntimeError(f"変換エラー: {str(e)}") from e finally: try: presentation.Close() powerpoint.Quit() except: pass # 使用例 if __name__ == "__main__": # 基本的なPDF変換 convert_presentation( "input.pptx", "output.pdf" ) # 高品質PDF作成 convert_presentation( "input.pptx", "output_high_quality.pdf", optimize_size=False ) # 最小サイズのPDF作成 convert_presentation( "input.pptx", "output_minimal.pdf", optimize_size=True ) # 画像形式への変換 convert_presentation( "input.pptx", "output.png", format="png" )