在实际渲染字典中的内容之前,我正在使用 docxtpl (python-docx-template) 渲染模板。尽管一切正常,但我的图像总是丢失。
我为我的模板收集了多个其他 docx 文件,访问它们,渲染字典中的内容并将它们保存在字节流中。但是,当加载组件并将其放入主文件中时,图像丢失了。有什么想法吗?
from io import BytesIO
from docx import Document
from docxtpl import DocxTemplate
from docxcompose.composer import Composer
templates_folder = os.path.join(os.path.dirname(__file__), 'templates')
output_folder = os.path.join(os.path.dirname(__file__), 'output')
test_data = {
'MODUL_header': {
'something': 'bla'
},
def generate_header(template_path):
document = DocxTemplate(template_path)
document.render(test_data)
file_stream = BytesIO()
document.save(file_stream)
file_stream.seek(0)
return file_stream
def test(template_path):
with open(template_path, 'rb') as f:
source_stream = BytesIO(f.read())
# Declare Template-Object
document = DocxTemplate(source_stream)
if "MODUL_header" in test_data:
_path = os.path.join(templates_folder, 'header.docx')
header = document.new_subdoc(generate_kopfzeile(_path))
test_data['MODUL_header'] = header
document.render(test_data)
file_path = os.path.join(output_folder, 'test.docx')
document.save(file_path)
if __name__ == '__main__':
template_path = os.path.join(templates_folder, 'main_template.docx')
test(template_path)
当然,我的 docx 文件中有一个名为
MODUL_header
的 var :)
我遇到了类似的问题,标题图像中的 ID 和正文中的图像发生冲突。
要进行检查,请使用 7-Zip 之类的工具打开 docx 文件中的 word 文件夹,并检查 header.xml 文件中的任何图片 ID 是否与 document.xml 文件中的任何 ID 冲突。