具體生成word的代碼就不粘貼了,下面只介紹圖片居中的方法,因爲docx庫add_picture()方法不支持對圖片位置的設置。所以有兩種思路:
1、新建一個1行3列的表格,在中間的一列中插入圖片
2、改變段落的位置(直接將最近的一個段落更改)
第一個方法:
def add_center_picture(self, image_path_or_stream, width=None, height=None):
# run = self.doc.add_paragraph().add_run()
tab = self.doc.add_table(rows=1, cols=3) # 添加一個1行3列的空表
cell = tab.cell(0, 1) # 獲取某單元格對象(從0開始索引)
ph =cell.paragraphs[0]
run = ph.add_run()
# run.add_break()
run.add_picture(image_path_or_stream, width=width, height=height)
第二個方法:
def align_center(self):
last_paragraph = self.doc.paragraphs[-1]
last_paragraph.alignment = docx.enum.text.WD_ALIGN_PARAGRAPH.CENTER