Reputation: 627
I have problem with \n
and \t
tags. When I am opening a generated .docx
in OpenOffice everything looks fine, but when I open the same document in Microsoft Word I just get the last two tabulators in section "Surname"
and spaces instead of newlines/tabulators in other sections. What is wrong?
p = document.add_paragraph('Simple paragraph')
p.add_run('Name:\t\t' + name).bold = True
p.add_run('\n\nSurname:\t\t' + surname)
Upvotes: 1
Views: 2121
Reputation: 131
For my invoicing application, I made it work like this:
p = document.add_paragraph()
tab_count = 2
invoice_nr = '2024-5'
run = p.add_run()
run.add_text(f'Invoice nr.')
run.add_text(f'\t'*tab_count)
run.add_text(invoice_nr)
If the \t is fed on a new line, it works as expected. Depending on the number of tabs that needs to be added, a tab_count variable was pre-determined and added.
Upvotes: 0
Reputation: 28903
In Word, what we often think of as a line feed translates to a paragraph object. If you want empty paragraphs in your document you will need to insert them explicitly.
First of all though, you should ask whether you're using paragraphs for formatting, a common casual practice for Word users but one you might want to deal with differently, in particular by using the space-before and/or space-after properties of a paragraph. In HTML this would correspond roughly to padding-top and padding-bottom.
In this case, if you just want the line feeds, consider using paragraphs like so:
document.add_paragraph('Simple paragraph')
p = document.add_paragraph()
p.add_run('Name:\t\t').bold = True
p.add_run(name)
document.add_paragraph()
p = document.add_paragraph()
p.add_run('Surname:\t\t').bold = True
p.add_run(surname)
Upvotes: 3