python-openxml / python-docx

Create and modify Word documents with Python
MIT License
4.63k stars 1.13k forks source link

Page background-color #1293

Open SystemError7 opened 1 year ago

SystemError7 commented 1 year ago

Is there any attribute in Sections or in python-docx to set the background-color of the pages of the document??

dark-tonebone commented 10 months ago

While this is not an attribute of Section or Document, there is a way to do this. I found a post from Ashish Dudeja on Medium (from Aug 18, 2021) with a solution. It worked for me in Python 3.8.10. Below is the implementation into my code (simplified for clarity). The inline comments are how I understand it to work, but I'm not sure about them.

from docx import Document
from docx.oxml.shared import OxmlElement
from docx.oxml.ns import qn
document = Document()
background = OxmlElement('w:background')
background.set(qn('w:color'), '0D0D0D')     # Define black background
document.element.insert(0, background)      # Insert it
background_shp = OxmlElement('w:displayBackgroundShape') # Setting to use my background
document.settings.element.insert(0, background_shp)      # Apply setting
document.save('test.docx')