セクションの操作

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

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

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

この記事では、セクションとセクションブレークを操作する方法について説明します。

セクションとセクションブレークとは何ですか

ドキュメントセクションはSectionクラスとSectionCollectionクラスで表されます。 セクションオブジェクトはDocumentノードの直接の子であり、Sectionsプロパティを介してアクセスできます。 これらのノードは、次のようないくつかの方法を使用して管理できますRemove, Add, IndexOf, と他の人。

セクション区切りは、ドキュメントページをカスタマイズ可能なレイアウトのセクションに分割するオプションです。

セクションブレークの種類

Aspose.Wordsでは、BreakType列挙体の異なるセクション区切りを使用してドキュメントを分割および書式設定できます:

  • SectionBreakContinuous
  • SectionBreakNewColumn
  • SectionBreakNewPage
  • SectionBreakEvenPage
  • SectionBreakOddPage

また、SectionStart列挙体を使用して、次のような最初のセクションにのみ適用されるブレークタイプを選択することもできますNewColumn, NewPage, EvenPage, とOddPage。

セクションの管理

セクションは通常の複合ノードであるため、ノード操作API全体を使用してセクションを操作することができます:セクションの追加、削除、およびその他の 記事でノードの詳細を読むことができます Aspose.Wordsドキュメントオブジェクトモデル(DOM).

一方、DocumentBuilderAPIを使用してセクションを操作することもできます。 この記事では、セクションを操作するこの特定の方法に焦点を当てます。

セクション区切りを挿入または削除する

Aspose.Wordsは、InsertBreakメソッドを使用してテキストにセクション区切りを挿入できます。

次のコード例は、セクション区切りをドキュメントに挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
/// <summary>
/// Insert section breaks before the specified paragraphs.
/// </summary>
private void insertSectionBreaks(ArrayList<Paragraph> topicStartParas)
{
DocumentBuilder builder = new DocumentBuilder(mDoc);
for (Paragraph para : topicStartParas)
{
Section section = para.getParentSection();
// Insert section break if the paragraph is not at the beginning of a section already.
if (para != section.getBody().getFirstParagraph())
{
builder.moveTo(para.getFirstChild());
builder.insertBreak(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.getBody().getLastParagraph().remove();
}
}
}

セクション区切りを削除するには、Removeメソッドを使用します。 特定のセクション区切りを削除する必要がなく、代わりにそのセクションのコンテンツを削除する場合は、ClearContentメソッドを使用できます。

次のコード例は、セクションの区切りを削除する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.getSections().getCount() - 2; i >= 0; i--)
{
// Copy the content of the current section to the beginning of the last section.
doc.getLastSection().prependContent(doc.getSections().get(i));
// Remove the copied section.
doc.getSections().get(i).remove();
}
}

セクションを移動する

ドキュメント内のある位置から別の位置にセクションを移動する場合は、そのセクションのインデックスを取得する必要があります。 Aspose.WordsはSectionCollectionからセクションの位置を取得できます。 ドキュメント内のすべてのセクションを取得するには、Sectionsプロパティを使用できます。 ただし、最初のセクションのみを取得する場合は、FirstSectionプロパティを使用できます。

次のコード例は、最初のセクションにアクセスし、複合ノードの子を反復処理する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Section 1");
builder.moveToHeaderFooter(HeaderFooterType.HEADER_PRIMARY);
builder.write("Primary header");
builder.moveToHeaderFooter(HeaderFooterType.FOOTER_PRIMARY);
builder.write("Primary footer");
Section section = doc.getFirstSection();
// 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 node : section)
{
switch (node.getNodeType())
{
case NodeType.BODY:
{
Body body = (Body)node;
System.out.println("Body:");
System.out.println(MessageFormat.format("\t\"{0}\"", body.getText().trim()));
break;
}
case NodeType.HEADER_FOOTER:
{
HeaderFooter headerFooter = (HeaderFooter)node;
System.out.println(MessageFormat.format("HeaderFooter type: {0}:", headerFooter.getHeaderFooterType()));
System.out.println(MessageFormat.format("\t\"{0}\"", 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-Java.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.getPageSetup().setLayoutMode(SectionLayoutMode.LINE_GRID);
builder.getPageSetup().setLinesPerPage(15);
builder.getParagraphFormat().setSnapToGrid(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(getArtifactsDir() + "WorkingWithDocumentOptionsAndSettings.LinesPerPage.docx");

セクションを編集する

ドキュメントに新しいセクションを追加すると、編集できる本文や段落はありません。 Aspose.Wordsは、EnsureMinimumメソッドを使用して、セクションに少なくとも一つの段落を持つ本文が含まれていることを保証することができます–本文(またはHeaderFooter)ノードを文書に自動的に追加し、それに段落を追加します。

次のコード例は、EnsureMinimumを使用して新しいセクションノードを準備する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.getSections().add(new Section(doc));
// Run the "EnsureMinimum" method to add a body and a paragraph to this section to begin editing it.
doc.getLastSection().ensureMinimum();
doc.getSections().get(0).getBody().getFirstParagraph().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-Java.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.write("Section 1");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.write("Section 2");
builder.insertBreak(BreakType.SECTION_BREAK_NEW_PAGE);
builder.write("Section 3");
// This is the section that we will append and prepend to.
Section section = doc.getSections().get(2);
// Insert the contents of the first section to the beginning of the third section.
Section sectionToPrepend = doc.getSections().get(0);
section.prependContent(sectionToPrepend);
// Insert the contents of the second section to the end of the third section.
Section sectionToAppend = doc.getSections().get(1);
section.appendContent(sectionToAppend);

セクションのクローンを作成する

Aspose.Wordsを使用すると、deepCloneメソッドを使用してセクションの完全なコピーを作成することにより、セクションを複製できます。

次のコード例は、ドキュメントの最初のセクションを複製する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document doc = new Document(getMyDir() + "Document.docx");
Section cloneSection = doc.getSections().get(0).deepClone();

ドキュメント間のセクションのコピー

場合によっては、多数のセクションを含む大きなドキュメントがあり、セクションの内容をあるドキュメントから別のドキュメントにコピーする

Aspose.Wordsは、ImportNodeメソッドを使用してドキュメント間のセクションをコピーできます。

次のコード例は、ドキュメント間のセクションをコピーする方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document srcDoc = new Document(getMyDir() + "Document.docx");
Document dstDoc = new Document();
Section sourceSection = srcDoc.getSections().get(0);
Section newSection = (Section) dstDoc.importNode(sourceSection, true);
dstDoc.getSections().add(newSection);
dstDoc.save(getArtifactsDir() + "WorkingWithSection.CopySection.docx");

セクションヘッダーとフッターの操作

各セクションのヘッダーまたはフッターを表示するための基本的なルールは非常に簡単です:

  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-Java.git.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.getPageSetup().setOrientation(Orientation.LANDSCAPE);
builder.getPageSetup().setLeftMargin(50.0);
builder.getPageSetup().setPaperSize(PaperSize.PAPER_10_X_14);
doc.save(getArtifactsDir() + "WorkingWithDocumentOptionsAndSettings.SetPageSetupAndSectionFormatting.docx");

次のコード例は、すべてのセクションのページプロパティを変更する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.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.
for (Section section : doc.getSections())
section.getPageSetup().setPaperSize(PaperSize.LETTER);
doc.save(getArtifactsDir() + "WorkingWithSection.ModifyPageSetupInAllSections.doc");

また見て下さい