LoginSignup
21

More than 5 years have passed since last update.

posted at

updated at

Pythonで画像ファイルをパワポに貼る

内容

タイトル通りディレクトリにある複数の画像をパワポに自動で貼るプログラムです。

プログラム

from pptx import Presentation
from glob import glob

# Presentationインスタンスの作成
ppt = Presentation()
# 幅
width = ppt.slide_width
# 高さ
height = ppt.slide_height

# レイアウト, 6番は白紙
blank_slide_layout = ppt.slide_layouts[6]

# 画像ファイルの読み込み
fnms = glob('./figure/*.png')

# ファイル毎にループ
for fnm in fnms:
    # 白紙のスライドの追加
    slide = ppt.slides.add_slide(blank_slide_layout)

    # 画像の挿入
    pic = slide.shapes.add_picture(fnm, 0, 0)

    # 中心に移動
    pic.left = int( ( width  - pic.width  ) / 2 )
    pic.top  = int( ( height - pic.height ) / 2 )

# 名前をつけて保存
ppt.save('figure.pptx')

おまけ

上のやり方だと連番のファイル名の順番がバラバラになるので、数字順にソートするやり方です。もっといいやり方があると思うので教えてほしいです...。

import re

# 文字列から数値だけを取り出す
def str2int(str):
    i = int( re.search('\d+',str).group() )
    return i

# ファイルの読み込み
fnms = glob('./figure/*.png')
# ソート
fnms.sort(key=str2int)

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
What you can do with signing up
21