本記事では、Pythonにて複数の画像ファイルをMicrosoft OfficeのWordに貼り付ける雛形コードを載せました。使用するライブラリは「python-docx」と「Pillow」です。
雛形コードは下記①②で、画像ファイルを各ページに4枚ずつ貼り付ける場合と6枚の場合の2パターンです。一応、仕様として貼り付ける画像の枚数は、列方向と行方向の数をそれぞれ任意に指定できます。但し、その場合はレイアウトが崩れる可能性があります。
▼①各ページ4枚の画像貼り付けの場合
各頁の冒頭に余白を設定して、8行分の文章を手入力できるレイアウトです。
▼②各ページ6枚の画像貼り付けの場合
図を各頁に余白なく貼り付けるレイアウトです。
■ライブラリのインストール
pip install python-docx
pip install Pillow
■本プログラム
冒頭で述べた2パターンのレイアウト①②は、変数「my_rows」の値を順に2, 3に指定した場合で実現できます。
import glob
from docx import Document
from docx.shared import Inches
from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
from PIL import Image
import os
doc = Document()
section = doc.sections[0]
section.top_margin = Inches(0.7)
section.left_margin = Inches(0.7)
section.right_margin = Inches(0.7)
section.bottom_margin = Inches(0.7)
images = glob.glob("./dir_img/*.jpg")
my_cols = 2
my_rows = 3
figs_per_page = my_rows * my_cols
for i in range(0, len(images), figs_per_page):
if my_rows == 2:
for _ in range(8):
doc.add_paragraph()
table = doc.add_table(rows=my_rows, cols=my_cols)
for row in table.rows:
row.width = doc.sections[0].page_width
for row in range(my_rows):
for col in range(my_cols):
if i < len(images):
cell = table.cell(row, col)
cell.text = ''
paragraph = cell.paragraphs[0]
run = paragraph.add_run()
with Image.open(images[i]) as img:
original_width, original_height = img.size
aspect_ratio = original_height / original_width
new_width = doc.sections[0].page_width / 2.5
new_height = new_width * aspect_ratio
run.add_picture(images[i], width=new_width, height=new_height)
paragraph = cell.add_paragraph(f"図{i+1}. ")
paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
i += 1
else:
break
if i >= len(images):
break
if i % figs_per_page == 0 and i != 0:
doc.add_page_break()
doc.save(f"output_{figs_per_page}figs_per_page.docx")
以上
<広告>
リンク
リンク
リンク