Problems removing empty paragraphs in table cells

Hi,


I need to generate a document which contains a table which contents are converted from HTML. In general this is successful but depending on the piece of HTML that is inserted in the table cells, the DocumentBuilder.InsertHtml method will add empty paragraphs at the end of the text. I included a snippet of code below with comments where the code will break. I included a sample of a document, if I leave the parts out to delete the last empty paragraph in the document, generated with the original content and a corrected version of it. Do you have any guidance on how I could fix this problem?

Thanks in advance,
Steven


Snippet:

string htmlContent1 = @β€œThis one is ok”;
string htmlContent2 = @β€œ

This one is not ok

”;
string htmlContent3 = @β€œ

This one

is also wrong

”;

DocumentBuilder builder = new DocumentBuilder();

Table table = builder.StartTable();
Cell cell0 = builder.InsertCell();
builder.InsertHtml(htmlContent1, true);
if (cell0.LastParagraph != null) // Will evaluate as false since the inserted HTML won’t create an empty paragraph at the end
{
if (cell0.LastParagraph.ToString(SaveFormat.Text).Trim() == β€œβ€)
{
cell0.LastParagraph.Remove();
}
}
builder.EndRow();

Cell cell1= builder.InsertCell();
builder.InsertHtml(htmlContent2, true);
if (cell1.LastParagraph != null) // Will evaluate as true since the inserted HTML will create an empty paragraph at the end
{
if (cell1.LastParagraph.ToString(SaveFormat.Text).Trim() == β€œβ€)
{
cell1.LastParagraph.Remove();
}
}
builder.EndRow();

Cell cell2 = builder.InsertCell(); // Throws a NullRef Exception
builder.InsertHtml(htmlContent3, true);
if (cell2.LastParagraph != null)
{
if (cell2.LastParagraph.ToString(SaveFormat.Text).Trim() == β€œβ€)
{
cell2.LastParagraph.Remove();
}
}

builder.EndRow();
builder.EndTable();



Found the solution on my own in the end. If you perform builder.MoveToDocumentEnd(); right after you remove the last paragraph in a cell then it won’t throw the exception anymore.

1 Like

Hi Steven,


Thanks for your inquiry. It is nice to hear from you that you have found the solution of your issue. Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.

Thanks! You make my day!