@Hankch In your case you should create a separator paragraph and insert it after the original table before inserting the cloned table. For example see the following code:
Document doc = new Document(@"C:\Temp\in.docx");
// Get the table that need to be cloned.
Table table = doc.FirstSection.Body.Tables[0];
// Clone the table 10 times.
for (int i = 0; i < 10; i++)
{
// Clone the table.
Table clone = (Table)table.Clone(true);
// Create a separator paragraph.
Paragraph separator = new Paragraph(doc);
// Insert separator paragraph and the cloned table after the original table.
table.ParentNode.InsertAfter(separator, table);
table.ParentNode.InsertAfter(clone, separator);
}
doc.Save(@"C:\Temp\out.docx");
@HankchDocumentBuilder.InsertParagraph inserts a paragraph at the current DocumentBuilder position. In your code, on the first iteration table’s next sibling is a paragraph, but on the second iteration it is a table. This is the reason why exception is thrown. If you would like to use DocumentBuilder, you should modify your code like the following:
Document doc = new Document(@"C:\Temp\in.docx");
DocumentBuilder builder = new DocumentBuilder(doc);
// Get the table that need to be clonned.
Table table = doc.FirstSection.Body.Tables[0];
// Clone the table 10 times.
for (int i = 0; i < 10; i++)
{
// Clone the table.
Table clone = (Table)table.Clone(true);
// Move document builder to the paragraph after the table.
builder.MoveTo(table.NextSibling);
builder.InsertParagraph();
// Insert cloned table after the original table next sibling.
table.ParentNode.InsertAfter(clone, table.NextSibling);
}
doc.Save(@"C:\Temp\out.docx");