セクションの操作

場合によっては、すべてのページにわたって同じ書式設定を持たないドキュメントが必要になることがあります。たとえば、ページ番号の形式を変更したり、ページのサイズや方向を変更したり、文書の最初のページを番号を付けずに表紙として使用したりする必要がある場合があります。セクションを使用するとそれを実現できます。

セクションは、ヘッダーとフッター、方向、列、余白、ページ番号の書式設定などを制御するレベル ノードです。

Aspose.Words を使用すると、セクションを管理し、ドキュメントをセクションに分割し、特定のセクションにのみ適用される書式変更を行うことができます。 Aspose.Words は、ヘッダーとフッター、ページ設定、セクション区切りの列設定などのセクションの書式設定に関する情報を保存します。

この記事では、セクションとセクション区切りの操作方法について説明します。

セクションとセクション区切りとは

ドキュメント セクションは、Section クラスと SectionCollection クラスによって表されます。セクション オブジェクトは 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-.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 列挙を使用してセクション レイアウト モードを選択できます。

  • デフォルト
  • グリッド
  • ライングリッド
  • 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 メソッドを使用してセクションに少なくとも 1 つの段落を含む本文が含まれていることを保証できます。これにより、自動的に本文 (またはヘッダーフッター) ノードがドキュメントに追加され、次に段落が追加されます。

次のコード例は、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!"));

コンテンツを追加または先頭に追加

セクションの先頭/末尾に何らかの図形を描画したり、テキストや画像を追加したりする場合は、Section クラスの AppendContent メソッドと PrependContent メソッドを使用できます。

次のコード例は、既存のセクションのコンテンツを追加する方法を示しています。

// 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");

関連項目