添加段落文本时如何使用 python-docx 删除 Word header 中的新行?

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

我已经在 Word header 中的 two-cells table 中成功添加了文本和图像。

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

但是,问题是 python-docx 将我的文本放在新行的左栏中?

如何去除第一个添加的段落行?

空白 (newly-created) 部分包含一个空段落。这种Word东西(叫一个"story")必须总是包含至少一个段落,否则无效,会在加载时触发修复错误。

所以问题是如何避免table出现在那段之后。

第一个答案,也是我最喜欢的一个,是完全避免使用 table。您似乎仅将其用于对齐,并且出于多种原因,使用制表符可以更好地完成此工作,其中之一是它避免了由于 table 内部单元格边距引起的小错位。

此过程在此处的文档中进行了描述:
https://python-docx.readthedocs.io/en/latest/user/hdrftr.html#adding-zoned-header-content

本质上,您将制表符添加到单个现有段落并使用 tab-characters 将徽标与标题分开。如果您使用 right-aligned 选项卡,则徽标与右边距很好地对齐。

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")

如果您真的必须使用table,您需要在添加table之前删除空段落,然后将其重新添加到之后:

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