Python Word设置页面边距纸张大小教程
用python-docx设置Word页面纸张大小(A4/A3)、上下左右边距、横向纵向,批量调整多个文档的页面布局,适配打印和标准格式要求。
场景痛点
公司要求所有正式文档统一用A4纸、上下边距2.54厘米、左右边距3.17厘米。手里一堆文档有的边距不对,有的是A5纸,有的方向是横向,打印出来格式乱七八糟。手动打开每个文件进页面设置改,几十份文档点几十次。用python-docx可以批量设置纸张大小和边距,一键把所有文档调成统一格式。
用到的库
pip install python-docx
完整代码
# 导入库
from docx import Document
from docx.shared import Cm, Mm
from docx.enum.section import WD_ORIENT
import os
def set_page_layout(section,
page_width=21.0, page_height=29.7,
margin_top=2.54, margin_bottom=2.54,
margin_left=3.17, margin_right=3.17,
orientation='portrait'):
"""
设置单个节的页面布局
page_width/page_height: 纸张宽高,单位厘米
margin_*: 四边边距,单位厘米
orientation: portrait纵向 / landscape横向
"""
# 设置方向
if orientation == 'landscape':
section.orientation = WD_ORIENT.LANDSCAPE
# 横向时宽高互换
section.page_width = Cm(page_height)
section.page_height = Cm(page_width)
else:
section.orientation = WD_ORIENT.PORTRAIT
section.page_width = Cm(page_width)
section.page_height = Cm(page_height)
# 设置四边边距
section.top_margin = Cm(margin_top)
section.bottom_margin = Cm(margin_bottom)
section.left_margin = Cm(margin_left)
section.right_margin = Cm(margin_right)
# 页眉页脚距边界距离
section.header_distance = Cm(1.5)
section.footer_distance = Cm(1.75)
def set_a4_standard(input_path, output_path, orientation='portrait'):
"""按标准公文格式设置页面:A4纸,上下2.54cm,左右3.17cm"""
doc = Document(input_path)
# 文档可能有多个节,全部设置
for section in doc.sections:
set_page_layout(
section,
page_width=21.0, # A4宽21cm
page_height=29.7, # A4高29.7cm
margin_top=2.54,
margin_bottom=2.54,
margin_left=3.17,
margin_right=3.17,
orientation=orientation
)
doc.save(output_path)
print(f'页面设置完成:{output_path}')
def batch_set_page_layout(folder_path):
"""批量处理文件夹下所有docx"""
for filename in os.listdir(folder_path):
if filename.endswith('.docx') and not filename.startswith('~'):
input_path = os.path.join(folder_path, filename)
output_path = os.path.join(folder_path, 'A4排版_' + filename)
try:
set_a4_standard(input_path, output_path)
except Exception as e:
print(f'处理失败:{filename},错误:{e}')
if __name__ == '__main__':
# 单文件设置为标准A4纵向
set_a4_standard('demo.docx', 'A4排版_demo.docx')
# 设置为横向A4(适合宽表格)
# set_a4_standard('宽表格.docx', '横向_宽表格.docx', orientation='landscape')
# 批量处理文件夹(取消注释)
# batch_set_page_layout('./word_files')
代码讲解
- 页面设置在
doc.sections的每个section里,一个文档可能有多个节,遍历所有节才能确保全文统一。 section.page_width和section.page_height设置纸张大小,A4纸宽21厘米高29.7厘米,用Cm()转换单位。section.top_margin等四个属性设置上下左右边距,单位都是厘米。Word默认普通边距就是上下2.54厘米左右3.17厘米,直接按这个数值设。WD_ORIENT.LANDSCAPE是横向,设置横向时要把宽高互换,否则方向不对。纵向用WD_ORIENT.PORTRAIT。header_distance和footer_distance控制页眉页脚距离纸张边缘的距离,默认1.5厘米和1.75厘米,按标准公文格式设置。
运行结果
运行脚本后生成A4排版_demo.docx,打开后在Word里点"布局→纸张大小"可以看到是A4纸,"页边距"显示上下2.54厘米左右3.17厘米,和标准Word默认边距一致。批量处理文件夹时,每个文件旁边生成A4排版_xxx.docx。
注意事项
- 纸张大小除了A4,常用的还有A3(29.7×42厘米)、B5(18.2×25.7厘米)、16开(18.4×26厘米),改对应的宽高数值即可。
- 设置横向时一定要同时把宽高互换,否则虽然orientation设成横向,但宽高还是A4纵向的数值,Word里显示会不对。
- 文档里如果有分节符,每个节的页面设置是独立的,必须遍历所有section,只改第一个节会导致后半部分文档边距不对。
- 页眉页脚距离如果设得太小,可能和正文内容重叠,建议保持默认1.5厘米以上。

更新时间:2026-09-14 21:45:22