使用部分

有时您希望文档的所有页面都具有不同的格式。例如,您可能需要修改页码格式、具有不同的页面大小和方向,或者将文档首页作为封面而不进行任何编号。您可以通过部分来实现这一点。

节是控制页眉和页脚、方向、列、边距、页码格式等的级别节点。

Aspose.Words 允许您管理部分、将文档划分为多个部分以及进行仅适用于特定部分的格式更改。 Aspose.Words 存储有关节格式的信息,例如页眉和页脚、页面设置以及分节符中的列设置。

本文介绍如何使用节和分节符。

什么是节和分节符

文档部分由 SectionSectionCollection 类表示。节对象是 Document 节点的直接子级,可以通过 Sections 属性进行访问。您可以使用 RemoveAddIndexOf 等一些方法来管理这些节点。

分节符是一个选项,可将文档页面分为具有可自定义布局的部分。

分节符的类型

Aspose.Words 允许您使用 BreakType 枚举的不同分节符来分割和格式化文档:

  • 连续分节符
  • 分节符新列
  • 分节符新页
  • 节断偶数页
  • 分节奇数页

您还可以使用 SectionStart 枚举来选择仅适用于第一部分的分隔类型,例如 NewColumn、NewPage、EvenPage 和 OddPage。

管理部分

由于节是一个普通的复合节点,因此可以使用全节点操作 API 来操作节:对节进行添加、删除等操作。您可以在 Aspose.Words Document Object Model (DOM) 文章中阅读有关节点的更多信息。

另一方面,您还可以使用 DocumentBuilder API 来处理部分。在本文中,我们将重点讨论这种使用节的特殊方式。

插入或删除分节符

Aspose.Words 允许您使用 InsertBreak 方法在文本中插入分节符。

以下代码示例演示如何在文档中插入分节符:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
def test_insert_section_breaks(self):
doc = aw.Document(MY_DIR + "Footnotes and endnotes.docx")
builder = aw.DocumentBuilder(doc)
paras = [para.as_paragraph() for para in doc.get_child_nodes(aw.NodeType.PARAGRAPH, True)]
topic_start_paras = []
for para in paras:
style = para.paragraph_format.style_identifier
if style == aw.StyleIdentifier.HEADING1:
topic_start_paras.append(para)
for para in topic_start_paras:
section = para.parent_section
# Insert section break if the paragraph is not at the beginning of a section already.
if para != section.body.first_paragraph:
builder.move_to(para.first_child)
builder.insert_break(aw.BreakType.SECTION_BREAK_NEW_PAGE)
# This is the paragraph that was inserted at the end of the now old section.
# We don't really need the extra paragraph, we just needed the section.
section.body.last_paragraph.remove()

使用 Remove 方法删除分节符。如果您不需要删除特定分节符而是删除该节的内容,则可以使用 ClearContent 方法。

以下代码示例展示了如何删除分节符:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
@staticmethod
def remove_section_breaks(doc: aw.Document):
# Loop through all sections starting from the section that precedes the last one and moving to the first section.
for i in range(doc.sections.count - 2, -1):
# Copy the content of the current section to the beginning of the last section.
doc.last_section.prepend_content(doc.sections[i])
# Remove the copied section.
doc.sections[i].remove()

移动一个部分

如果要将文档中的某个部分从一个位置移动到另一个位置,则需要获取该部分的索引。 Aspose.Words 允许您从 SectionCollection 中获取章节位置。您可以使用 Sections 属性来获取文档中的所有部分。但如果您只想获取第一部分,则可以使用 FirstSection 属性。

以下代码示例演示如何访问第一部分并迭代复合节点的子节点:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.write("Section 1")
builder.move_to_header_footer(aw.HeaderFooterType.HEADER_PRIMARY)
builder.write("Primary header")
builder.move_to_header_footer(aw.HeaderFooterType.FOOTER_PRIMARY)
builder.write("Primary footer")
section = doc.first_section
# A Section is a composite node and can contain child nodes,
# but only if those child nodes are of a "Body" or "HeaderFooter" node type.
for node in section.get_child_nodes(aw.NodeType.ANY, False):
if node.node_type == aw.NodeType.BODY:
body = node.as_body()
print("Body:")
print(f"\t\"{body.get_text().strip()}\"")
if node.node_type == aw.NodeType.HEADER_FOOTER:
header_footer = node.as_header_footer()
print(f"HeaderFooter type: {header_footer.header_footer_type};")
print(f"\t\"{header_footer.get_text().strip()}\"")

指定部分布局

有时,您希望通过为文档的不同部分制作创意布局来使文档看起来更好。如果要指定当前截面网格的类型,可以使用 SectionLayoutMode 枚举选择截面布局模式:

  • 默认
  • 网格
  • 线网格
  • SnapToChars

