3

I am trying to create a table with cells width a fixed width.
Let's say I have this code:

$table->addCell(300)->addText('first');
$table->addCell(300)->addText('text that is very looooooooong');

The first cell's 300 width is ignored and is crushed against the left side of the page like this:

f
i
r
s
t

My second cell is going to contain large texts, but I want that cell to maintain it's width.
I couldn't find it anywhere on the web so I am asking if somebody knows what I will have to do here.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
HansElsen
  • 1,639
  • 5
  • 27
  • 47
  • Value `300` is in twips by default, where `1440 twips = 1 inch = 2.54 cm`. You need to either calculate absolute column width against absolute inner page width or set the table to use `percent` units and then use also percent width for columns. See https://phpword.readthedocs.io/en/develop/styles.html#table – lubosdz Jan 29 '23 at 21:49

2 Answers2

4

Remeber that these values are TWIPS and 300 Twips are mere 5mm. Not enough room to hold more than 1 character.

Here is a calculator that helps you to convert values:

Topgrapy Calculator

Also you might use the built in conversion functions in Shared\Font.php like this:

$helper= new PHPWord_Shared_Font();
//convert 5cm to Twips
$inTwips=$helper->centimeterSizeToTwips(5);

I have not tried this so far.

mainguy
  • 8,283
  • 2
  • 31
  • 40
1

I just found out that you have to set style "layout" fixed on your table like below

$fancyTableStyle = [
    'borderSize'  => 6,
    'borderColor' => '000000',
    'cellMargin'  => 80,
    'alignment'   => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER,
    'layout'      => \PhpOffice\PhpWord\Style\Table::LAYOUT_FIXED,
];
$table = $section->addTable($fancyTableStyle);

and then the long word will wrap itself inside the cell.

If you preset a table style on your phpword object, the layout style won't work.

$fancyTableStyleName = 'Fancy Table';
$fancyTableStyle = [
    'borderSize'  => 6,
    'borderColor' => '000000',
    'cellMargin'  => 80,
    'alignment'   => \PhpOffice\PhpWord\SimpleType\JcTable::CENTER,
    'layout'      => \PhpOffice\PhpWord\Style\Table::LAYOUT_FIXED,
];
//table will not be fixed
$table = $section->addTable($fancyTableStyleName);

In ms word you also need to set the autofit option directly on each table, maybe that's why.

robBinlzX
  • 11
  • 1