- 模版:/root/main/index.docx
{{ title_pic1 }}
{{ title_pic2 }}
{{ title_pic3 }}
- 渲染函数
import sys
import jinja2
from docxtpl import DocxTemplate, InlineImage
from docx.shared import Mm, Pt
def render(tpl_path='index.docx', output='sample.docx', **kwargs):
tpl = DocxTemplate(tpl_path)
jinja_env = jinja2.Environment(trim_blocks=True, lstrip_blocks=True)
if 'images' in kwargs:
for pic in kwargs['images']:
width = pic.get('width')
height = pic.get('height')
if width and height:
kwargs.setdefault(pic.get('name'), InlineImage(tpl, pic.get('path'), width=Pt(width), height=Pt(height)))
elif width:
kwargs.setdefault(pic.get('name'), InlineImage(tpl, pic.get('path'), width=Pt(width)))
else:
kwargs.setdefault(pic.get('name'), InlineImage(tpl, pic.get('path'), height=Pt(height)))
del kwargs['images']
tpl.render(kwargs, jinja_env)
tpl.save(output)
print("completed")
def cmd_format(**data):
filepath = sys.argv
filepath.append('')
filepath.append('')
if filepath[1] and filepath[2]:
render(filepath[1], filepath[2], **data)
elif filepath[1]:
render(filepath[1], **data)
else:
render(**data)
if __name__ == '__main__':
datainput = {
'images': [
{'name': 'title_pic1', 'path': 'pic/test.png', 'height': 100},
{'name': 'title_pic2', 'path': 'pic/test.png', 'width': 100},
{'name': 'title_pic3', 'path': 'pic/test.png', 'width': 100, 'height': 100}
]
}
cmd_format(**datainput)
- 效果
Original: https://blog.csdn.net/chucksun0426/article/details/125205012
Author: chuck-Gemini
Title: Python运维(五)–Jinja2、word模板及Excel
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/748829/
转载文章受原作者版权保护。转载请注明原作者出处!