與分節一起工作

有時你希望有一份文件,它不希望在所有頁面上具有相同的格式。 例如,您可能需要修改頁碼格式、不同頁面大小和方向,或者將第一份文件作為沒有頁碼的封面頁。 你可以用分組來實現。

節是控制標題和腳線、方向、欄位、邊距、頁碼格式等之水平節點。

Aspose.Words讓您可以管理章節、將一篇文件分成幾段,以及只對特定一段做出格式化變更。您可以在Aspose.Words中儲存章節格式化資訊,如標頭和尾列、頁面設定以及欄位設定。

本文說明如何處理章節與分節。

什麼是章節與分節標記

文件節是使用 SectionSectionCollection 類別表示的。 節點物件是 Document 節點的直接子節點,並且可以透過 Sections 屬性來存取。 您可以使用一些方法來管理這些節點,例如 RemoveAddIndexOf 和其他。

分節選項可將文件頁面分成可自訂布局的分節。

分節的種類

Aspose.Words 讓您可以透過不同的BreakType列號分節來分割並格式化文件:

*SectionBreakContinuous *SectionBreakNewColumn *SectionBreakNewPage *SectionBreakEvenPage *SectionBreakOddPage

您也可以使用 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-.NET.git.
/// <summary>
/// Insert section breaks before the specified paragraphs.
/// </summary>
private void InsertSectionBreaks(List<Paragraph> topicStartParas)
{
DocumentBuilder builder = new DocumentBuilder(mDoc);
foreach (Paragraph para in topicStartParas)
{
Section section = para.ParentSection;
// Insert section break if the paragraph is not at the beginning of a section already.
if (para != section.Body.FirstParagraph)
{
builder.MoveTo(para.FirstChild);
builder.InsertBreak(BreakType.SectionBreakNewPage);
// 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.LastParagraph.Remove();
}
}
}

使用 Remove 方法來刪除一個分節區段。 如果你不需要移除特定分頁,而要刪除該段落的內容,你可以利用第一種 ClearContent 的方法。

接下來的程式碼範例示範了如何移除段落斷點:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
private void RemoveSectionBreaks(Document doc)
{
// Loop through all sections starting from the section that precedes the last one and moving to the first section.
for (int i = doc.Sections.Count - 2; i >= 0; i--)
{
// Copy the content of the current section to the beginning of the last section.
doc.LastSection.PrependContent(doc.Sections[i]);
// Remove the copied section.
doc.Sections[i].Remove();
}
}

移動一節內容

如果您想將一節內容從文件中的一個位置移動到另一個位置,則需要獲取該節的索引。 Aspose.Words允許您通過使用 Item 屬性從 SectionCollection 中獲取一節的位置。 您可以使用 Sections 屬性取得您的文件中所有分節。 但是如果你只想得到第一個節奏,你可以利用 FirstSection 的屬性。

以下範例示範如何訪問第一個節點,然後迭代複合節點的子節點:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Section 1");
builder.MoveToHeaderFooter(HeaderFooterType.HeaderPrimary);
builder.Write("Primary header");
builder.MoveToHeaderFooter(HeaderFooterType.FooterPrimary);
builder.Write("Primary footer");
Section section = doc.FirstSection;
// 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.
foreach (Node node in section)
{
switch (node.NodeType)
{
case NodeType.Body:
{
Body body = (Body)node;
Console.WriteLine("Body:");
Console.WriteLine($"\t\"{body.GetText().Trim()}\"");
break;
}
case NodeType.HeaderFooter:
{
HeaderFooter headerFooter = (HeaderFooter)node;
Console.WriteLine($"HeaderFooter type: {headerFooter.HeaderFooterType}:");
Console.WriteLine($"\t\"{headerFooter.GetText().Trim()}\"");
break;
}
default:
{
throw new Exception("Unexpected node type in a section.");
}
}
}

請指定分欄布陣。

