Free Support Forum - aspose.com

Change cell width

Hi,

I’m trying to change the width of cells and I ran into a problem.

A table is inserted into a document via insertHtml(String).
Then the width of the cells is changed. The changes are displayed correctly in the saved document.

However, if I insert the same table within another table using insertHtml(String) and change the width of the cell, the changes are not displayed correctly. Other changed properties (e.g. vertical alignment) are displayed correctly.

The source code:

DocumentBuilder builder = new DocumentBuilder();

String htmlTable = "<table width=\"200\">"
        + "<tr>"
        + "<td height=\"100\">50</td>"
        + "<td>150</td>"
        + "</tr>"
        + "<tr>"
        + "<td height=\"100\">150</td>"
        + "<td>50</td>"
        + "</tr>"
        + "</table>";

builder.insertHtml(htmlTable);

// get table inserted using HTML
Table table = builder.getDocument().getSections().get(0).getBody().getTables().get(0);
table.getRows().get(0).getCells().get(0).getCellFormat().setWidth(50);
table.getRows().get(0).getCells().get(0).getCellFormat().setVerticalAlignment(3);
table.getRows().get(0).getCells().get(1).getCellFormat().setWidth(150);
table.getRows().get(1).getCells().get(0).getCellFormat().setWidth(150);
table.getRows().get(1).getCells().get(1).getCellFormat().setWidth(50);

builder.insertParagraph();

builder.startTable();
Cell cell = builder.insertCell();
builder.insertHtml(htmlTable);
builder.endRow();
builder.endTable();

// get table inserted in cell using HTML
table = cell.getTables().get(0);
table.getRows().get(0).getCells().get(0).getCellFormat().setWidth(50);
table.getRows().get(0).getCells().get(0).getCellFormat().setVerticalAlignment(3); // is set
table.getRows().get(0).getCells().get(1).getCellFormat().setWidth(150);
table.getRows().get(1).getCells().get(0).getCellFormat().setWidth(150);
table.getRows().get(1).getCells().get(1).getCellFormat().setWidth(50);

builder.getDocument().save("...\\result.docx");

The result looks like this: result.png (5.8 KB)

Testet with Aspose Words 18.4

Is there an explanation for this behaviour? Have I missed anything here?
Many greetings
Ingo Gutzeit

@gutzeit,

Thanks for your inquiry. Please use the Table.setPreferredWidth and Table.autoFit methods as shown below to get the desired output.

table.getRows().get(0).getCells().get(0).getCellFormat().setWidth(50);
table.getRows().get(0).getCells().get(0).getCellFormat().setVerticalAlignment(3); // is set
table.getRows().get(0).getCells().get(1).getCellFormat().setWidth(150);
table.getRows().get(1).getCells().get(0).getCellFormat().setWidth(150);
table.getRows().get(1).getCells().get(1).getCellFormat().setWidth(50);

table.setPreferredWidth(PreferredWidth.fromPoints(150));
table.autoFit(AutoFitBehavior.FIXED_COLUMN_WIDTHS);

That solves my problem. Thank you very much.

@gutzeit,

Please feel free to ask if you have any question about Aspose.Words, we will be happy to help you.