문서 삽입 및 추가

때로는 여러 문서를 하나로 통합해야 하는 경우도 있습니다. 이 작업을 수동으로 수행하거나 Aspose.Words 삽입 또는 추가 기능을 사용할 수 있습니다.

삽입 작업을 사용하면 이전에 생성된 문서의 내용을 새 문서나 기존 문서에 삽입할 수 있습니다.

또한 추가 기능을 사용하면 다른 문서의 끝에만 문서를 추가할 수 있습니다.

이 문서에서는 다양한 방법으로 문서를 다른 문서에 삽입하거나 추가하는 방법을 설명하고 문서를 삽입하거나 추가하는 동안 적용할 수 있는 공통 속성에 대해 설명합니다.

문서 {#insert-a-document} 삽입

위에서 언급했듯이 Aspose.Words에서 문서는 노드 트리로 표현되며, 한 문서를 다른 문서에 삽입하는 작업은 첫 번째 문서 트리에서 두 번째 문서 트리로 노드를 복사하는 것입니다.

다양한 위치에 다양한 방법으로 문서를 삽입할 수 있습니다. 예를 들어 바꾸기 작업, 병합 작업 중 병합 필드 또는 책갈피를 통해 문서를 삽입할 수 있습니다.

Microsoft Word에 문서를 삽입하는 것과 유사한 InsertDocument 또는 InsertDocumentInline 방법을 사용하면 이전에 가져오지 않고도 현재 커서 위치에 전체 문서를 삽입할 수 있습니다.

다음 코드 예제에서는 InsertDocument 메서드를 사용하여 문서를 삽입하는 방법을 보여줍니다

// 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 source.docx");
Document dstDoc = new Document(MyDir + "Northwind traders.docx");
DocumentBuilder builder = new DocumentBuilder(dstDoc);
builder.MoveToDocumentEnd();
builder.InsertBreak(BreakType.PageBreak);
builder.InsertDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
builder.Document.Save(ArtifactsDir + "JoinAndAppendDocuments.InsertDocument.docx");

다음 코드 예제에서는 InsertDocumentInline 메서드를 사용하여 문서를 삽입하는 방법을 보여줍니다

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
DocumentBuilder srcDoc = new DocumentBuilder();
srcDoc.Write("[src content]");
// Create destination document.
DocumentBuilder dstDoc = new DocumentBuilder();
dstDoc.Write("Before ");
dstDoc.InsertNode(new BookmarkStart(dstDoc.Document, "src_place"));
dstDoc.InsertNode(new BookmarkEnd(dstDoc.Document, "src_place"));
dstDoc.Write(" after");
Assert.AreEqual("Before after", dstDoc.Document.GetText().TrimEnd());
// Insert source document into destination inline.
dstDoc.MoveToBookmark("src_place");
dstDoc.InsertDocumentInline(srcDoc.Document, ImportFormatMode.UseDestinationStyles, new ImportFormatOptions());
Assert.AreEqual("Before [src content] after", dstDoc.Document.GetText().TrimEnd());

다음 하위 섹션에서는 한 문서를 다른 문서에 삽입할 수 있는 옵션에 대해 설명합니다.

찾기 및 바꾸기 작업 중에 문서 삽입

찾기 및 바꾸기 작업을 수행하는 동안 문서를 삽입할 수 있습니다. 예를 들어, 문서에는 [INTRODUCTION] 및 [CONCLUSION] 텍스트가 있는 단락이 포함될 수 있습니다. 하지만 최종 문서에서는 해당 단락을 다른 외부 문서에서 얻은 내용으로 바꿔야 합니다. 이를 위해서는 교체 이벤트에 대한 핸들러를 생성해야 합니다.

다음 코드 예제에서는 대체 이벤트에 대한 처리기를 만들어 나중에 삽입 프로세스에서 사용하는 방법을 보여줍니다

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
private class InsertDocumentAtReplaceHandler : IReplacingCallback
{
ReplaceAction IReplacingCallback.Replacing(ReplacingArgs args)
{
Document subDoc = new Document(MyDir + "Document insertion 2.docx");
// Insert a document after the paragraph, containing the match text.
Paragraph para = (Paragraph)args.MatchNode.ParentNode;
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-.NET.git.
Document mainDoc = new Document(MyDir + "Document insertion 1.docx");
FindReplaceOptions options = new FindReplaceOptions
{
Direction = FindReplaceDirection.Backward,
ReplacingCallback = new InsertDocumentAtReplaceHandler()
};
mainDoc.Range.Replace(new Regex("\\[MY_DOCUMENT\\]"), "", options);
mainDoc.Save(ArtifactsDir + "CloneAndCombineDocuments.InsertDocumentAtReplace.docx");

Mail Merge 작업 중 문서 삽입

mail merge 작업 중에 병합 필드에 문서를 삽입할 수 있습니다. 예를 들어 Mail Merge 템플릿에는 [요약]과 같은 병합 필드가 포함될 수 있습니다. 하지만 최종 문서에서는 다른 외부 문서에서 얻은 콘텐츠를 이 병합 필드에 삽입해야 합니다. 이를 위해서는 병합 이벤트에 대한 핸들러를 생성해야 합니다.

다음 코드 예제에서는 나중에 삽입 프로세스에서 사용할 병합 이벤트에 대한 처리기를 만드는 방법을 보여줍니다

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
private class InsertDocumentAtMailMergeHandler : 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.
void IFieldMergingCallback.FieldMerging(FieldMergingArgs args)
{
if (args.DocumentFieldName == "Document_1")
{
// Use document builder to navigate to the merge field with the specified name.
DocumentBuilder builder = new DocumentBuilder(args.Document);
builder.MoveToMergeField(args.DocumentFieldName);
// The name of the document to load and insert is stored in the field value.
Document subDoc = new Document((string)args.FieldValue);
InsertDocument(builder.CurrentParagraph, subDoc);
// The paragraph that contained the merge field might be empty now, and you probably want to delete it.
if (!builder.CurrentParagraph.HasChildNodes)
builder.CurrentParagraph.Remove();
// Indicate to the mail merge engine that we have inserted what we wanted.
args.Text = null;
}
}
void IFieldMergingCallback.ImageFieldMerging(ImageFieldMergingArgs args)
{
// Do nothing.
}
}

다음 코드 예제에서는 생성된 핸들러를 사용하여 병합 필드에 문서를 삽입하는 방법을 보여줍니다

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document mainDoc = new Document(MyDir + "Document insertion 1.docx");
mainDoc.MailMerge.FieldMergingCallback = 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.MailMerge.Execute(new[] { "Document_1" }, new object[] { MyDir + "Document insertion 2.docx" });
mainDoc.Save(ArtifactsDir + "CloneAndCombineDocuments.InsertDocumentAtMailMerge.doc");

북마크 {#insert-a-document-at-bookmark}에 문서 삽입

텍스트 파일을 문서로 가져와서 문서에 정의한 북마크 바로 뒤에 삽입할 수 있습니다. 이렇게 하려면 문서를 삽입할 북마크된 단락을 만듭니다.

다음 코딩 예제에서는 한 문서의 내용을 다른 문서의 책갈피에 삽입하는 방법을 보여줍니다

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document mainDoc = new Document(MyDir + "Document insertion 1.docx");
Document subDoc = new Document(MyDir + "Document insertion 2.docx");
Bookmark bookmark = mainDoc.Range.Bookmarks["insertionPlace"];
InsertDocument(bookmark.BookmarkStart.ParentNode, subDoc);
mainDoc.Save(ArtifactsDir + "CloneAndCombineDocuments.InsertDocumentAtBookmark.docx");

문서 {#append-a-document} 추가

문서에서 기존 문서 끝까지 추가 페이지를 포함해야 하는 사용 사례가 있을 수 있습니다. 이렇게 하려면 AppendDocument 메서드를 호출하여 다른 문서의 끝에 문서를 추가하면 됩니다.

다음 코드 예제에서는 다른 문서의 끝에 문서를 추가하는 방법을 보여줍니다

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.git.
Document dstDoc = new Document();
dstDoc.FirstSection.Body.AppendParagraph("Destination document text. ");
Document srcDoc = new Document();
srcDoc.FirstSection.Body.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.KeepSourceFormatting);
dstDoc.Save(ArtifactsDir + "JoinAndAppendDocuments.KeepSourceFormatting.docx");

수동으로 노드 가져오기 및 삽입

Aspose.Words를 사용하면 이전 가져오기 요구 사항 없이 자동으로 문서를 삽입하고 추가할 수 있습니다. 그러나 섹션이나 단락과 같은 문서의 특정 노드를 삽입하거나 추가해야 하는 경우 먼저 이 노드를 수동으로 가져와야 합니다.

한 섹션이나 단락을 다른 섹션이나 단락에 삽입하거나 추가해야 하는 경우 기본적으로 ImportNode 방법을 사용하여 첫 번째 문서 노드 트리의 노드를 두 번째 노드로 가져와야 합니다. 노드를 가져온 후 InsertAfter/InsertBefore 방법을 사용하여 참조 노드 앞/뒤에 새 노드를 삽입해야 합니다. 이를 통해 문서에서 노드를 가져와서 지정된 위치에 삽입하여 삽입 프로세스를 사용자 정의할 수 있습니다.

예를 들어 섹션 수준이 아닌 단락 수준에서 콘텐츠를 추가하려는 경우 AppendChild 메서드를 사용하여 하위 노드 목록 끝에 지정된 새 노드를 추가할 수도 있습니다.

다음 코드 예제에서는 InsertAfter 메서드를 사용하여 수동으로 노드를 가져오고 특정 노드 뒤에 삽입하는 방법을 보여줍니다

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-.NET.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.NodeType == NodeType.Paragraph || insertionDestination.NodeType == NodeType.Table)
{
CompositeNode destinationParent = insertionDestination.ParentNode;
NodeImporter importer =
new NodeImporter(docToInsert, insertionDestination.Document, ImportFormatMode.KeepSourceFormatting);
// 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.
foreach (Section srcSection in docToInsert.Sections.OfType<Section>())
foreach (Node srcNode in srcSection.Body)
{
if (srcNode.NodeType == 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 ArgumentException("The destination node should be either a paragraph or table.");
}
}

콘텐츠는 섹션별로 대상 문서 섹션으로 가져옵니다. 즉, 페이지 설정, 머리글 또는 바닥글과 같은 설정이 가져오는 동안 유지됩니다. 문서를 삽입하거나 추가할 때 서식 설정을 정의하여 두 문서를 결합하는 방법을 지정할 수 있다는 점도 알아두면 유용합니다.

문서 삽입 및 추가 {#common-properties-for-insert-and-append-documents}의 공통 속성

InsertDocumentAppendDocument 방법 모두 ImportFormatModeImportFormatOptions를 입력 매개변수로 허용합니다. ImportFormatMode을 사용하면 UseDestinationStyles, KeepSourceFormatting, KeepDifferentStyles와 같은 다양한 형식 모드를 선택하여 한 문서에서 다른 문서로 콘텐츠를 가져올 때 문서 형식이 병합되는 방식을 제어할 수 있습니다. ImportFormatOptions를 사용하면 IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedListsSmartStyleBehavior과 같은 다양한 가져오기 옵션을 선택할 수 있습니다.

Aspose.Words를 사용하면 SectionPageSetup 속성을 사용하여 삽입 또는 추가 작업에서 두 문서를 함께 추가할 때 결과 문서의 시각화를 조정할 수 있습니다. PageSetup 속성에는 SectionStart, RestartPageNumbering, PageStartingNumber, Orientation 등과 같은 섹션의 모든 속성이 포함됩니다. 가장 일반적인 사용 사례는 SectionStart 속성을 설정하여 추가된 콘텐츠가 동일한 페이지에 표시되는지 아니면 새 페이지로 분할되는지 정의하는 것입니다.

다음 코드 예제에서는 콘텐츠가 두 페이지로 분할되지 않도록 하면서 한 문서를 다른 문서에 추가하는 방법을 보여줍니다

// 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 source.docx");
Document dstDoc = new Document(MyDir + "Northwind traders.docx");
// Set the source document to continue straight after the end of the destination document.
srcDoc.FirstSection.PageSetup.SectionStart = SectionStart.Continuous;
// Restart the page numbering on the start of the source document.
srcDoc.FirstSection.PageSetup.RestartPageNumbering = true;
srcDoc.FirstSection.PageSetup.PageStartingNumber = 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.FirstSection.PageSetup.PageWidth = dstDoc.LastSection.PageSetup.PageWidth;
srcDoc.FirstSection.PageSetup.PageHeight = dstDoc.LastSection.PageSetup.PageHeight;
srcDoc.FirstSection.PageSetup.Orientation = dstDoc.LastSection.PageSetup.Orientation;
// Iterate through all sections in the source document.
foreach (Paragraph para in srcDoc.GetChildNodes(NodeType.Paragraph, true))
{
para.ParagraphFormat.KeepWithNext = true;
}
dstDoc.AppendDocument(srcDoc, ImportFormatMode.KeepSourceFormatting);
dstDoc.Save(ArtifactsDir + "JoinAndAppendDocuments.DifferentPageSetup.docx");