有時你會希望你的文件透過為不同文件節的創意布局來看起來更好。 若您要指定目前區塊列的類型,您可以選擇使用 SectionLayoutMode 列舉方式的區塊排版模式。

  • 預設
  • 格子
  • LineGrid
  • SnapToChars

以下範例碼示意如何限制每個頁面的行數:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new 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.PageSetup.LayoutMode = SectionLayoutMode.LineGrid;
builder.PageSetup.LinesPerPage = 15;
builder.ParagraphFormat.SnapToGrid = true;
for (int i = 0; i < 30; i++)
builder.Write("Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. ");
doc.Save(ArtifactsDir + "WorkingWithDocumentOptionsAndSettings.LinesPerPage.docx");

編輯一節

當你新增一節到你的文件時,你會發現沒有任何體或段落可以編輯。 Aspose.Words 讓你用 EnsureMinimum 方法來保證一節至少有一段內容 – 它會自動在文件中加入一個 Body(或 HeaderFooter)節點,然後再加入一段文字。

以下範例程式碼示範如何透過 EnsureMinimum 來建立新節點:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
// If we add a new section like this, it will not have a body, or any other child nodes.
doc.Sections.Add(new Section(doc));
// Run the "EnsureMinimum" method to add a body and a paragraph to this section to begin editing it.
doc.LastSection.EnsureMinimum();
doc.Sections[0].Body.FirstParagraph.AppendChild(new Run(doc, "Hello world!"));

新增或串接內容

如果您要繪製某個形狀或在節目的開始/結束添加文字或圖像,則可以使用 AppendContentPrependContent 方法 Section 類別。

接下來這個程式碼範例示範了如何附加現有節的內容:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Write("Section 1");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 2");
builder.InsertBreak(BreakType.SectionBreakNewPage);
builder.Write("Section 3");
Section section = doc.Sections[2];
// Insert the contents of the first section to the beginning of the third section.
Section sectionToPrepend = doc.Sections[0];
section.PrependContent(sectionToPrepend);
// Insert the contents of the second section to the end of the third section.
Section sectionToAppend = doc.Sections[1];
section.AppendContent(sectionToAppend);

複製一段

Aspose.Words 讓您透過使用 Clone 方法來複製一整個區域。

接下來的程式碼範例展示了如何複製你文件中的第一節:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document(MyDir + "Document.docx");
Section cloneSection = doc.Sections[0].Clone();

將文件間複製部分內容

在有些情況下,你可能有大文件與許多分節,你想要從一個文件複製一個分節的內容到另一個文件。

Aspose.Words 允許您透過 ImportNode 方法在文件間複製章節。

以下示例程式碼示範了如何在文件之間複製部份內容:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document srcDoc = new Document(MyDir + "Document.docx");
Document dstDoc = new Document();
Section sourceSection = srcDoc.Sections[0];
Section newSection = (Section)dstDoc.ImportNode(sourceSection, true);
dstDoc.Sections.Add(newSection);
dstDoc.Save(ArtifactsDir + "WorkingWithSection.CopySection.docx");
view raw copy-section.cs 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-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.PageSetup.Orientation = Orientation.Landscape;
builder.PageSetup.LeftMargin = 50;
builder.PageSetup.PaperSize = PaperSize.Paper10x14;
doc.Save(ArtifactsDir + "WorkingWithDocumentOptionsAndSettings.PageSetupAndSectionFormatting.docx");

以下範例顯示如何在所有部分中修改頁面屬性:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Writeln("Section 1");
doc.AppendChild(new Section(doc));
builder.Writeln("Section 2");
doc.AppendChild(new Section(doc));
builder.Writeln("Section 3");
doc.AppendChild(new 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.
foreach (Section section in doc)
section.PageSetup.PaperSize = PaperSize.Letter;
doc.Save(ArtifactsDir + "WorkingWithSection.ModifyPageSetupInAllSections.doc");

另看: