You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过python-docx添加可自定义样式的矩形形状?

在python-docx中添加自定义样式矩形形状的解决方案

python-docx的高级API并未直接提供创建形状的功能,想要添加自定义样式的矩形,需要通过操作底层的Open XML来实现。以下是可直接复用的代码示例,支持调整矩形的尺寸、线条粗细、填充色和线条颜色:

from docx import Document
from docx.oxml.ns import qn
from docx.oxml.shared import OxmlElement, Emu
from docx.shared import Cm

def add_custom_rectangle(doc, width, height, line_width, fill_color, line_color):
    # 创建段落用于承载形状
    paragraph = doc.add_paragraph()
    run = paragraph.add_run()
    
    # 创建Drawing容器元素
    drawing = OxmlElement('w:drawing')
    inline = OxmlElement('wp:inline')
    
    # 设置形状整体尺寸
    extent = OxmlElement('wp:extent')
    extent.set(qn('cx'), str(width))
    extent.set(qn('cy'), str(height))
    inline.append(extent)
    
    # 构建图形结构
    graphic = OxmlElement('a:graphic')
    graphic_data = OxmlElement('a:graphicData')
    graphic_data.set(qn('uri'), 'http://schemas.openxmlformats.org/drawingml/2006/picture')
    
    # 创建矩形形状
    shape = OxmlElement('a:sp')
    shape.set(qn('bwMode'), 'auto')
    
    # 指定矩形几何形状
    prst_geom = OxmlElement('a:prstGeom')
    prst_geom.set(qn('prst'), 'rect')
    prst_geom.append(OxmlElement('a:avLst'))
    shape.append(prst_geom)
    
    # 设置纯色填充
    solid_fill = OxmlElement('a:solidFill')
    srgb_fill = OxmlElement('a:srgbClr')
    srgb_fill.set(qn('val'), fill_color.lstrip('#'))
    solid_fill.append(srgb_fill)
    shape.append(solid_fill)
    
    # 设置线条样式
    ln = OxmlElement('a:ln')
    ln.set(qn('w'), str(line_width))
    ln_solid_fill = OxmlElement('a:solidFill')
    ln_srgb = OxmlElement('a:srgbClr')
    ln_srgb.set(qn('val'), line_color.lstrip('#'))
    ln_solid_fill.append(ln_srgb)
    ln.append(ln_solid_fill)
    shape.append(ln)
    
    # 组装所有元素并加入段落
    graphic_data.append(shape)
    graphic.append(graphic_data)
    inline.append(graphic)
    drawing.append(inline)
    run._r.append(drawing)

# 示例调用
if __name__ == '__main__':
    doc = Document()
    
    # 自定义参数:尺寸用Cm类简化输入,线条粗细用Emu对应磅值(1磅=12700 Emu)
    rect_width = Cm(5)
    rect_height = Cm(2.5)
    line_thickness = Emu(3*12700) # 3磅粗细
    fill_hex = '#F0F8FF'
    line_hex = '#4169E1'
    
    add_custom_rectangle(doc, rect_width, rect_height, line_thickness, fill_hex, line_hex)
    
    doc.save('custom_rect.docx')

参数调整说明

  • 尺寸:直接用Cm()、Inches()或Pt()类输入直观单位,无需手动转换Emu
  • 颜色:输入标准十六进制颜色码,带不带#都可
  • 线条粗细:用Emu()转换磅值,比如Emu(2*12700)对应2磅线条

内容的提问来源于stack exchange,提问作者H H

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.15 00:10:17