文書の挿入と追加

複数のドキュメントを1つに結合する必要がある場合があります。 これは手動で行うことも、Aspose.Words挿入または追加機能を使用することもできます。

挿入操作を使用すると、以前に作成されたドキュメントの内容を新規または既存のドキュメントに挿入できます。

次に、追加機能を使用すると、別の文書の最後にのみ文書を追加できます。

この記事では、さまざまな方法でドキュメントを別のドキュメントに挿入または追加する方法と、ドキュメントの挿入または追加時に適用できる共通のプロパティについて説明します。

文書を挿入する

上述したように、Aspose.Wordsでは、文書はノードのツリーとして表され、ある文書を別の文書に挿入する操作は、第一の文書ツリーから第二の文書ツリーにノードをコピーす

ドキュメントは、さまざまな場所にさまざまな方法で挿入できます。 たとえば、置換操作、マージ操作中の差し込み項目、またはブックマークを使用してドキュメントを挿入できます。

また、InsertDocumentまたはInsertDocumentInlineメソッドを使用して、Microsoft Wordに文書を挿入するのと同様に、以前のインポートなしで現在のカーソル位置に文書全体を挿入することもできます。

次のコード例は、InsertDocumentメソッドを使用してドキュメントを挿入する方法を示しています:

// 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 source.docx");
Document dstDoc = new Document(getMyDir() + "Northwind traders.docx");
DocumentBuilder builder = new DocumentBuilder(dstDoc);
builder.moveToDocumentEnd();
builder.insertBreak(BreakType.PAGE_BREAK);
builder.insertDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
builder.getDocument().save(getArtifactsDir() + "JoinAndAppendDocuments.insertDocument.docx");

次のコード例は、InsertDocumentInlineメソッドを使用してドキュメントを挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
DocumentBuilder srcDoc = new DocumentBuilder();
srcDoc.write("[src content]");
// Create destination document.
DocumentBuilder dstDoc = new DocumentBuilder();
dstDoc.write("Before ");
dstDoc.insertNode(new BookmarkStart(dstDoc.getDocument(), "src_place"));
dstDoc.insertNode(new BookmarkEnd(dstDoc.getDocument(), "src_place"));
dstDoc.write(" after");
Assert.assertEquals("Before after", dstDoc.getDocument().getText().trim());
// Insert source document into destination inline.
dstDoc.moveToBookmark("src_place");
dstDoc.insertDocumentInline(srcDoc.getDocument(), ImportFormatMode.USE_DESTINATION_STYLES, new ImportFormatOptions());
Assert.assertEquals("Before [src content] after", dstDoc.getDocument().getText().trim());

次のサブセクションでは、あるドキュメントを別のドキュメントに挿入するためのオプションについて説明します。

