-1

I created a word document using python and docx module. I want some method to change the background color of the whole document, but I can't find any. Any ideas?

from docx import Document
document = Document()
Diggy.
  • 6,744
  • 3
  • 19
  • 38

2 Answers2

0

Use this approach.

  • First create two Word files. One with the formatting you like, one completely empty. Save them.

  • Extract the docx files using some unzip tool.

  • Open the files settings.xml and document.xml and compare the files from the two docx files using a diff tool, e.g. Winmerge or Meld

  • Look for <w:background w:color="004586"/> in document.xml

  • Look for <w:displayBackgroundShape/> in settings.xml

Now try to set the fields using the method mentioned above.

If that does not work you can follow the approach described here for LibreOffice files (open as XML, modify or add nodes, save, zip).

Joe
  • 6,758
  • 2
  • 26
  • 47
0

Detailed explanation of the approach by Joe and Post Referenced using python-docx.

import docx
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
doc = docx.Document()
doc.add_paragraph().add_run("Sample Text")

# Now Add below children to root xml tree
# create xml element using OxmlElement
shd = OxmlElement('w:background')
# Add attributes to the xml element
shd.set(qn('w:color'), '0D0D0D') #black color
shd.set(qn('w:themeColor'), 'text1')
shd.set(qn('w:themeTint'), 'F2')

# Add background element at the start of Document.xml using below
doc.element.insert(0,shd)

# Add displayBackgroundShape element to setting.xml
shd1 = OxmlElement('w:displayBackgroundShape')
doc.settings.element.insert(0,shd1)

# Save to file
doc.save('sample.docx')