python-docx 添加横线

python-docx add horizontal line

是否可以在段落后添加一条横跨整个页面宽度的水平线?

通过使用 add_header 在 header:

之后创建这样一行
  document.add_heading('Test', 0)

我需要在文档中的两个段落之间添加这样一行,是否可以单独添加该行?

python-docx API 尚不直接支持。

但是,您可以通过在您打开以创建新文档的 "template" 文档中创建具有此边框设置的段落样式来实现此效果,例如

document = Document('template-with-style.docx')

然后您可以使用 python-docx 将该样式应用于该文档中的新段落。

只需添加

document.add_paragraph("_____________________________________________")

这行的长度可能不够,但你可以添加它,我希望你已经解决了你的问题这是给新手的

这可以通过 python-docx API 使用低级函数实现。这是取自 a GitHub comment

from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn

def insertHR(paragraph):
    p = paragraph._p  # p is the <w:p> XML element
    pPr = p.get_or_add_pPr()
    pBdr = OxmlElement('w:pBdr')
    pPr.insert_element_before(pBdr,
        'w:shd', 'w:tabs', 'w:suppressAutoHyphens', 'w:kinsoku', 'w:wordWrap',
        'w:overflowPunct', 'w:topLinePunct', 'w:autoSpaceDE', 'w:autoSpaceDN',
        'w:bidi', 'w:adjustRightInd', 'w:snapToGrid', 'w:spacing', 'w:ind',
        'w:contextualSpacing', 'w:mirrorIndents', 'w:suppressOverlap', 'w:jc',
        'w:textDirection', 'w:textAlignment', 'w:textboxTightWrap',
        'w:outlineLvl', 'w:divId', 'w:cnfStyle', 'w:rPr', 'w:sectPr',
        'w:pPrChange'
    )
    bottom = OxmlElement('w:bottom')
    bottom.set(qn('w:val'), 'single')
    bottom.set(qn('w:sz'), '6')
    bottom.set(qn('w:space'), '1')
    bottom.set(qn('w:color'), 'auto')
    pBdr.append(bottom)

这将为段落添加水平线。