使用 python-docx 和 docxtpl 将图像添加到 header

Add image to header using python-docx and docxtpl

我有将图像插入 DOCX 模板的工作代码(使用 docxtpl 提供的 Jinja 模板格式),但是当图像插入文档时可以正常工作 body 图像无法在 header。文档中的插入点 {{p my_image}} 显示消息 'Read Error'.

我假设这是 python-docx 库中的 bug/limitation,但我想知道是否有已知的解决方法。我已经尝试了 2 种方法来创建图像,但只有在 header:

中使用时,它们都失败并显示相同的 'Read Error' 消息

方法一:

sub_doc = self.template.new_subdoc()
p = sub_doc.add_paragraph()
r = p.add_run()
r.add_picture(output_path)
return sub_doc

方法二:

from docxtpl import InlineImage
return InlineImage(template, image_path, width, height)

老问题,但也许有人需要它。

我使用 docx 模块将图像写入 header 的 DOCX 文件,如下所示。就我而言,我必须将图像写入 table.

from docx import Document
from docx.shared import Inches

header = doc.sections[0].header

#Insert table with 2 rows and 3 columns
headertable = header.add_table(2, 3, Inches(6))
headertable.style("borderColor:black")
a = headertable.cell(0, 0)
b = headertable.cell(1, 0)
A = a.merge(b)

#add table in header
headertab_cells = headertable.rows[0].cells

ht0 = headertab_cells[0].add_paragraph()
kh = ht0.add_run()
kh.add_picture('logo.jpg', width=Inches(1))