Matija Lukic
Matija Lukic

Reputation: 669

How to remove new line in Word header using python-docx when adding paragraph text?

I've successfully added text and image in a two-cells table in Word header.

section = document.sections[0]
header = section.header

htable = header.add_table(1, 2, Inches(6))

htab_cells = htable.rows[0].cells

ht0 = htab_cells[0]
ht1 = htab_cells[1]

ht0.paragraphs[0].text = 'Test project'
run = ht1.paragraphs[0].add_run()
run.add_picture('app/static/images/logo.png', width=Inches(1))
ht1.paragraphs[0].alignment = WD_ALIGN_PARAGRAPH.RIGHT

enter image description here

But, the problem is that python-docx put my text in the left column in the new line?

How to get rid of this first added paragraph line?

Upvotes: 2

Views: 2506

Answers (1)

scanny
scanny

Reputation: 28903

A blank (newly-created) section contains an empty paragraph. This kind of Word thing (called a "story") must always contain at least one paragraph, otherwise it is invalid and will trigger a repair error on loading.

So the question is how to avoid having the table appear after that paragraph.

The first answer, and the one I like best, is to avoid using a table at all. You appear to be using it only for alignment, and using tabs does a better job of that for multiple reasons, one of which is it avoids small misalignments due to table internal cell margin.

This process is described in the documentation here:
https://python-docx.readthedocs.io/en/latest/user/hdrftr.html#adding-zoned-header-content

Essentially, you add tab(s) to the single existing paragraph and use tab-characters to separate your logo from the title. If you use a right-aligned tab, the logo aligns nicely with the right margin.

from docx.enum.text import WD_TAB_ALIGNMENT

paragraph = section.paragraphs[0]
tab_stops = paragraph.paragraph_format.tab_stops
tab_stops.add_tab_stop(Inches(6.5), WD_TAB_ALIGNMENT.RIGHT)

paragraph.text = "My Header Title\t"  # ---note trailing tab char---
run = paragraph.add_run()
run.add_picture("my-logo")

If you really must use a table, you'll need to remove the empty paragraph before adding the table, then add it back in afterward:

paragraph = header.paragraphs[0]
p = paragraph._p  # ---this is the paragraph XML element---
p.getparent().remove(p)
header.add_table(...)
...
header.add_paragraph()

Upvotes: 2

Related Questions