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')

你可能感兴趣的:(python,python-docx,python,开发语言)