代碼和實現效果
from docx import Document
from docx.oxml import OxmlElement
from docx.oxml.ns import qn
from docx.shared import Pt# 調整pt設置字間距
def SetParagraphCharSpaceByPt(run, pt=1):'''通過修改word源碼方式, 添加w:spacing標簽直接通過調整pt來設置字符間距'''# 獲取或創建<w:rPr>元素rPr = run._element.find(qn('w:rPr'))if rPr is None:rPr = OxmlElement('w:rPr')run._element.insert(0, rPr)# 創建<w:spacing>元素spaceChar = OxmlElement('w:spacing')spaceChar.set(qn('w:val'), str(pt * 20))# 添加<w:spacing>到<w:rPr>rPr.append(spaceChar)def AddParagraph(doc, text):p = doc.add_paragraph()run = p.add_run(text)return p, rundoc = Document()
p, run = AddParagraph(doc, text='這是一個段落')
SetParagraphCharSpaceByPt(run=run, pt=3)
doc.save('test.docx')
原理和代碼思路
通過解壓
的方式打開一個已經提前設置好字符間距的word文檔,在word/document.xml
可以看到具體關于字符間距設置的XML
標簽代碼
<w:p><w:r><w:rPr><w:rFonts w:ascii="黑體" w:hAnsi="黑體" w:eastAsia="黑體"/><w:b w:val="0"/><w:i w:val="0"/><w:sz w:val="32"/><w:spacing w:val="150.0"/></w:rPr><w:t>這是一個段落</w:t></w:r>
</w:p>
<w:p>
表示word:paragraph
;<w:r>
表示word:run
;<w:t>
表示word:text
,定義段落的文本內容;<w:rPr>
表示word:runProperty
,而在<w:rPr>
標簽下的是各類屬性標簽,其中<w:spacing>
為字符間距,這是需要coding為我們自定義的標簽。而上述示例Python代碼也在對這個標簽進行創建并賦值;<w:spacing>
標簽中的屬性w:val
代表字符間距大小,其值等于pt(磅) * 20