検索および置換操作 {#insert-a-document-during-find-and-replace-operation}中に文書を挿入する

検索および置換操作の実行中にドキュメントを挿入できます。 たとえば、文書には[INTRODUCTION]と[CONCLUSION]というテキストを含む段落を含めることができます。 しかし、最終的な文書では、それらの段落を別の外部文書から取得した内容に置き換える必要があります。 これを実現するには、replaceイベントのハンドラーを作成する必要があります。

次のコード例は、replacingイベントのハンドラーを作成して、挿入プロセスの後半で使用する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
private static class InsertDocumentAtReplaceHandler implements IReplacingCallback
{
public /*ReplaceAction*/int /*IReplacingCallback.*/replacing(ReplacingArgs args) throws Exception
{
Document subDoc = new Document(getMyDir() + "Document insertion 2.docx");
// Insert a document after the paragraph, containing the match text.
Paragraph para = (Paragraph)args.getMatchNode().getParentNode();
insertDocument(para, subDoc);
// Remove the paragraph with the match text.
para.remove();
return ReplaceAction.SKIP;
}
}

次のコード例は、検索および置換操作中にあるドキュメントのコンテンツを別のドキュメントに挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx");
// Set find and replace options.
FindReplaceOptions options = new FindReplaceOptions();
{
options.setDirection(FindReplaceDirection.BACKWARD);
options.setReplacingCallback(new InsertDocumentAtReplaceHandler());
}
// Call the replace method.
mainDoc.getRange().replace(Pattern.compile("\\[MY_DOCUMENT\\]"), "", options);
mainDoc.save(getArtifactsDir() + "CloneAndCombineDocuments.InsertDocumentAtReplace.docx");

Mail Merge操作 {#insert-a-document-during-mail-merge-operation}中に文書を挿入する

Mail Merge操作中に差し込み項目に文書を挿入できます。 たとえば、Mail Mergeテンプレートには[Summary]などの差し込み項目を含めることができます。 ただし、最終文書では、別の外部文書から取得したコンテンツをこの差し込み項目に挿入する必要があります。 これを実現するには、mergeイベントのハンドラーを作成する必要があります。

次のコード例は、mergingイベントのハンドラーを作成して、挿入プロセスの後半で使用する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
private static class InsertDocumentAtMailMergeHandler implements IFieldMergingCallback
{
// This handler makes special processing for the "Document_1" field.
// The field value contains the path to load the document.
// We load the document and insert it into the current merge field.
public void /*IFieldMergingCallback.*/fieldMerging(FieldMergingArgs args) throws Exception
{
if ("Document_1".equals(args.getDocumentFieldName()))
{
// Use document builder to navigate to the merge field with the specified name.
DocumentBuilder builder = new DocumentBuilder(args.getDocument());
builder.moveToMergeField(args.getDocumentFieldName());
// The name of the document to load and insert is stored in the field value.
Document subDoc = new Document((String)args.getFieldValue());
insertDocument(builder.getCurrentParagraph(), subDoc);
// The paragraph that contained the merge field might be empty now, and you probably want to delete it.
if (!builder.getCurrentParagraph().hasChildNodes())
builder.getCurrentParagraph().remove();
// Indicate to the mail merge engine that we have inserted what we wanted.
args.setText(null);
}
}
public void /*IFieldMergingCallback.*/imageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
}

次のコード例は、createdハンドラーを使用して差し込み項目にドキュメントを挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx");
mainDoc.getMailMerge().setFieldMergingCallback(new InsertDocumentAtMailMergeHandler());
// The main document has a merge field in it called "Document_1".
// The corresponding data for this field contains a fully qualified path to the document.
// That should be inserted to this field.
mainDoc.getMailMerge().execute(new String[] { "Document_1" }, new Object[] { getMyDir() + "Document insertion 2.docx" });
mainDoc.save(getArtifactsDir() + "CloneAndCombineDocuments.InsertDocumentAtMailMerge.doc");

ブックマークに文書を挿入する

テキストファイルをドキュメントにインポートして、ドキュメントで定義したブックマークの直後に挿入することができます。 これを行うには、ドキュメントを挿入するブックマークされた段落を作成します。

次のコーディング例は、ある文書の内容を別の文書のブックマークに挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document mainDoc = new Document(getMyDir() + "Document insertion 1.docx");
Document subDoc = new Document(getMyDir() + "Document insertion 2.docx");
Bookmark bookmark = mainDoc.getRange().getBookmarks().get("insertionPlace");
insertDocument(bookmark.getBookmarkStart().getParentNode(), subDoc);
mainDoc.save(getArtifactsDir() + "CloneAndCombineDocuments.InsertDocumentAtBookmark.docx");

文書を追加する

ドキュメントから既存のドキュメントの最後まで追加のページを含める必要があるユースケースがある場合があります。 これを行うには、AppendDocumentメソッドを呼び出してドキュメントを別のドキュメントの最後に追加するだけです。

次のコード例は、ドキュメントを別のドキュメントの末尾に追加する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
Document dstDoc = new Document();
dstDoc.getFirstSection().getBody().appendParagraph("Destination document text. ");
Document srcDoc = new Document();
srcDoc.getFirstSection().getBody().appendParagraph("Source document text. ");
// Append the source document to the destination document.
// Pass format mode to retain the original formatting of the source document when importing it.
dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
dstDoc.save(getArtifactsDir() + "JoinAndAppendDocuments.KeepSourceFormatting.docx");

ノードの手動でのインポートと挿入

Aspose.Words以前のインポート要件を使用せずに、ドキュメントを自動的に挿入および追加できます。 ただし、セクションや段落など、文書の特定のノードを挿入または追加する必要がある場合は、まずこのノードを手動でインポートする必要があります。

あるセクションや段落を別のセクションや段落に挿入または追加する必要がある場合は、基本的にImportNodeメソッドを使用して最初のドキュメントノードツリーノードツリーのノードを2番目のノードにインポートする必要があります。 ノードをインポートした後、InsertAfterメソッドを使用して、参照ノードの前後に新しいノードを挿入する必要があります。 これにより、ドキュメントからノードをインポートし、指定された位置に挿入することで、挿入プロセスをカスタマイズできます。

また、セクションレベルではなく段落レベルでコンテンツを追加する場合など、AppendChildメソッドを使用して、子ノードのリストの最後に新しい指定されたノードを追加することもできます。

次のコード例は、ノードを手動でインポートし、InsertAfterメソッドを使用して特定のノードの後に挿入する方法を示しています:

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-Java.git.
/// <summary>
/// Inserts content of the external document after the specified node.
/// Section breaks and section formatting of the inserted document are ignored.
/// </summary>
/// <param name="insertionDestination">Node in the destination document after which the content
/// Should be inserted. This node should be a block level node (paragraph or table).</param>
/// <param name="docToInsert">The document to insert.</param>
private static void insertDocument(Node insertionDestination, Document docToInsert)
{
if (insertionDestination.getNodeType() == NodeType.PARAGRAPH || insertionDestination.getNodeType() == NodeType.TABLE)
{
CompositeNode destinationParent = insertionDestination.getParentNode();
NodeImporter importer =
new NodeImporter(docToInsert, insertionDestination.getDocument(), ImportFormatMode.KEEP_SOURCE_FORMATTING);
// Loop through all block-level nodes in the section's body,
// then clone and insert every node that is not the last empty paragraph of a section.
for (Section srcSection : docToInsert.getSections())
for (Node srcNode : srcSection.getBody())
{
if (srcNode.getNodeType() == NodeType.PARAGRAPH)
{
Paragraph para = (Paragraph)srcNode;
if (para.isEndOfSection() && !para.hasChildNodes())
continue;
}
Node newNode = importer.importNode(srcNode, true);
destinationParent.insertAfter(newNode, insertionDestination);
insertionDestination = newNode;
}
}
else
{
throw new IllegalArgumentException("The destination node should be either a paragraph or table.");
}
}

これは、ページ設定やヘッダーやフッターなどの設定がインポート中に保持されることを意味します。 また、文書を挿入または追加するときに書式設定を定義して、2つの文書を結合する方法を指定できることにも注意してください。

挿入文書と追加文書の共通プロパティ

InsertDocumentAppendDocumentの両方のメソッドは、入力パラメータとしてImportFormatModeImportFormatOptionsを受け入れます。 ImportFormatModeを使用すると、UseDestinationStylesKeepSourceFormattingKeepDifferentStylesなどの異なる書式モードを選択して、ある文書から別の文書にコンテンツをインポートするときに文書の書式をマージする方法を制 ImportFormatOptionsを使用すると、次のようなさまざまなインポートオプションを選択できますIgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists, とSmartStyleBehavior

Aspose.Wordsでは、SectionおよびPageSetupプロパティを使用して、挿入または追加操作で二つの文書が一緒に追加されたときに、結果の文書の視覚化を調整できます。Aspose.Wordsは、SectionPageSetup PageSetupプロパティには、次のようなセクションのすべての属性が含まれていますSectionStart, RestartPageNumbering, PageStartingNumber, Orientation, と他の人。 最も一般的な使用例は、SectionStartプロパティを設定して、追加されたコンテンツが同じページに表示されるか、新しいページに分割されるかを定義することです。

次のコード例は、コンテンツが2つのページに分割されないようにしながら、あるドキュメントを別のドキュメントに追加する方法を示しています:

// 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 source.docx");
Document dstDoc = new Document(getMyDir() + "Northwind traders.docx");
// Set the source document to continue straight after the end of the destination document.
srcDoc.getFirstSection().getPageSetup().setSectionStart(SectionStart.CONTINUOUS);
// Restart the page numbering on the start of the source document.
srcDoc.getFirstSection().getPageSetup().setRestartPageNumbering(true);
srcDoc.getFirstSection().getPageSetup().setPageStartingNumber(1);
// To ensure this does not happen when the source document has different page setup settings, make sure the
// settings are identical between the last section of the destination document.
// If there are further continuous sections that follow on in the source document,
// this will need to be repeated for those sections.
srcDoc.getFirstSection().getPageSetup().setPageWidth(dstDoc.getLastSection().getPageSetup().getPageWidth());
srcDoc.getFirstSection().getPageSetup().setPageHeight(dstDoc.getLastSection().getPageSetup().getPageHeight());
srcDoc.getFirstSection().getPageSetup().setOrientation(dstDoc.getLastSection().getPageSetup().getOrientation());
// Iterate through all sections in the source document.
for (Paragraph para : (Iterable<Paragraph>) srcDoc.getChildNodes(NodeType.PARAGRAPH, true))
{
para.getParagraphFormat().setKeepWithNext(true);
}
dstDoc.appendDocument(srcDoc, ImportFormatMode.KEEP_SOURCE_FORMATTING);
dstDoc.save(getArtifactsDir() + "JoinAndAppendDocuments.DifferentPageSetup.docx");