【python-docx 04】對章節操作

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)

從理論上講,文檔可能沒有任何明確的部分。但是如果正在訪問不可預測的.docx文件,你可能希望使用len()檢查或try方法來避免IndexError異常意外停止程序。

添加新章節

Document.add_section()方法允許在文檔末尾開始新的部分。
調用此方法後添加的段落和表格將顯示在新部分中:

from  docx.enum.section import WD_SECTION_START
current_section = document.sections[-1]  # 文檔最後一個章節
new_section = document.add_section(WD_SECTION_START.ODD_PAGE)

章節屬性

Section對象有11個屬性,允許找到和指定頁面佈局設置。

章節開始類型

Section.start_type描述了該章節與之前的中斷類型,start_type的值是WD_SECTION_START中的的方法:

>>> from  docx.enum.section import WD_SECTION_START
>>> section.start_type
NEW_PAGE (2)
>>> section.start_type = WD_SECTION_START.ODD_PAGE
>>> section.start_type
ODD_PAGE (4)
頁面尺寸和方向

Section有三個屬性描述頁面尺寸和方向。
例如,這些可以用於將章節的方向從縱向更改爲橫向:

from  docx.enum.section import WD_ORIENTATION

print(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_ORIENTATION.LANDSCAPE
section.page_width = new_width
section.page_height = new_height
print(section.orientation, section.page_width, section.page_height)
# (LANDSCAPE (1), 10058400, 7772400)
頁邊距

Section有七個屬性一起指定了確定文本在頁面上出現位置的各種邊距:

from docx.shared import Inches

print(section.left_margin, section.right_margin)
#(1143000, 1143000)  # (Inches(1.25), Inches(1.25))
print(section.top_margin, section.bottom_margin)
# (914400, 914400)  # (Inches(1), Inches(1))
print(section.gutter)
# 0
print(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)
print(section.left_margin, section.right_margin)
# (1371600, 914400)
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章