2309docx04节

使用节

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)

猜你喜欢

转载自blog.csdn.net/fqbqrr/article/details/132686931
今日推荐