Sisipkan dan Lampirkan Dokumen
Terkadang diperlukan untuk menggabungkan beberapa dokumen menjadi satu. Anda dapat melakukan ini secara manual atau Anda dapat menggunakan fitur penyisipan atau penambahan Aspose.Words.
Operasi penyisipan memungkinkan Anda memasukkan konten dokumen yang dibuat sebelumnya ke dalam dokumen baru atau yang sudah ada.
Pada gilirannya, fitur tambahkan 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.
Masukkan Dokumen
Seperti disebutkan di atas, di Aspose.Words, sebuah dokumen direpresentasikan sebagai pohon node, dan operasi memasukkan satu dokumen ke dokumen lain adalah menyalin node dari pohon dokumen pertama ke pohon dokumen kedua.
Anda dapat menyisipkan dokumen di berbagai lokasi dengan cara berbeda. Misalnya, Anda bisa menyisipkan dokumen melalui operasi penggantian, bidang penggabungan selama operasi penggabungan, atau melalui penanda.
Anda juga dapat menggunakan metode InsertDocument atau InsertDocumentInline, yang mirip dengan menyisipkan dokumen dalam Microsoft Word, untuk menyisipkan seluruh dokumen pada posisi kursor saat ini tanpa perlu mengimpor 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-.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"); |
Contoh kode berikut menunjukkan cara menyisipkan dokumen menggunakan metode 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()); |
Subbagian berikut menjelaskan opsi di mana Anda dapat menyisipkan satu dokumen ke dokumen lain.
Masukkan Dokumen Selama Operasi Temukan dan Ganti
Anda dapat menyisipkan dokumen saat melakukan operasi pencarian dan penggantian. Misalnya, sebuah dokumen dapat berisi paragraf dengan teks [PENDAHULUAN] dan [KESIMPULAN]. Namun di dokumen akhir, Anda perlu mengganti paragraf tersebut dengan konten yang diperoleh dari dokumen eksternal lain. Untuk mencapai hal tersebut, Anda perlu membuat handler untuk event replace.
Contoh kode berikut menunjukkan cara membuat handler untuk event pengganti untuk digunakan nanti dalam proses penyisipan:
// 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; | |
} | |
} |
Contoh kode berikut menunjukkan cara memasukkan konten dari satu dokumen ke dokumen lain selama operasi pencarian dan penggantian:
// 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"); |
Masukkan Dokumen Selama Operasi Mail Merge
Anda dapat menyisipkan dokumen ke dalam bidang gabungan selama operasi mail merge. Misalnya, templat Mail Merge bisa berisi bidang gabungan seperti [Ringkasan]. Namun di dokumen akhir, Anda perlu memasukkan konten yang diperoleh dari dokumen eksternal lain ke dalam bidang gabungan ini. Untuk mencapai hal tersebut, Anda perlu membuat handler untuk acara penggabungan.
Contoh kode berikut menunjukkan cara membuat handler 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-.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. | |
} | |
} |
Contoh kode berikut menunjukkan cara menyisipkan dokumen ke dalam bidang gabungan menggunakan pengendali yang dibuat:
// 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"); |
Masukkan Dokumen di Bookmark
Anda dapat mengimpor file teks ke dalam dokumen dan menyisipkannya tepat setelah penanda yang telah Anda tetapkan dalam dokumen. Untuk melakukan ini, buat paragraf yang diberi bookmark di mana Anda ingin dokumen disisipkan.
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-.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"); |
Tambahkan Dokumen
Anda mungkin memiliki kasus penggunaan di mana Anda perlu menyertakan halaman tambahan dari dokumen ke akhir dokumen yang sudah 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-.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"); |
Impor dan Sisipkan Node Secara Manual
Aspose.Words memungkinkan Anda menyisipkan dan menambahkan dokumen secara otomatis tanpa persyaratan impor sebelumnya. Namun, jika Anda perlu menyisipkan atau menambahkan simpul tertentu pada dokumen Anda, seperti bagian atau paragraf, Anda harus mengimpor simpul tersebut secara manual terlebih dahulu.
Saat Anda perlu menyisipkan atau menambahkan satu bagian atau paragraf ke bagian atau paragraf lainnya, pada dasarnya Anda perlu mengimpor node dari pohon simpul dokumen pertama ke bagian atau paragraf kedua menggunakan metode ImportNode. Setelah mengimpor node, Anda perlu menggunakan metode InsertAfter/InsertBefore untuk memasukkan node baru setelah/sebelum node referensi. Hal ini memungkinkan Anda untuk menyesuaikan proses penyisipan dengan mengimpor node dari dokumen dan menyisipkannya pada posisi tertentu.
Anda juga dapat menggunakan metode AppendChild untuk menambahkan simpul baru yang ditentukan ke akhir daftar simpul anak, misalnya, jika Anda ingin menambahkan konten di tingkat paragraf, bukan di tingkat bagian.
Contoh kode berikut menunjukkan cara mengimpor node secara manual dan menyisipkannya setelah node tertentu menggunakan metode 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."); | |
} | |
} |
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
Metode InsertDocument dan AppendDocument menerima ImportFormatMode dan ImportFormatOptions sebagai parameter masukan. ImportFormatMode memungkinkan Anda mengontrol bagaimana pemformatan dokumen digabungkan saat Anda mengimpor konten dari satu dokumen ke dokumen lain dengan memilih mode format 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 ketika dua dokumen ditambahkan bersama dalam operasi penyisipan atau penambahan dengan menggunakan properti Section dan PageSetup. Properti PageSetup berisi semua atribut suatu bagian seperti SectionStart, RestartPageNumbering, PageStartingNumber, Orientation, dan lain-lain. Kasus penggunaan yang paling umum adalah menyetel properti SectionStart untuk menentukan apakah konten yang ditambahkan akan muncul di halaman yang sama atau dipecah menjadi halaman baru.
Contoh kode berikut menunjukkan cara menambahkan satu dokumen ke dokumen lain sambil menjaga agar konten tidak terpecah menjadi dua halaman:
// 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"); |