>>> 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)
节属性
"节"对象具有 11 个属性,允许发现和指定页面布局设置。
节开始类型1个属性
节.start_type描述节前面的中断类型:
>>> section.start_type
NEW_PAGE (2)
>>> section.start_type = WD_SECTION.ODD_PAGE
>>> section.start_type
ODD_PAGE (4)
的值是WD_SECTION_START枚举的成员。start_type
页面尺寸和方向3个属性
剖面上的三个属性描述页面尺寸和方向。例如,这些可以一起用于更改剖面的方向从纵向到横向:
>>> 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)
页面边距7个属性
剖面上的七个属性一起指定各种边缘间距,确定文本在页面上的显示位置:
>>> 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)