Table style

The class TableStyle offer methods to change the properties of the table as a whole, like the width, margin, etc.

To create a TableStyle object, we call the constructor with the table's name as an argument. Then, we can pass it to the table using the method setStyle($style).

$tableStyle = new TableStyle($table->getTableName());
$table->setStyle($tableStyle);

Width

We use the method setWidth($width) to change the width of the table.

$tableStyle->setWidth('14cm');

Note that won't be effective until we specify the widths of each column too, using the class ColumnStyle that we already saw, and the alignment of the table, that will see below.

Alignment

To change the alignment, we use the method setAlignment($align). The possible values are StyleConstants::(LEFT|RIGHT|CENTER|MARGINS)

$tableStyle->setAlignment(StyleConstants::CENTER);

So here is an example to change the width of the table.

$table = new Table('table1');
//create a TableStyle
$tableStyle = new TableStyle($table->getTableName());
//set the width of the table
$tableStyle->setWidth('4cm');
//set the alignment
$tableStyle->setAlignment(StyleConstants::CENTER);

$table->setStyle($tableStyle);

$table->createColumns(2);
//set the width of the columns
$columnStyle1 = $table->getColumnStyle(0);
$columnStyle1->setWidth('2cm');
$columnStyle1 = $table->getColumnStyle(1);
$columnStyle1->setWidth('2cm');
// ...
// add rows 

Margins

To change the margins, we call setHorizontalMargin($marginLeft, $marginRight) for the horizontal margin, and setVerticalMargin($marginTop, $marginBottom) for the vertical one.

$tableStyle->setHorizontalMargin('2cm', '2cm');
$tableStyle->setVerticalMargin('2cm', '2cm');

Background color

We can change the background color of the table, using setBgColor($color).

$tableStyle->setBgColor('#FF0000');

Background image

To set an image as the background of the table, we use setBgImage. This method is similar to the one on the classes RowStyle and CellStyle.

$tableStyle->setBgImage('image.jpeg');

Border model

There are two types of border model:

  • Collapsing border model StyleConstants::COLLAPSING: When two adjacent cells have different borders, the wider border appears as the border between the cells. Each cell receives half of the width of the border.
  • Separating border model StyleConstants::SEPARATING: Borders appear within the cell that specifies the border.
$tableStyle->setBorderModel(StyleConstants::COLLAPSING);

Break before and break after

We can insert a page or column break before or after a table using setBreakBefore($break) or setBreakAfter($break). The value of the $break can be either StyleConstants::PAGE for a page break or StyleConstants::COLUMN for a column break.

$tableStyle->setBreakBefore(StyleConstants::PAGE);

Note that you should not call the two methods on the same table.