【问题标题】:How to add a page border with python-docx如何使用 python-docx 添加页面边框
【发布时间】:2020-04-03 06:04:49
【问题描述】:

我想使用 python-docx 为我的 MS Word 文档添加页面边框。我该怎么办?

我查看了section 的文档,但没有找到任何相关信息。

【问题讨论】:

    标签: python python-3.x python-docx


    【解决方案1】:

    官方python-docx库还不支持,但是可以自己实现。您正在寻找存储在section properties 下的page borders

    这里有一些可以帮助你的代码示例:

    import docx
    from docx.oxml.xmlchemy import OxmlElement
    from docx.oxml.shared import qn
    
    doc = docx.Document()
    sec_pr = doc.sections[0]._sectPr # get the section properties el
    # create new borders el
    pg_borders = OxmlElement('w:pgBorders')
    # specifies how the relative positioning of the borders should be calculated
    pg_borders.set(qn('w:offsetFrom'), 'page')
    for border_name in ('top', 'left', 'bottom', 'right',): # set all borders
        border_el = OxmlElement(f'w:{border_name}')
        border_el.set(qn('w:val'), 'single') # a single line
        border_el.set(qn('w:sz'), '4') # for meaning of  remaining attrs please look docs
        border_el.set(qn('w:space'), '24')
        border_el.set(qn('w:color'), 'auto')
        pg_borders.append(border_el) # register single border to border el
    sec_pr.append(pg_borders) # apply border changes to section
    
    doc.save('border_test.docx')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-09-14
      • 1970-01-01
      • 2020-08-18
      • 1970-01-01
      • 1970-01-01
      • 2022-11-11
      • 1970-01-01
      • 2014-10-19
      相关资源
      最近更新 更多