非IT企業に勤める中年サラリーマンのIT日記

非IT企業でしかもITとは全く関係ない部署にいる中年エンジニア。唯一の趣味がプログラミングという”自称”プログラマー。

【Python】定型レイアウトのPowerPoint資料作成を自動化する(画像挿入編)

   

業務において、大量の画像データをPowerPoint資料にまとめる作業は頻繁に発生しますが、手作業での貼り付けや整列は多大な時間を要します。本記事ではPythonの python-pptx ライブラリを活用し、特定の命名規則に従った画像ファイルを自動的にグルーピング、既存のテンプレートを基にスライドを生成・配置するプログラムを紹介します。定型報告書の作成を効率化の一助となればと。

プログラムの概要
  • 命名規則に基づく自動判別: 画像名の特定の数値を抽出し、同じ数値を持つ画像を1枚のスライドにまとめます。
  • テンプレートの再利用: format.pptx の2枚目のスライドレイアウトを複製元として使用し、書式を維持します。
  • 等間隔の自動配置: スライド幅に合わせて、複数枚の画像を横並びに自動整列させます。
  • テストデータ生成機能: 実装の動作確認用に、指定された背景色とラベルを持つPNG画像を生成するコードも同梱しています。
ソースコード
import os
import re
from pptx import Presentation
from pptx.util import Inches

def automate_ppt_generation():
    # 入出力ファイルとフォルダの定義
    input_file = "format.pptx"
    output_file = "result.pptx"
    image_dir = "img"

    if not os.path.exists(input_file):
        print("エラー: テンプレートとなる format.pptx が見つかりません。")
        return

    # 1. 画像ファイルを数値ごとにグルーピング
    # 例: {'01': ['img01a.png', 'img01b.png', 'img01c.png'], ...}
    image_groups = {}
    pattern = re.compile(r'img(\d{2})[a-c]\.png')
    
    files = sorted(os.listdir(image_dir))
    for f in files:
        match = pattern.search(f)
        if match:
            group_id = match.group(1)
            if group_id not in image_groups:
                image_groups[group_id] = []
            image_groups[group_id].append(os.path.join(image_dir, f))

    # 2. PowerPointの読み込みとテンプレート設定
    prs = Presentation(input_file)
    # テンプレートとして2枚目(インデックス1)のレイアウトを使用
    base_slide = prs.slides[1]
    slide_layout = base_slide.slide_layout

    # 3. グループごとにスライドを処理
    sorted_ids = sorted(image_groups.keys())
    for idx, gid in enumerate(sorted_ids):
        # 最初のグループは既存の2枚目を使い、以降は新規スライドを追加
        if idx == 0:
            slide = base_slide
        else:
            slide = prs.slides.add_slide(slide_layout)
        
        # 配置する画像のリストを取得
        current_images = image_groups[gid]
        num_imgs = len(current_images)

        # 4. 画像の配置位置の計算
        # スライドの全幅を画像枚数で割り、中央寄せで並べる
        slide_width = prs.slide_width
        img_w = Inches(2.8) # 画像1枚の幅
        img_top = Inches(2.5) # 上部からの固定位置
        
        # 余白を計算して均等配置
        total_img_width = img_w * num_imgs
        spacing = (slide_width - total_img_width) / (num_imgs + 1)

        for i, img_path in enumerate(current_images):
            left = spacing + (img_w + spacing) * i
            # 画像をスライドに挿入
            slide.shapes.add_picture(img_path, left, img_top, width=img_w)

    # 5. 結果の保存
    prs.save(output_file)
    print(f"処理完了: {output_file} を保存しました。")

if __name__ == "__main__":
    automate_ppt_generation()
 

 

スポンサーリンク

 - Python