Insert Table at ContentPosition

In our application we are using a RegEx to locate a ContentRange. We remove the text at that range and then at the range Start we insert a Table:

var position = range.LoadText(string.Empty).Start;
position.InsertRange(table.Content);

Viewing the resulting DOCX on a desktop version of Word generally looks fine. But trying to edit it at Word online (https://word.cloud.microsoft/) the tables are very narrow and squished:

It seems this method of inserting a table at a random location isn’t well supported by Microsoft. Is there a better way for us to do something like this?

For reference, here is what the document looked like before the “tokens” were replaced:

Hi,

I believe the problem occurs because the inserted table is missing column information.

Can you please share how you’re generating the table object?

Regards,
Mario

This is a simplified version of the what the code is for the the first example in the screenshot:

var table = new Table(documentModel);

var row = new TableRow(documentModel)
{
	RowFormat = { AllowBreakAcrossPages = false }
};
table.Rows.Add(row);

var cellFormat = new TableCellFormat
{
	VerticalAlignment = VerticalAlignment.Center,
	Padding = new Padding(0, 0, 8, 0, LengthUnit.Pixel),
};
cellFormat.Borders.SetBorders(MultipleBorderTypes.All, BorderStyle.None, GemBox.Document.Color.Empty, 0);
var cell = new TableCell(documentModel)
{
	CellFormat = cellFormat
};
row.Cells.Add(cell);

var textParagraph = new Paragraph(documentModel);
textParagraph.Content.LoadText("Corporate");
cell.Blocks.Add(textParagraph);

Yes, the issue is with the missing cell or column width. The online version requires you to specify this value.

For that simplified version, try this:

var table = new Table(documentModel);
table.Columns.Add(new TableColumn(60));
// ...

An alternative that you might try is to use this:

documentModel.GetPaginator(new PaginatorOptions() { UpdateTableCellWidths = true, UpdateTableColumnWidths = true });

This will calculate the cell and column widths based on GemBox.Document’s rendering engine, which might be slightly different from what Microsoft Word’s rendering engine calculates.

Regards,
Mario

Thanks! I will try that out. What is the unit for the TableColumn() preferredWidth? Percentage? Points?

It’s points, please check TableColumn.PreferredWidth.

Also, as an FYI, on cells you can specify width in points or percentages, see TableCell.CellFormat.PreferredWidth.