Python-docx中设置页面宽度与高度的正确方法

在使用python-docx库修改word文档页面尺寸时,常见错误是将page_width和page_height误当作可调用方法使用,实际它们是可赋值的属性,应直接赋值inches()对象而非调用。

当你通过 doc.sections[0] 获取文档默认节对象后,section.page_width 和 section.page_height 是 Length 类型的属性(property),而非函数。因此以下写法是错误的:

section.page_width(Inches(5))  # ❌ 错误:'Twips' object is not callable
section.page_height(Inches(5)) # ❌ 同样触发 TypeError

这会导致 Python 尝试调用一个 Twips 实例(Inches(5) 内部转换为 Twips 单位),而 Twips 类未实现 __call__ 方法,从而抛出 'Twips' object is not callable 异常。

✅ 正确做法是直接赋值

from docx import Document
from docx.shared import Inches

doc = Document()
section = doc.sections[0]

# ✅ 正确:直接赋值 Length 对象
section.page_width = Inches(5)
section.page_height = Inches(5)

# 可选:同时设置页边距(单位同理)
section.left_margin = Inches(0.75)
section.right_margin = Inches(0.75)
section.top_margin = Inches(1.0)
section.bottom_margin = Inches(1.0)

doc.save("custom_size.docx")

⚠️ 注意事项:

  • Inches()、Cm()、Pt() 等单位构造器返回的是 Length 子类实例(如 Twips),专用于 docx 属性赋值,不可调用
  • 所有页面布局相关属性(如 page_width、page_height、left_margin 等)均为可读写属性,不带括号;
  • 若需添加新节(如分栏、不同页眉页脚),可用 doc.add_section(),但新节的尺寸仍需通过属性赋值方式设置;
  • 修改尺寸后务必调用 doc.save() 才能持久化到文件。

? 小技巧:可通过 print(section.page_width.inches) 验证设置是否生效,输出应为 5.0。

掌握这一基本规则,可避免绝大多数与 Twips、Emu、Pt 等单位对象相关的调用错误,让文

档自动化更稳健可靠。