如何在python-docx中减少段落之间的空间



我试图用下面的代码减少段落之间的间距python-docx但是当将格式应用于段落时,最后一段会缩小,但段落之间的线条不会减少。

我在这里找到了一些示例链接 1 和链接 2,但不了解实现预期结果的xml部分。

我需要您的帮助,通过python减少段落之间的间距,但不通过word文件进行设置。

from docx import Document
from docx.shared import Inches
from docx.enum.style import WD_STYLE_TYPE
from docx.shared import Pt

document = Document()
document.add_heading('THIS IS MY HEADER WANT TO UNDERLINE IT')

paragraph = document.add_paragraph('THIS IS MY FIRST PARAGRAPH ')
paragraph = document.add_paragraph('THIS IS SECOND PARAGRAPH')
paragraph = document.add_paragraph('SPACING BETWEEN EACH SHOULD BE DECREASED')
paragraph_format = paragraph.paragraph_format
paragraph_format.line_spacing = Pt(3)
paragraph_format.space_after = Pt(5)

print("document created")
document.save('demo.docx')

如果您检查生成的 Word 文件,您可以看到您的代码完全按照您所说的方式工作。最后一段 -您应用格式的唯一段落- 行距为 3pt,之后有 5 磅的空格;所有其他段落都以默认格式显示。

所以python-docx工作正常,如果你的输出是错误的,那是因为你的代码是错误的。

首先,我强烈建议不要将行距设置为 3 pt;我假设你感到困惑,因为它"不起作用",你打算设置space_before。其次,确保将格式应用于所有段落,而不仅仅是最后一个段落:

from docx import Document
from docx.shared import Pt
document = Document()
document.add_heading('THIS IS MY HEADER WANT TO UNDERLINE IT')
paragraph = document.add_paragraph('THIS IS MY FIRST PARAGRAPH ')
paragraph.paragraph_format.space_before = Pt(3)
paragraph.paragraph_format.space_after = Pt(5)
paragraph = document.add_paragraph('THIS IS SECOND PARAGRAPH')
paragraph.paragraph_format.space_before = Pt(3)
paragraph.paragraph_format.space_after = Pt(5)
paragraph = document.add_paragraph('SPACING BETWEEN EACH SHOULD BE DECREASED')
paragraph.paragraph_format.space_before = Pt(3)
# no need to set space_after because there is no text after this
print("document created")
document.save('demo.docx')

这会导致文档在所有三个文本段落之前和之后有 5 磅的额外空间(并且具有常规的行距(。

最新更新