Variable Column Widths in Table

I am in the process of attempting to upgrade a project which currently uses a very old version of Aspose.Words (v13!) to use GemBox.Document. This project depends on the ability to have variable numbers and sizes of cells in each row of a table. I’ve included some sample code below using Aspose.Words which achieves the desired behavior:

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

builder.StartTable();

double pageWidth = doc.FirstSection.PageSetup.PageWidth -
				   doc.FirstSection.PageSetup.LeftMargin -
				   doc.FirstSection.PageSetup.RightMargin;

// First row with two 50% width cells
for (int i = 1; i <= 2; i++)
{
	builder.InsertCell();
	builder.CellFormat.Width = pageWidth * 0.5;
	builder.Write($"Cell {i}");
}

builder.EndRow();

// Second row with three 33% width cells
for (int i = 1; i <= 3; i++)
{
	builder.InsertCell();
	builder.CellFormat.Width = pageWidth / 3;
	builder.Write($"Cell {i + 2}");
}

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

Produces the following output document:

I was wondering if anything similar can be achieved using GemBox.Document. I’ve been unable to get this to work using PreferredWidth, as the columns are always the same size between rows, and there ends up being empty space following Cell 2. How can I produce the above layout using GemBox.Document?

Hi Michael,

This can be done with GemBox.Document, but there is no document builder or something similar to create the desired layout for you.

In other words, you’ll need to adjust the column spans depending on your requirements.
So, try something like this:

var document = new DocumentModel();
var section = new Section(document);
document.Sections.Add(section);

double pageWidth = section.PageSetup.PageWidth -
    section.PageSetup.PageMargins.Left -
    section.PageSetup.PageMargins.Right;

var table = new Table(document);
section.Blocks.Add(table);

var firstRow = new TableRow(document);
table.Rows.Add(firstRow);
for (int i = 1; i <= 2; i++)
{
    var cell = new TableCell(document, $"Cell {i}");
    cell.CellFormat.PreferredWidth = new TableWidth(pageWidth * 0.5, TableWidthUnit.Point);
    firstRow.Cells.Add(cell);
}

var secondRow = new TableRow(document);
table.Rows.Add(secondRow);
for (int i = 1; i <= 3; i++)
{
    var cell = new TableCell(document, $"Cell {i + 2}");
    cell.CellFormat.PreferredWidth = new TableWidth(pageWidth / 3, TableWidthUnit.Point);
    secondRow.Cells.Add(cell);
}

// Adjust column spans.
int maxColumns = table.Rows.Max(r => r.Cells.Count) * 2;
foreach (var row in table.Rows)
{
    int remainingColumns = maxColumns;
    for (int cellIndex = 0; cellIndex < row.Cells.Count; cellIndex++)
    {
        int columnSpan = remainingColumns / (row.Cells.Count - cellIndex);
        row.Cells[cellIndex].ColumnSpan = columnSpan;
        remainingColumns -= columnSpan;
    }
}

document.Save("output.docx");

Does this solve your issue?

Regards,
Mario