Free Support Forum - aspose.com

Set table and cell width to document's page width

I’m using the latest version of Aspose Words for Java and document builder to create tables.

The tables all have different left indent values but I need the Right part of the table NOT to exceed the page width.

I searched and tried various versions of autofit, cell width, table width but nothing seems to alter the length of the table cell.

Here is the code:

		    builder.writeln("");

    		Table wordTable = builder.startTable();
			
    		
    		
    		
    			if(textType.equalsIgnoreCase("Text")){
    				
    				builder.insertCell();
		    		//Set margin and autofit

    				builder.getCellFormat().setWidth(300);
    				
	    			
		    		builder.getRowFormat().setHeight(25);

		    		builder.endRow();
		    		
		    		wordTable.setLeftIndent(setLeftMarginValue(leftPrintMargin, "Text"));

builder.endTable();

Here is an example of the word document output and how I need it to line up

image.png (22.8 KB)

@paul.calhoun,

Thanks for your inquiry. Please refer to the following article.
Specifying Table and Cell Widths

In your case, we suggest you please set the table’s width in points as shown in following code example. Hope this helps you.

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

// We call this method to start building the table.
Table table = builder.startTable();
builder.insertCell();
table.setLeftIndent(50);
builder.getCellFormat().setWidth(300);
builder.write("Row 1, Cell 1 Content.");

builder.endRow();
builder.endTable();
table.setPreferredWidth(PreferredWidth.fromPoints(300));

builder.writeln();

// We call this method to start building the table.
Table table2 = builder.startTable();
builder.insertCell();
table2.setLeftIndent(250);
double cellwidth = builder.getPageSetup().getPageWidth() -table2.getLeftIndent()
        -builder.getPageSetup().getLeftMargin() - builder.getPageSetup().getRightMargin();
System.out.println(cellwidth);
builder.getCellFormat().setWidth(cellwidth);
builder.write("Second table. Row 1, Cell 1 Content.");
builder.endRow();
builder.endTable();

table2.setPreferredWidth(PreferredWidth.fromPoints(cellwidth));

builder.writeln();
Table table3 = builder.startTable();
builder.insertCell();
table3.setLeftIndent(300);
cellwidth = builder.getPageSetup().getPageWidth() -table3.getLeftIndent()
        -builder.getPageSetup().getLeftMargin() - builder.getPageSetup().getRightMargin();
System.out.println(cellwidth);
builder.getCellFormat().setWidth(cellwidth);
builder.write("Third table. Row 1, Cell 1 Content.");
builder.endRow();
builder.endTable();

table3.setPreferredWidth(PreferredWidth.fromPoints(cellwidth));
// Save the document to disk.
doc.save(MyDir + "18.4.docx");