首页 > 解决方案 > 如何控制docxtpl中的spces和分页符(基于现有的docx模板)?

问题描述

我创建了一个 docx 模板,然后使用 python 的docxtpl包生成了 python 代码来更新变量和所有其他数据到这个模板中:

 tpl = DocxTemplate((path.join('report','templates','my_template.docx')))
 tpl.new_subdoc()
 file_path = path.join(output_dir_name, file_name)
 get_all_data_report(tpl)
 tpl.save(file_path)enter code here

我不明白如何完全控制生成的 docx 文件中的空格/分页符。如果我在页面开头的模板中放置一些文本,它有时会移动并添加 x 行空格。

标签: pythondocxpython-docx

解决方案


from docxtpl import *
tpl = DocxTemplate('templates/escape_tpl.docx')
context = {'myvar': R('"less than" must be escaped : <, this can be done with RichText() or R()'),
       'myescvar': 'It can be escaped with a "|e" jinja filter in the template too : < ',
       'nlnp': R('Here is a multiple\nlines\nstring\aand some\aother\aparagraphs\aNOTE: the current character styling is removed'),
       'mylisting': Listing('the listing\nwith\nsome\nlines\nand special chars : <>&\f ... and a page break'),
       'page_break': R('\f'),
       }
tpl.render(context)
tpl.save('output/escape.docx')

并在您的模板中使用 {{r page_break}}

看到这个https://github.com/elapouya/python-docx-template/blob/master/tests/escape.py

和这个https://github.com/elapouya/python-docx-template/blob/master/tests/templates/escape_tpl.docx


推荐阅读