Word页面排版

Python
from docx import Document
from docx.shared import Inches
from docx.enum.section import WD_ORIENT

# 加载文档
document=Document('测试.docx')

# 加载sections类
sections = document.sections
section = sections[0]

# 设置上边距、左右边距为0.5英寸
section.left_margin = Inches(0.5)
section.top_margin = Inches(0.5)
section.right_margin = Inches(0.5)


# 设置纸张格式
section.page_width = Inches(0.5)
section.page_height = Inches(0.5)

# 设置纸张方向
# section.orientation = WD_ORIENT.LANDSCAPE # 改为横向
# section.orientation = WD_ORIENT.PORTRAIT # 改为纵向
"""好像不管用,不知道是咋回事"""

# 保存文档
document.save('测试2.docx')

如果要使用厘米作为单位的话,可以这样写:

Python
from docx.shared import Pt, Cm
sections.left_margin = Cm(1.5) # 设置左边距为1.5厘米

如果要给某一段内容设置背景填充的话,可以这样写:

Python
# 引用部分略过
text="测试文字"
para = doc.add_paragraph(text)
para.paragraph_format.line_spacing = Pt(20)
para.paragraph_format.space_after = Pt(0)
for run in para.runs:
    run.font.size = Pt(12)
    run.font.name = '宋体'
    r = run._element.rPr.rFonts
    r.set(qn('w:eastAsia'), '宋体')
    tag = run._r
    shd = OxmlElement('w:shd')
    shd.set(qn('w:val'), 'clear')
    shd.set(qn('w:color'), 'auto')
    shd.set(qn('w:fill'), 'fff5ce')
    tag.rPr.append(shd)

Note

对照英文的python-docx帮助文档,总算找到了可以进行页面设置的地方了

不过本人暂时不太清楚具体每行代码是什么意思,尤其是为什么需要加载sections类,不过目前我知道的是边距方法是在sections类中,看官方文档有些不知所云,之后再慢慢研究吧