3

I want to modify the color of the border, and I get its XML by calling style._element.xml:

>>> document = Document()
>>> run = document.add_heading(u'', 0).add_run('hello world')
>>> paragraphs = document.paragraphs
>>> print(paragraphs[0].style._element.xml)
<w:style xmlns:w="http://schemas.openxmlformats.org/wordprocessingml/2006/main" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" xmlns:w14="http://schemas.microsoft.com/office/word/2010/wordml" w:type="paragraph" w:styleId="Title">
  <w:name w:val="Title"/>
  <w:basedOn w:val="Normal"/>
  <w:next w:val="Normal"/>
  <w:link w:val="TitleChar"/>
  <w:uiPriority w:val="10"/>
  <w:qFormat/>
  <w:rsid w:val="00FC693F"/>
  <w:pPr>
    <w:pBdr>
      <w:bottom w:val="single" w:sz="8" w:space="4" w:color="4F81BD" w:themeColor="accent1"/>
    </w:pBdr>
    <w:spacing w:after="300" w:line="240" w:lineRule="auto"/>
    <w:contextualSpacing/>
  </w:pPr>
  <w:rPr>
    <w:rFonts w:asciiTheme="majorHAnsi" w:eastAsiaTheme="majorEastAsia" w:hAnsiTheme="majorHAnsi" w:cstheme="majorBidi"/>
    <w:color w:val="17365D" w:themeColor="text2" w:themeShade="BF"/>
    <w:spacing w:val="5"/>
    <w:kern w:val="28"/>
    <w:sz w:val="52"/>
    <w:szCs w:val="52"/>
  </w:rPr>
</w:style>


Now I want to change a color code in attribute border, how can I do it?

Si Zhang
  • 93
  • 7

1 Answers1

3

paragraph.style._element is an lxml.etree._Element object, so something like this should do the trick:

from docx.oxml.ns import qn

bottom = paragraph.style._element.xpath("./w:pPr/w:pBdr/w:bottom")[0]
bottom.set(qn("w:color"), "FF00FF")
scanny
  • 26,423
  • 5
  • 54
  • 80
  • It's really helpful. I have another problem. I have set the color to black and made it work in Linux but it showed to blue again in Windows. How can I deal with this problem? – Si Zhang Nov 05 '19 at 04:01
  • I notice a `w:themeColor` attribute also appears in that element and "accent1" is commonly a shade of blue. Try removing that attribute with `bottom.attrib.pop(qn("w:themeColor"))` and see if that does the trick. – scanny Nov 05 '19 at 04:13
  • But can we turn w:sym to w:t so it prints the unicode text of symbols instead of totally ignoring the symbols. – Cazforshort May 12 '21 at 12:37