Menyisipkan dan Menambahkan Dokumen

Terkadang diperlukan untuk menggabungkan beberapa dokumen menjadi satu. Anda dapat melakukannya secara manual atau menggunakan fitur Aspose.Words insert atau append.

Operasi penyisipan memungkinkan Anda memasukkan konten dokumen yang dibuat sebelumnya ke dalam dokumen baru atau yang sudah ada.

Pada gilirannya, fitur append memungkinkan Anda menambahkan dokumen hanya di akhir dokumen lain.

Artikel ini menjelaskan cara menyisipkan atau menambahkan dokumen ke dokumen lain dengan berbagai cara dan menjelaskan properti umum yang dapat Anda terapkan saat menyisipkan atau menambahkan dokumen.

Menyisipkan Dokumen

Seperti disebutkan di atas, dalam Aspose.Words sebuah dokumen direpresentasikan sebagai pohon simpul, dan operasi memasukkan satu dokumen ke dokumen lainnya adalah menyalin simpul dari pohon dokumen pertama ke pohon dokumen kedua.

Anda dapat menyisipkan dokumen di berbagai lokasi dengan berbagai cara. Misalnya, Anda dapat menyisipkan dokumen melalui operasi replace, bidang gabungan selama operasi penggabungan, atau melalui bookmark.

Anda juga dapat menggunakan metode InsertDocument, yang mirip dengan menyisipkan dokumen di Microsoft Word, untuk menyisipkan seluruh dokumen pada posisi kursor saat ini tanpa pengimporan sebelumnya.

Contoh kode berikut menunjukkan cara menyisipkan dokumen menggunakan metode 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");

Subbagian berikut menjelaskan opsi di mana Anda dapat menyisipkan satu dokumen ke dokumen lainnya.

Sisipkan Dokumen Selama Operasi Temukan dan Ganti

Anda dapat menyisipkan dokumen saat melakukan operasi temukan dan ganti. Misalnya, dokumen dapat berisi paragraf dengan teks [INTRODUCTION] dan [CONCLUSION]. Namun di dokumen akhir, Anda perlu mengganti paragraf tersebut dengan konten yang diperoleh dari dokumen eksternal lain. Untuk mencapainya, Anda perlu membuat penangan untuk acara replace.

Contoh kode berikut menunjukkan cara membuat pengendali untuk peristiwa penggantian untuk digunakan nanti dalam proses penyisipan:

// 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;
}
};

Contoh kode berikut menunjukkan caranya menyisipkan konten dari satu dokumen ke dokumen lainnya selama operasi temukan dan ganti:

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

Menyisipkan Dokumen Selama Operasi Mail Merge

Anda dapat menyisipkan dokumen ke dalam bidang gabungan selama operasi mail merge. Misalnya, templat Mail Merge dapat berisi bidang gabungan seperti [Ringkasan]. Namun di dokumen akhir, Anda perlu menyisipkan konten yang diperoleh dari dokumen eksternal lain ke dalam bidang penggabungan ini. Untuk mencapainya, Anda perlu membuat pengendali untuk acara penggabungan.

Contoh kode berikut menunjukkan cara membuat pengendali untuk peristiwa penggabungan untuk digunakan nanti dalam proses penyisipan:

// 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.
}
};

Contoh kode berikut menunjukkan cara menyisipkan dokumen ke dalam bidang gabungan menggunakan penangan yang dibuat:

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

Sisipkan Dokumen di Bookmark

Anda dapat mengimpor file teks ke dalam dokumen dan menyisipkannya tepat setelah penanda yang telah Anda tentukan dalam dokumen. Untuk melakukannya, buat paragraf yang ditandai di tempat Anda ingin menyisipkan dokumen.

Contoh pengkodean berikut menunjukkan cara menyisipkan konten satu dokumen ke bookmark di dokumen lain:

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

Tambahkan Dokumen

Anda mungkin memiliki kasus penggunaan di mana Anda perlu menyertakan halaman tambahan dari dokumen hingga akhir dokumen yang ada. Untuk melakukan ini, Anda hanya perlu memanggil metode AppendDocument untuk menambahkan dokumen ke akhir dokumen lainnya.

Contoh kode berikut menunjukkan cara menambahkan dokumen ke akhir dokumen lain:

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

Impor dan Sisipkan Simpul Secara Manual

Aspose.Words memungkinkan Anda menyisipkan dan menambahkan dokumen secara otomatis tanpa persyaratan pengimporan sebelumnya. Namun, jika Anda perlu menyisipkan atau menambahkan simpul tertentu dari dokumen Anda, seperti bagian atau paragraf, maka pertama-tama Anda perlu mengimpor simpul ini secara manual.

Saat Anda perlu menyisipkan atau menambahkan satu bagian atau paragraf ke bagian lainnya, pada dasarnya Anda perlu mengimpor simpul dari pohon simpul dokumen pertama ke simpul kedua menggunakan metode ImportNode. Setelah mengimpor node Anda, Anda perlu menggunakan metode InsertAfter/InsertBefore untuk menyisipkan node baru setelah / sebelum node referensi. Ini memungkinkan Anda untuk menyesuaikan proses penyisipan dengan mengimpor simpul dari dokumen dan memasukkannya pada posisi tertentu.

Anda juga dapat menggunakan metode AppendChild untuk menambahkan simpul baru yang ditentukan ke akhir daftar simpul turunan, misalnya, jika Anda ingin menambahkan konten di tingkat paragraf, bukan di tingkat bagian.

Contoh kode berikut menunjukkan cara mengimpor node secara manual dan memasukkannya setelah node tertentu menggunakan metode 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.");
}
}

Konten diimpor ke dokumen tujuan bagian demi bagian, yang berarti bahwa pengaturan, seperti pengaturan halaman dan header atau footer, dipertahankan selama impor. Penting juga untuk dicatat bahwa Anda dapat menentukan pengaturan pemformatan saat Anda menyisipkan atau menambahkan dokumen untuk menentukan bagaimana dua dokumen digabungkan.

Properti Umum untuk Menyisipkan dan Menambahkan Dokumen

Keduanya InsertDocument dan AppendDocument metode menerima ImportFormatMode dan ImportFormatOptions sebagai parameter masukan. ImportFormatMode memungkinkan Anda mengontrol bagaimana pemformatan dokumen digabungkan saat Anda mengimpor konten dari satu dokumen ke dokumen lainnya dengan memilih mode format yang berbeda seperti UseDestinationStyles, KeepSourceFormatting, dan KeepDifferentStyles. ImportFormatOptions memungkinkan Anda memilih opsi impor yang berbeda seperti IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists, dan SmartStyleBehavior.

Aspose.Words memungkinkan Anda menyesuaikan visualisasi dokumen yang dihasilkan saat dua dokumen dijumlahkan dalam operasi sisipkan atau tambahkan dengan menggunakan properti Section dan PageSetup. Properti PageSetup berisi semua atribut bagian seperti SectionStart, RestartPageNumbering, PageStartingNumber, Orientation, dan lainnya. Kasus penggunaan yang paling umum adalah menyetel properti SectionStart untuk menentukan apakah konten yang ditambahkan akan muncul di halaman yang sama atau dipecah menjadi yang baru.

Contoh kode berikut menunjukkan cara menambahkan satu dokumen ke dokumen lainnya sambil menjaga konten agar tidak terbagi menjadi dua halaman:

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