python-pptxについて勉強したので、それについてまとめる。/npython-pptxはオブジェクトの階層化構造を取っており、各要素で親子関係がある。 階層順に紹介していく。
階層順
- Presentationオブジェクト
- slideオブジェクト
- shapeオブジェクト
- placeholderオブジェクト
コードサンプル
prs = Presentation() (既存のファイルを読み込むときは()の中にファイルパスを記述)
slides = prs.slides
slide = slides[0]
shape = slide.shapes
placeholders = slide.placeholders
このようにPresentationオブジェクトを生成して、それに対してslideオブジェクト、shapeオブジェクトを作成していく。
shapeとplaceholderの違い
shape テキストボックスや画像など、そのスライドに存在しているもの全てのこと placeholder スライドを追加した際に最初から存在するtitleやsubtitle用のテキストボックスのこと shapeを取得すると全てを取得できるが、placeholderを取得すると一部しか取得できない。
placeholderにテキストを挿入する方法
placeholder = slide.placeholders[0] pleceholder.text = "test"
pleceholder.textはString型しか入らないので、数値を入れたいときはstr()で変換する。
テキストボックスの操作について
テキストボックスの作成
textbox = slide.shapes.add_textbox(left, top, width, height) tf = textbox.text_frame paragraph = tf.paragraphs[0] paragraph.text = "test" paragraph.font.name = "Alial" paragraph.font.size = Pt(18)
テキストボックスの中も階層化されており、以下のような順となっている。 text_frame paragraphs *runs
text_frame
まずテキストを書き込むために該当するtextboxにたいしてtext_frameオブジェクトを生成する。文字を入力するには生成したオブジェクトに対して.textとする。しかし、この入力方法だと文字のフォントなどは変更できないため注意が必要となる。
tf = textbox.text_frame
tf.text = "test"
paragraphs
text_frameの中にはparagraphがある。paragraphは一行に対して操作を行うことができる。できることとしては文字の入力、フォントの変更、文字の大きさの変更などがある。一行に対して行われるため、個別に色を変えたい場合はrunsを用いる必要がある。
tf.add_paragraph() paragraphs = tf.paragraphs paragraph = paragraphs[0] paragraph.text = "test" paragraph.font.name = "Alial" paragraph.font.size = Pt(18)
runs
段落内のテキストを細かく設定するときに用いる。add_run()でparagraph[n]の中に小さな領域を作成し、そこに文字を入力したり、フォントを設定するイメージ。
tf.add_paragraph() pg = tf.paragraphs[1] rn0 = pg.add_run() rn0.text = "rn0" rn0.font.color.rgb = RGBColor(255, 0 , 0) rn1 = pg.add_run() rn1.text = "rn1" rn1.font.italic = True