使用节
Word
支持节
的概念,节是有相同页布局设置
(如页边距和页方向
)的文档划分.因此文档可包含纵向
布局的某些页
和横向
布局的其他页
.
大多数Word
文档只有默认
提供的单个节
,此外,多数文档不必更改默认边距或其他页布局
.但是,确实需要更改页布局
时,也可完成它.
访问节
由Document
对象上的sections
属性访问
文档节:
document = Document()
sections = document.sections
sections
<docx.parts.document.Sections object at 0x1deadbeef>
len(sections)
3
section = sections[0]
section
<docx.section.Section object at 0x1deadbeef>
for section in sections:
... print(section.start_type)
...
NEW_PAGE (2)
EVEN_PAGE (3)
ODD_PAGE (4)
添加新节
Document.add_section()
方法允许在文档
末尾开始新节
.调用此方法后,在新节
中显示添加的段落和表格
:
current_section = document.sections[-1] # last section in document
current_section.start_type
NEW_PAGE (2)
new_section = document.add_section(WD_SECTION.ODD_PAGE)
new_section.start_type
ODD_PAGE (4)
节属性
Section
对象有11
个属性,来指定页布局
设置.
节开始类型
Section.start_type
描述了前面所说的中断类型
:
section.start_type
NEW_PAGE (2)
section.start_type = WD_SECTION.ODD_PAGE
section.start_type
ODD_PAGE (4)
start_type
的值是WD_SECTION_START
枚举的成员.
页尺寸和方向
如下从纵向
更改截面
方向为横向
:
section.orientation, section.page_width, section.page_height
(PORTRAIT (0), 7772400, 10058400) # (Inches(8.5), Inches(11))
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
section.orientation, section.page_width, section.page_height
(LANDSCAPE (1), 10058400, 7772400)
页边距
Section
上的七个
属性共同指定
文本在页
上显示位置的各种边距
:
from docx.shared import Inches
section.left_margin, section.right_margin
(1143000, 1143000) # (Inches(1.25), Inches(1.25))
section.top_margin, section.bottom_margin
(914400, 914400) # (Inches(1), Inches(1))
section.gutter
0
section.header_distance, section.footer_distance
(457200, 457200) # (Inches(0.5), Inches(0.5))
section.left_margin = Inches(1.5)
section.right_margin = Inches(1)
section.left_margin, section.right_margin
(1371600, 914400)