Add empty line after word table

Hello,

If there any method can add empty line ( or break line) after table?
Below is what I use to clone table

for (int i = 0; i < tableCount - 1; i++)
{
    Table table = (Table)doc.GetChild(NodeType.Table, 0, true);
    Table tableClone = (Table)table.Clone(true);

    Node node = doc.GetChild(NodeType.Table, i, true).NextSibling;
    DocumentBuilder builder = new DocumentBuilder(doc);
    builder.MoveTo(node);
    builder.InsertParagraph();

    table.ParentNode.InsertAfter(tableClone, table);
}

I will clone multi table, but use InsertAfter will make all table add after another table without any breakline.
How can I solve it?

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

OK,I will try it later.
Thank you.

But I have a question,why I use builder.InsertParagraph will have error log

Cannot insert a node of this type at this location

What different between InsertParagraph and New Paragraph?

@Hankch DocumentBuilder.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");

Got it.
Thanks for clarifying.

1 Like