Had a similar problem with a parent row containing both a horizontally merged cell and a vertically merged cell.
The following code need to be reviewed and better rewritten, but it works for now.
The following code need to be reviewed and better rewritten, but it works for now.
private void ProcessClosingTableRow(HtmlEnumerator en)
{
if (!tables.HasContext) return;
TableRow row = tables.CurrentTable.GetLastChild<TableRow>();
if (row == null) return;
// Word will not open documents with empty rows (reported by scwebgroup)
if (row.GetFirstChild<TableCell>() == null)
{
row.Remove();
return;
}
// Add empty columns to fill rowspan
if (tables.RowSpan.Count > 0)
{
int rowIndex = tables.CellPosition.Y;
for (int i = 0; i < tables.RowSpan.Count; i++)
{
Point position = tables.RowSpan.Keys[i];
if (position.Y == rowIndex) continue;
//note: incorrect when the row source of the rowspan contains some horizontally spanned cells), position.X can be invalid
//row.InsertAt<TableCell>(new TableCell(new TableCellProperties(
// new VerticalMerge()),
// new Paragraph()),
// position.X);
TableRow spanSourceRow = tables.CurrentTable.ChildElements.OfType<TableRow>().ElementAtOrDefault(position.Y - 1);
int insertPos = position.X;
int gridspan = 0;
if (spanSourceRow != null)
{
int virtualInsertPos = spanSourceRow.ChildElements.OfType<TableCell>().Take(position.X + 1)
.Sum(c =>
{
if (c.TableCellProperties != null && c.TableCellProperties.GridSpan != null && c.TableCellProperties.VerticalMerge == null)
return (int) c.TableCellProperties.GridSpan.Val;
return 1;
}) - 1;
// the destination row can have horizontally merged cells too
int hiddenColumnsCountBeforeInsertPos = 0;
if (virtualInsertPos > 0)
{
int virtualDestInsertPos = 0;
foreach (var c in row.ChildElements.OfType<TableCell>())
{
if (c.TableCellProperties != null && c.TableCellProperties.GridSpan != null)
{
hiddenColumnsCountBeforeInsertPos += (int) c.TableCellProperties.GridSpan.Val - 1;
virtualDestInsertPos += (int) c.TableCellProperties.GridSpan.Val;
}
else
virtualDestInsertPos++;
if (virtualDestInsertPos >= virtualInsertPos)
break;
}
}
insertPos = virtualInsertPos - hiddenColumnsCountBeforeInsertPos;
//report gridspan from the parent cell
var parentCell = spanSourceRow.ChildElements.OfType<TableCell>().Skip(position.X).FirstOrDefault();
if (parentCell != null && parentCell.TableCellProperties != null && parentCell.TableCellProperties.GridSpan != null)
gridspan = parentCell.TableCellProperties.GridSpan.Val;
}
var tcProps = new TableCellProperties();
if (gridspan > 0)
tcProps.AppendChild(new GridSpan() {Val = gridspan});
row.InsertAt<TableCell>(new TableCell(tcProps, new Paragraph()), insertPos);
int span = tables.RowSpan[position];
if (span == 1) { tables.RowSpan.RemoveAt(i); i--; }
else tables.RowSpan[position] = span - 1;
}
}
htmlStyles.Tables.EndTag("<tr>");
htmlStyles.Runs.EndTag("<tr>");
}