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

在使用 python-docx 修改 word 文档页面尺寸时,`page_width` 和 `page_height` 是可读写属性(而非方法),错误地将其当作函数调用(如 `section.page_width(...)`)会导致 `'twips' object is not callable` 异常。

python-docx 库中,Section 对象的 page_width 和 page_height 属性属于 Length 类型(底层为 Twips 单位封装),它们是属性(property),不是可调用的方法。因此,必须使用赋值语法(=)进行设置,而非函数调用语法(())。

✅ 正确写法如下:

from docx import Document
from docx.shared import Inches

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

# ✅ 正确:直接赋值(支持 Inches、Cm、Pt、Emu 等单位)
section.page_width = Inches(5)
section.page_height = Inches(5)

# 其他常用单位示例:
# section.page_width = Cm(12.7)      # 12.7 厘米
# section.page_width = Pt(432)        # 432 磅(约 6 英寸)
# section.page_width = Emu(914400)    # 1 英寸 = 914400 EMU(English Metric Units)

doc.save("custom_size.docx")

⚠️ 注意事项:

  • 不要写成 section.page_width(Inches(5)) 或 section.page_width = Inches(5)() —— 后者会尝试调用 Twips 实例,引发 TypeError: 'Twips' object is not callable;
  • 所有长度单位需通过 docx.shared 模块导入(如 Inches, Cm, Pt, Emu),不可直接传入浮点数或字符串;
  • 页面尺寸修改仅对当前 Section 生效;若文档含多个节(section

    ),需遍历 doc.sections 分别设置;
  • 设置后务必调用 doc.save(...) 才能持久化到文件。

? 小技巧:可通过 print(section.page_width.inches) 快速验证当前值(单位自动转换),便于调试。

总结:牢记 page_width / page_height 是属性而非方法——赋值即生效,调用即报错。这是 python-docx 中常见的“属性误用”陷阱,掌握这一原则,也能避免类似 left_margin、top_margin 等其他 Length 类型属性的误操作。