如何控制docxtpl中的spces和分页符(基于现有的docx模板)?

时间:2019-04-12 16:46:11

标签: python docx python-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行空格。

3 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

您可以放置​​条件的分页符空格。

步骤:

  1. 以Microsoft Word打开文档的形式打开文档
  2. 单击“主页”,然后单击(Ctrl + *)或引用符号
  3. 您将找到所有分页符和屏幕截图之类的空格
  4. 然后添加条件语句,例如在屏幕截图中显示enter image description here

答案 2 :(得分:0)

我已经找到了可以在模板docx上手动添加分页符的解决方案,而不是从代码及其工作中确定