Belge Ekleme ve Ekleme

Bazen birden fazla belgenin tek bir belgede birleştirilmesi gerekebilir. Bunu manuel olarak yapabileceğiniz gibi Aspose.Words ekleme veya ekleme özelliğini de kullanabilirsiniz.

Ekleme işlemi, önceden oluşturulmuş belgelerin içeriğini yeni veya mevcut bir belgeye eklemenizi sağlar.

Buna karşılık, ekleme özelliği bir belgeyi yalnızca başka bir belgenin sonuna eklemenize olanak tanır.

Bu makalede, bir belgenin diğerine farklı yollarla nasıl ekleneceği veya ekleneceği açıklanmakta ve belge eklerken veya eklerken uygulayabileceğiniz ortak özellikler açıklanmaktadır.

Belge {#insert-a-document} Ekle

Yukarıda belirtildiği gibi, Aspose.Words’te bir belge bir düğüm ağacı olarak temsil edilir ve bir belgeyi diğerine ekleme işlemi, düğümlerin birinci belge ağacından ikincisine kopyalanmasıdır.

Belgeleri çeşitli konumlara farklı şekillerde ekleyebilirsiniz. Örneğin, bir belgeyi değiştirme işlemi yoluyla, birleştirme işlemi sırasında birleştirme alanıyla veya yer işaretiyle ekleyebilirsiniz.

Ayrıca, Microsoft Word’e belge eklemeye benzer olan InsertDocument veya InsertDocumentInline yöntemini de, daha önce herhangi bir içe aktarma işlemi yapmadan belgenin tamamını geçerli imleç konumuna eklemek için kullanabilirsiniz.

Aşağıdaki kod örneği, InsertDocument yöntemini kullanarak belgenin nasıl ekleneceğini gösterir:

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

Aşağıdaki kod örneği, InsertDocumentInline yöntemini kullanarak belgenin nasıl ekleneceğini gösterir:

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

Aşağıdaki alt bölümlerde bir belgeyi diğerine ekleyebileceğiniz seçenekler açıklanmaktadır.

Bul ve Değiştir İşlemi Sırasında Belge Ekleme

Bul ve değiştir işlemlerini gerçekleştirirken belge ekleyebilirsiniz. Örneğin, bir belge [GİRİŞ] ve [SONUÇ] metnini içeren paragraflar içerebilir. Ancak son belgede bu paragrafları başka bir harici belgeden alınan içerikle değiştirmeniz gerekir. Bunu başarmak için, değiştirme olayı için bir işleyici oluşturmanız gerekecektir.

Aşağıdaki kod örneği, değiştirme olayının daha sonra ekleme işleminde kullanılması için bir işleyicinin nasıl oluşturulacağını gösterir:

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

Aşağıdaki kod örneği, bul ve değiştir işlemi sırasında bir belgenin içeriğinin diğerine nasıl ekleneceğini gösterir:

// 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 İşlemi Sırasında Belge Ekleme

mail merge işlemi sırasında birleştirme alanına belge ekleyebilirsiniz. Örneğin, bir Mail Merge şablonu [Özet] gibi bir birleştirme alanı içerebilir. Ancak son belgede, başka bir harici belgeden elde edilen içeriği bu birleştirme alanına eklemeniz gerekir. Bunu başarmak için birleştirme olayı için bir işleyici oluşturmanız gerekecektir.

Aşağıdaki kod örneği, birleştirme olayının daha sonra ekleme işleminde kullanması için bir işleyicinin nasıl oluşturulacağını gösterir:

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

Aşağıdaki kod örneği, oluşturulan işleyiciyi kullanarak birleştirme alanına nasıl belge ekleneceğini gösterir:

// 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} Yer İşaretine Bir Belge Ekleme

Bir metin dosyasını bir belgeye aktarabilir ve belgede tanımladığınız yer işaretinin hemen sonrasına ekleyebilirsiniz. Bunu yapmak için belgenin eklenmesini istediğiniz yere yer imli bir paragraf oluşturun.

Aşağıdaki kodlama örneği, bir belgenin içeriğinin başka bir belgedeki yer imine nasıl ekleneceğini gösterir:

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

Bir Belge {#append-a-document} Ekleme

Bir belgeden mevcut bir belgenin sonuna kadar ek sayfalar eklemenizi gerektiren bir kullanım durumunuz olabilir. Bunu yapmak için, bir belgeyi diğerinin sonuna eklemek için AppendDocument yöntemini çağırmanız yeterlidir.

Aşağıdaki kod örneği, bir belgenin başka bir belgenin sonuna nasıl ekleneceğini gösterir:

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

Düğümleri Manuel Olarak İçe Aktarma ve Ekleme

Aspose.Words, önceden herhangi bir içe aktarma gereksinimi olmadan belgeleri otomatik olarak eklemenize ve eklemenize olanak tanır. Ancak belgenize bölüm veya paragraf gibi belirli bir düğüm eklemeniz veya eklemeniz gerekiyorsa, önce bu düğümü manuel olarak içe aktarmanız gerekir.

Bir bölümü veya paragrafı diğerine eklemeniz veya eklemeniz gerektiğinde, esasen ilk belge düğüm ağacının düğümlerini ImportNode yöntemini kullanarak ikinciye aktarmanız gerekir. Düğümlerinizi içe aktardıktan sonra, referans düğümün arkasına/öncesine yeni bir düğüm eklemek için InsertAfter/InsertBefore yöntemini kullanmanız gerekir. Bu, bir belgeden düğümleri içe aktarıp belirli konumlara ekleyerek ekleme işlemini özelleştirmenize olanak tanır.

Örneğin, içeriği bölüm düzeyi yerine paragraf düzeyinde eklemek istiyorsanız, alt düğümler listesinin sonuna yeni bir belirtilen düğüm eklemek için AppendChild yöntemini de kullanabilirsiniz.

Aşağıdaki kod örneği, düğümlerin manuel olarak nasıl içe aktarılacağını ve bunların InsertAfter yöntemini kullanarak belirli bir düğümden sonra nasıl ekleneceğini gösterir:

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

İçerik, hedef belgeye bölüm bölüm içe aktarılır; bu, sayfa düzeni ve üstbilgiler veya altbilgiler gibi ayarların içe aktarma sırasında korunduğu anlamına gelir. İki belgenin nasıl bir araya getirileceğini belirlemek için bir belge eklediğinizde veya eklerken biçimlendirme ayarlarını tanımlayabileceğinizi de unutmamakta fayda var.

Belge Eklemek ve Eklemek için Ortak Özellikler

Hem InsertDocument hem de AppendDocument yöntemleri, giriş parametreleri olarak ImportFormatMode ve ImportFormatOptions‘i kabul eder. ImportFormatMode, UseDestinationStyles, KeepSourceFormatting ve KeepDifferentStyles gibi farklı format modlarını seçerek bir belgeden diğerine içerik aktardığınızda belge formatının nasıl birleştirileceğini kontrol etmenize olanak tanır. ImportFormatOptions, IgnoreHeaderFooter, IgnoreTextBoxes, KeepSourceNumbering, MergePastedLists ve SmartStyleBehavior gibi farklı içe aktarma seçeneklerini seçmenize olanak tanır.

Aspose.Words, Section ve PageSetup özelliklerini kullanarak bir ekleme veya ekleme işleminde iki belge birbirine eklendiğinde ortaya çıkan belgenin görselleştirmesini ayarlamanıza olanak tanır. PageSetup özelliği bir bölümün SectionStart, RestartPageNumbering, PageStartingNumber, Orientation ve diğerleri gibi tüm niteliklerini içerir. En yaygın kullanım durumu, eklenen içeriğin aynı sayfada mı görüneceğini yoksa yeni bir sayfaya mı bölüneceğini tanımlamak için SectionStart özelliğini ayarlamaktır.

Aşağıdaki kod örneği, içeriğin iki sayfaya bölünmesini önlerken bir belgenin diğerine nasıl ekleneceğini gösterir:

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