문서 삽입 및 추가

때로는 여러 문서를 하나로 결합 할 필요가 있습니다. 이 작업을 수동으로 수행하거나 다음을 사용할 수 있습니다 Aspose.Words 기능을 삽입 또는 추가합니다.

삽입 작업을 사용하면 이전에 만든 문서의 내용을 새 문서 또는 기존 문서에 삽입 할 수 있습니다.

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

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

문서 삽입

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

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

당신은 또한 사용할 수 있습니다 InsertDocument 에 문서를 삽입하는 것과 유사한 방법 Microsoft Word,이전 가져오기 없이 현재 커서 위치에 전체 문서를 삽입합니다.

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto srcDoc = MakeObject<Document>(MyDir + u"Document source.docx");
auto dstDoc = MakeObject<Document>(MyDir + u"Northwind traders.docx");
auto builder = MakeObject<DocumentBuilder>(dstDoc);
builder->MoveToDocumentEnd();
builder->InsertBreak(BreakType::PageBreak);
builder->InsertDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
builder->get_Document()->Save(ArtifactsDir + u"JoinAndAppendDocuments.InsertDocument.docx");

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

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

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
class InsertDocumentAtReplaceHandler : public IReplacingCallback
{
private:
ReplaceAction Replacing(SharedPtr<ReplacingArgs> args) override
{
auto subDoc = MakeObject<Document>(MyDir + u"Document insertion 2.docx");
// Insert a document after the paragraph, containing the match text.
auto para = System::ExplicitCast<Paragraph>(args->get_MatchNode()->get_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-C.git.
auto mainDoc = MakeObject<Document>(MyDir + u"Document insertion 1.docx");
// Set find and replace options.
auto options = MakeObject<FindReplaceOptions>();
options->set_Direction(FindReplaceDirection::Backward);
options->set_ReplacingCallback(MakeObject<CloneAndCombineDocuments::InsertDocumentAtReplaceHandler>());
// Call the replace method.
mainDoc->get_Range()->Replace(MakeObject<System::Text::RegularExpressions::Regex>(u"\\[MY_DOCUMENT\\]"), u"", options);
mainDoc->Save(ArtifactsDir + u"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-C.git.
class InsertDocumentAtMailMergeHandler : public IFieldMergingCallback
{
private:
void FieldMerging(SharedPtr<FieldMergingArgs> args) override
{
if (args->get_DocumentFieldName() == u"Document_1")
{
// Use document builder to navigate to the merge field with the specified name.
auto builder = MakeObject<DocumentBuilder>(args->get_Document());
builder->MoveToMergeField(args->get_DocumentFieldName());
// The name of the document to load and insert is stored in the field value.
auto subDoc = MakeObject<Document>(System::ObjectExt::Unbox<String>(args->get_FieldValue()));
InsertDocument(builder->get_CurrentParagraph(), subDoc);
// The paragraph that contained the merge field might be empty now, and you probably want to delete it.
if (!builder->get_CurrentParagraph()->get_HasChildNodes())
{
builder->get_CurrentParagraph()->Remove();
}
// Indicate to the mail merge engine that we have inserted what we wanted.
args->set_Text(nullptr);
}
}
void ImageFieldMerging(SharedPtr<ImageFieldMergingArgs> args) override
{
ASPOSE_UNUSED(args);
// Do nothing.
}
};

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto mainDoc = MakeObject<Document>(MyDir + u"Document insertion 1.docx");
mainDoc->get_MailMerge()->set_FieldMergingCallback(MakeObject<CloneAndCombineDocuments::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->get_MailMerge()->Execute(MakeArray<String>({u"Document_1"}),
MakeArray<SharedPtr<System::Object>>({System::ObjectExt::Box<String>(MyDir + u"Document insertion 2.docx")}));
mainDoc->Save(ArtifactsDir + u"CloneAndCombineDocuments.InsertDocumentAtMailMerge.doc");

책갈피에 문서 삽입

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto mainDoc = MakeObject<Document>(MyDir + u"Document insertion 1.docx");
auto subDoc = MakeObject<Document>(MyDir + u"Document insertion 2.docx");
SharedPtr<Bookmark> bookmark = mainDoc->get_Range()->get_Bookmarks()->idx_get(u"insertionPlace");
InsertDocument(bookmark->get_BookmarkStart()->get_ParentNode(), subDoc);
mainDoc->Save(ArtifactsDir + u"CloneAndCombineDocuments.InsertDocumentAtBookmark.docx");

문서 추가

문서에서 기존 문서의 끝까지 추가 페이지를 포함해야 하는 사용 사례가 있을 수 있습니다. 이 작업을 수행하려면,당신은 단지 호출 할 필요가 AppendDocument 다른 문서의 끝에 문서를 추가하는 방법.

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto dstDoc = MakeObject<Document>();
dstDoc->get_FirstSection()->get_Body()->AppendParagraph(u"Destination document text. ");
auto srcDoc = MakeObject<Document>();
srcDoc->get_FirstSection()->get_Body()->AppendParagraph(u"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 + u"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-C.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>
static void InsertDocument(SharedPtr<Node> insertionDestination, SharedPtr<Document> docToInsert)
{
if (insertionDestination->get_NodeType() == NodeType::Paragraph || insertionDestination->get_NodeType() == NodeType::Table)
{
SharedPtr<CompositeNode> destinationParent = insertionDestination->get_ParentNode();
auto importer = MakeObject<NodeImporter>(docToInsert, insertionDestination->get_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.
for (const auto& srcSection : System::IterateOver(docToInsert->get_Sections()->LINQ_OfType<SharedPtr<Section>>()))
{
for (const auto& srcNode : System::IterateOver(srcSection->get_Body()))
{
if (srcNode->get_NodeType() == NodeType::Paragraph)
{
auto para = System::ExplicitCast<Paragraph>(srcNode);
if (para->get_IsEndOfSection() && !para->get_HasChildNodes())
{
continue;
}
}
SharedPtr<Node> newNode = importer->ImportNode(srcNode, true);
destinationParent->InsertAfter(newNode, insertionDestination);
insertionDestination = newNode;
}
}
}
else
{
throw System::ArgumentException(u"The destination node should be either a paragraph or table.");
}
}

즉,페이지 설정,머리글 또는 바닥글과 같은 설정이 가져오는 동안 유지됩니다. 또한 문서를 삽입하거나 추가할 때 서식 설정을 정의하여 두 문서를 함께 결합하는 방법을 지정할 수 있습니다.

문서 삽입 및 추가에 대한 공통 속성

둘 다 InsertDocument 그리고 AppendDocument 메서드 수락 ImportFormatMode 그리고 ImportFormatOptions 입력 매개 변수로. 그 ImportFormatMode 다음과 같은 다른 형식 모드를 선택하여 한 문서에서 다른 문서로 콘텐츠를 가져올 때 문서 서식이 병합되는 방법을 제어할 수 있습니다 UseDestinationStyles, KeepSourceFormatting,그리고 KeepDifferentStyles. 그 ImportFormatOptions 다음과 같은 다양한 가져오기 옵션을 선택할 수 있습니다 IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists,그리고 SmartStyleBehavior.

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

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

// For complete examples and data files, please go to https://github.com/aspose-words/Aspose.Words-for-C.git.
auto srcDoc = MakeObject<Document>(MyDir + u"Document source.docx");
auto dstDoc = MakeObject<Document>(MyDir + u"Northwind traders.docx");
// Set the source document to continue straight after the end of the destination document.
srcDoc->get_FirstSection()->get_PageSetup()->set_SectionStart(SectionStart::Continuous);
// Restart the page numbering on the start of the source document.
srcDoc->get_FirstSection()->get_PageSetup()->set_RestartPageNumbering(true);
srcDoc->get_FirstSection()->get_PageSetup()->set_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->get_FirstSection()->get_PageSetup()->set_PageWidth(dstDoc->get_LastSection()->get_PageSetup()->get_PageWidth());
srcDoc->get_FirstSection()->get_PageSetup()->set_PageHeight(dstDoc->get_LastSection()->get_PageSetup()->get_PageHeight());
srcDoc->get_FirstSection()->get_PageSetup()->set_Orientation(dstDoc->get_LastSection()->get_PageSetup()->get_Orientation());
// Iterate through all sections in the source document.
for (const auto& para : System::IterateOver<Paragraph>(srcDoc->GetChildNodes(NodeType::Paragraph, true)))
{
para->get_ParagraphFormat()->set_KeepWithNext(true);
}
dstDoc->AppendDocument(srcDoc, ImportFormatMode::KeepSourceFormatting);
dstDoc->Save(ArtifactsDir + u"JoinAndAppendDocuments.DifferentPageSetup.docx");