[英]Change the page color of a word document using python
我使用 python 和 docx 模块创建了一个 word 文档。 我想要一些方法来更改整个文档的背景颜色,但我找不到任何方法。 有任何想法吗?
from docx import Document
document = Document()
使用这种方法。
首先创建两个Word文件。 一种具有您喜欢的格式,一种完全为空。 拯救他们。
使用一些解压缩工具提取 docx 文件。
打开文件settings.xml
和document.xml
并使用差异工具比较两个 docx 文件中的文件,例如 Winmerge 或 Meld
在document.xml
中查找<w:background w:color="004586"/>
settings.xml
中查找<w:displayBackgroundShape/>
现在尝试使用上述方法设置字段。
如果这不起作用,您可以按照此处描述的方法处理 LibreOffice 文件(以 XML 打开,修改或添加节点,保存,压缩)。
Joe和Post Referenced使用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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.