Python-docx设置纸张方向为横向

此篇博客将从两个方面讲清楚如何使用Python-docx库将docx文档设置为横向

第一种,设置当前页面方向为横线
from docx import Document
from docx.enum.section import WD_ORIENT
#这里能够获取到当前的章节,也就是第一个章节
section = document.sections[0]
#需要同时设置width,height才能成功
new_width, new_height = section.page_height, section.page_width
section.orientation = WD_ORIENT.LANDSCAPE
section.page_width = new_width 
section.page_height = new_height
#保存docx文件
document.save('test3.docx')
第二种,设置所有章节的页面方向均为横向
from docx import Document
from docx.enum.section import WD_ORIENT
#获取本文档中的所有章节
sections = document.sections
#将该章节中的纸张方向设置为横向
for section in sections:
    #需要同时设置width,height才能成功
    new_width, new_height = section.page_height, section.page_width
    section.orientation = WD_ORIENT.LANDSCAPE
    section.page_width = new_width 
    section.page_height = new_height
document.save('test2.docx')
第三种,分别设置为每一章节的纸张方向,处理结果为:第一章节为纵向,第二章节为横向,第三章节为纵向
from docx import Document
from docx.enum.section import WD_ORIENTATION, WD_SECTION_START # 导入节方向和分节符类型
document = Document() # 新建docx文档
document.add_paragraph() # 添加一个空白段落
section = document.add_section(start_type=WD_SECTION_START.CONTINUOUS) # 添加横向页的连续节
section.orientation = WD_ORIENTATION.LANDSCAPE # 设置横向
page_h, page_w = section.page_width, section.page_height
section.page_width = page_w # 设置横向纸的宽度
section.page_height = page_h # 设置横向纸的高度
document.add_paragraph() # 添加第二个空白段落
section = document.add_section(start_type=WD_SECTION_START.CONTINUOUS) # 添加连续的节
section.orientation = WD_ORIENTATION.PORTRAIT # 设置纵向
page_h, page_w = section.page_width, section.page_height # 读取插入节的高和宽
section.page_width = page_w # 设置纵向纸的宽度
section.page_height = page_h # 设置纵向纸的高度
document.save('test.docx')
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值