Python-docx:添加形状(矩形)

问题描述 投票:0回答:1

我需要一些帮助,我想在我的 python-docx 文件中添加一个如图所示的形状 [我想要的形状示例 --> https://i.stack.imgur.com/k96I2.png),但找不到解决方案。它是一个简单的矩形,但需要通过颜色、高度和宽度以及线条和填充的粗细进行操作。

我尝试使用 ChatGTP 使用一堆不同的代码,但没有成功。

python shapes python-docx
1个回答
0
投票

python-docx 库主要是为文本操作而设计的;然而,它还提供了实现表格边框的能力,作为添加边框的有效解决方法,如图所示。

这是完整的演示:

    from docx import Document
    from docx.shared import Pt
    from docx.enum.text import WD_PARAGRAPH_ALIGNMENT
    from docx.oxml import OxmlElement
    from docx.oxml.ns import qn
    
    doc = Document()
    
    table = doc.add_table(rows=1, cols=1)
    
    table.autofit = False
    table.columns[0].width = Pt(442)
    table.rows[0].height = Pt(500) 
    
    cell = table.cell(0, 0)
    tc_pr = cell._element.get_or_add_tcPr()
    borders = OxmlElement('w:tcBorders')
    tc_pr.append(borders)
    
    for border_type in ['top', 'left', 'bottom', 'right']:
        border_elm = OxmlElement(f'w:{border_type}')
        border_elm.set(qn('w:val'), 'single')
        border_elm.set(qn('w:sz'), '24')
        border_elm.set(qn('w:space'), '0')
        border_elm.set(qn('w:color'), 'FF0000')
        borders.append(border_elm)
    
    paragraph = table.cell(0, 0).add_paragraph()
    run = paragraph.add_run('Hello, World!')
    
    paragraph.alignment = WD_PARAGRAPH_ALIGNMENT.CENTER
    
    for _ in range(5):
        doc.add_paragraph()
    
    doc.save('hello_world.docx')

在这里您可以调整宽度和高度:

    table.columns[0].width = Pt(442)
    table.rows[0].height = Pt(500)

您可以通过更改“w:sz”属性的值来调整边框的粗细。该属性指的是边框的大小。在 DOCX 的 XML 中,大小以八分之一点给出。因此,如果您想要 4 点边框,则可以使用“32”(因为 4*8 = 32)。

我已经在 libre-office 中对此进行了测试,因此我根据它进行了调整,在 Microsoft Word 中您可能需要进行额外的调整。另外我在底部添加了 5 个空段落,您可以根据需要删除或调整它们。

© www.soinside.com 2019 - 2024. All rights reserved.