以下代码示例显示如何限制每个页面可以拥有的行数:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
# Enable pitching, and then use it to set the number of lines per page in this section.
# A large enough font size will push some lines down onto the next page to avoid overlapping characters.
builder.page_setup.layout_mode = aw.SectionLayoutMode.LINE_GRID
builder.page_setup.lines_per_page = 15
builder.paragraph_format.snap_to_grid = True
for i in range(30):
builder.write(
"Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ")
doc.save(ARTIFACTS_DIR + "WorkingWithDocumentOptionsAndSettings.line_grid_section_layout_mode.docx")

编辑部分

当您向文档添加新部分时,将没有可以编辑的正文或段落。 Aspose.Words 允许您使用 EnsureMinimum 方法保证一个节包含至少一个段落的正文 - 它会自动向文档添加一个 Body(或 HeaderFooter)节点,然后向其中添加一个 Paragraph。

以下代码示例展示了如何使用 EnsureMinimum 准备新的节节点:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document()
# If we add a new section like this, it will not have a body, or any other child nodes.
doc.sections.add(aw.Section(doc))
# Run the "EnsureMinimum" method to add a body and a paragraph to this section to begin editing it.
doc.last_section.ensure_minimum()
doc.sections[0].body.first_paragraph.append_child(aw.Run(doc, "Hello world!"))

追加或前置内容

如果您想在部分的开头/结尾绘制某些形状或添加文本或图像,可以使用 Section 类的 AppendContentPrependContent 方法。

以下代码示例演示如何附加现有部分的内容:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.write("Section 1")
builder.insert_break(aw.BreakType.SECTION_BREAK_NEW_PAGE)
builder.write("Section 2")
builder.insert_break(aw.BreakType.SECTION_BREAK_NEW_PAGE)
builder.write("Section 3")
section = doc.sections[2]
# Insert the contents of the first section to the beginning of the third section.
section_to_prepend = doc.sections[0]
section.prepend_content(section_to_prepend)
# Insert the contents of the second section to the end of the third section.
section_to_append = doc.sections[1]
section.append_content(section_to_append)

克隆一个部分

Aspose.Words 允许您通过使用 Clone 方法创建该部分的完整副本来复制该部分。

以下代码示例演示如何克隆文档中的第一部分:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document(MY_DIR + "Document.docx")
clone_section = doc.sections[0].clone()

复制文档之间的部分

在某些情况下,您可能拥有包含许多部分的大型文档,并且您希望将某个部分的内容从一个文档复制到另一个文档。

Aspose.Words 允许您使用 ImportNode 方法复制文档之间的部分。

以下代码示例演示如何在文档之间复制部分:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
src_doc = aw.Document(MY_DIR + "Document.docx")
dst_doc = aw.Document()
source_section = src_doc.sections[0]
new_section = dst_doc.import_node(source_section, True).as_section()
dst_doc.sections.add(new_section)
dst_doc.save(ARTIFACTS_DIR + "WorkingWithSection.copy_section.docx")
view raw copy-section.py hosted with ❤ by GitHub

使用节页眉和页脚

显示每个部分的页眉或页脚的基本规则非常简单:

  1. 如果该节没有自己的某种类型的页眉/页脚,则它取自上一节。
  2. 页面上显示的页眉/页脚类型由"不同首页"和"不同奇数页和偶数页"部分设置控制 - 如果禁用它们,则忽略该部分自己的标题。

以下代码示例演示如何创建具有不同标头的 2 个部分:

如果要删除页眉和页脚的文本而不删除文档中的 HeaderFooter 对象,可以使用 ClearHeadersFooters 方法。此外,您可以使用 DeleteHeaderFooterShapes 方法从文档的页眉和页脚中删除所有形状。

以下代码示例演示如何清除节中所有页眉和页脚的内容:

以下代码示例如何从节中的所有页眉页脚中删除所有形状:

自定义部分中的页面属性

在打印页面或文档之前,您可能需要自定义和修改单页或整个文档的尺寸和布局。通过页面设置,您可以更改文档页面的设置,例如页边距、方向和尺寸,以打印不同的首页或奇数页。

Aspose.Words 允许您使用 PageSetup 类自定义页面和部分属性。

以下代码示例显示如何设置当前部分的页面大小和方向等属性:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.page_setup.orientation = aw.Orientation.LANDSCAPE
builder.page_setup.left_margin = 50
builder.page_setup.paper_size = aw.PaperSize.PAPER_10X14
doc.save(ARTIFACTS_DIR + "WorkingWithDocumentOptionsAndSettings.page_setup_and_section_formatting.docx")

以下代码示例显示如何修改所有部分中的页面属性:

# For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Python-via-.NET.git.
doc = aw.Document()
builder = aw.DocumentBuilder(doc)
builder.writeln("Section 1")
doc.append_child(aw.Section(doc))
builder.writeln("Section 2")
doc.append_child(aw.Section(doc))
builder.writeln("Section 3")
doc.append_child(aw.Section(doc))
builder.writeln("Section 4")
# It is important to understand that a document can contain many sections,
# and each section has its page setup. In this case, we want to modify them all.
for child in doc:
child.as_section().page_setup.paper_size = aw.PaperSize.LETTER
doc.save(ARTIFACTS_DIR + "WorkingWithSection.modify_page_setup_in_all_sections.doc")

也可以看看