Cloning Elements in DOCX Files
The following example shows how you can clone document elements (Section
and Paragraph
) together with their content (their descendant elements) using the GemBox.Document library.
using GemBox.Document;
using System.Linq;
class Program
{
static void Main()
{
// If using the Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY");
var document = DocumentModel.Load("%InputFileName%");
// Get first Section element.
var section = document.Sections[0];
// Get first Paragraph element.
var paragraph = section.Blocks.OfType<Paragraph>().First();
// Clone paragraph and add it to section.
var cloneParagraph = paragraph.Clone(true);
section.Blocks.Add(cloneParagraph);
// Clone section and add it to document.
var cloneSection = section.Clone(true);
document.Sections.Add(cloneSection);
document.Save("Cloning.%OutputFileType%");
}
}
Imports GemBox.Document
Imports System.Linq
Module Program
Sub Main()
' If using the Professional version, put your serial key below.
ComponentInfo.SetLicense("FREE-LIMITED-KEY")
Dim document = DocumentModel.Load("%InputFileName%")
' Get first Section element.
Dim section = document.Sections(0)
' Get first Paragraph element.
Dim paragraph = section.Blocks.OfType(Of Paragraph).First()
' Clone paragraph and add it to section.
Dim cloneParagraph = paragraph.Clone(True)
section.Blocks.Add(cloneParagraph)
' Clone section and add it to document.
Dim cloneSection = section.Clone(True)
document.Sections.Add(cloneSection)
document.Save("Cloning.%OutputFileType%")
End Sub
End Module

If you want to insert an element into another document, then you'll need to use one of the DocumentModel.Import
methods as shown in the Combining example.
When you want to generate multiple documents from the same document, you can use the DocumentModel.Clone
method to perform a deep copy of the document.
By creating multiple document copies you're avoiding the need to load and parse the document from a file or a stream each time and thus improve the performance of document generation.