python-docx官⽅⽂档翻译--⽤户指南05--处理节(section)
处理节(section)
Word ⽀持 节(section)的概念,即具有相同页⾯布局设置(例如页边距和页⾯⽅向)的⽂档的划分。例如,⽂档可以包含纵向布局的某些页⾯和横向布局的其他页⾯。
⼤多数 Word ⽂档默认只有⼀个节(section),⽽且,⼤多数⽂档没有理由更改默认边距或其他页⾯布局。但是,当您确实需要更改页⾯布局时,您需要了解节(section)以完成此操作。
访问节(section)
通过 对象上的 属性提供对⽂档节(section)的访问:
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>python官方文档中文版
for section in sections:
print(section.start_type)
# NEW_PAGE (2)
# EVEN_PAGE (3)
# ODD_PAGE (4)
# 实际上好像只有⼀个
从理论上讲,⽂档中可能没有明确的 section,尽管我还没有看到这种情况。如果您访问的是⽆法预测的 .docx ⽂件,则可能需要使⽤
len() 检查或 try 执⾏块操作来避免这种情况,以避免未捕获的 IndexError 异常停⽌程序。
添加新节(section)
Document.add_section() ⽅法允许在⽂档末尾开始新的 section。调⽤此⽅法后添加的段落和表格将出现在新 section 中:
current_section = document.sections[-1]# ⽂档的最后⼀个 section
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 开始类型
描述了该 section 之前的中断类型:
section.start_type
# NEW_PAGE (2)
section.start_type = WD_SECTION.ODD_PAGE
section.start_type
# ODD_PAGE (4)
start_type 的值是 枚举的成员。
页⾯尺⼨和⽅向
中的三个属性描述了页⾯尺⼨和⽅向。这些可以⼀起使⽤,例如,将 section 的⽅向从纵向更改为横向:
# (PORTRAIT (0), 7772400, 10058400)
# (Inches(8.5), Inches(11))
new_width, new_height = section.page_height, section.page_width
section.page_width = new_width
section.page_height = new_height
# (LANDSCAPE (1), 10058400, 7772400)
页边距
上的七个属性⼀起指定了各种边缘间距,这些间距确定了⽂本在页⾯上的显⽰位置:
from docx.shared import Inches
section.left_margin, section.right_margin
# (1143000, 1143000)
# (Inches(1.25), Inches(1.25))
# (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)
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论