Reputation: 795
I created a docx template and then generated the python code to update variable and all the other data into this template using python's docxtpl
package as:
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
I don't understand how can I fully control the spaces/ page break in the resulting docx file. If I put some text in the template in the beginning of the page it sometimes moves and adds x line spaces.
Upvotes: 2
Views: 5528
Reputation: 344
You can insert a page break from the jinja2 code using a variable and displaying it the docx template.
Python code :
from docxtpl import DocxTemplate
docxFields = {}
docxFields["pageBreak"] = "\f"
doc = DocxTemplate("myTemplate.docx")
doc.render(docxFields)
doc.save("myResult.docx")
Docx template edited in MSWord :
{%- for key in xxx %}{{ pageBreak }}
xxxx
{% endfor %}
Source https://docxtpl.readthedocs.io/en/stable/ (see Display Variables)
Upvotes: 0
Reputation: 31
Easy method is add a page break in a row of template table. Insert Page break from word.
\f was not really working for me. Tried multiple \f in multiple rows. All it was doing was adding more and more blank rows. In my case I have multiple tables so the table alignment was a mess. Inserting page break in the template document table fixed my problem
Upvotes: 0
Reputation: 81
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')
and using {{r page_break}} in your template
see this https://github.com/elapouya/python-docx-template/blob/master/tests/escape.py
and this https://github.com/elapouya/python-docx-template/blob/master/tests/templates/escape_tpl.docx
Upvotes: 4
Reputation: 795
I already found the solution you can add page break manually at the template docx not from the code and its work OK
Upvotes: 0
Reputation: 9301
You can put conditional page break of space.
Step to do :
Upvotes: 0