Python docx库水平居中对齐图片

15 投票
1 回答
15629 浏览
提问于 2025-04-28 15:36

我正在用 https://python-docx.readthedocs.org/en/latest/ 创建一个自动报告程序。

我想把一张图片居中,甚至试过在网上看到的一个小技巧:

document.add_picture('C:\Users\Public\Pictures\Picture.jpg',height=Inches(3.44)) last_paragraph = document.paragraphs[-1] last_paragraph.style = 'centerstyle'

但是没有成功……

有没有人找到解决这个问题的方法?

暂无标签

1 个回答

43

你可以这样做。

from docx import Document
from docx.enum.text import WD_ALIGN_PARAGRAPH

my_image = document.add_picture('path/to/image') 
last_paragraph = document.paragraphs[-1] 
last_paragraph.alignment = WD_ALIGN_PARAGRAPH.CENTER

我知道我可能回复得有点晚了,但也许这对其他人有帮助。

撰写回答