python-docx官方文档翻译--用户指南05--处理节(section)

处理节(section)

Word 支持 节(section)的概念,即具有相同页面布局设置(例如页边距和页面方向)的文档的划分。例如,文档可以包含纵向布局的某些页面和横向布局的其他页面。
大多数 Word 文档默认只有一个节(section),而且,大多数文档没有理由更改默认边距或其他页面布局。但是,当您确实需要更改页面布局时,您需要了解节(section)以完成此操作。

访问节(section)

通过 Document 对象上的 sections 属性提供对文档节(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>
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 的属性

Section 对象具有11个属性,这些属性允许查看和指定页面布局设置。

section 开始类型

Section.start_type 描述了该 section 之前的中断类型:

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 中的三个属性描述了页面尺寸和方向。这些可以一起使用,例如,将 section 的方向从纵向更改为横向:

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)
  • 3
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值