Search code examples
phpms-wordphpdocx

Centre Table In PHPDOCX


I am dynamically creating a msword document in PHP using PHPDocx (free version).

I am having trouble get a table to centre align in the page. I have tried passing in the style parameters as stated in the documentation, but no joy.

Any ideas on how to fix this?

My current code is;

$docx = new CreateDocx();

$valuesTable = array(
    array(
        11,
        12
    ),
    array(
        21,
        22
    ),
);

$paramsTable = array(
    'jc' => 'center',
    'border' => 'single',
    'border_sz' => 20
);

$docx->addTable($valuesTable, $paramsTable);

$docx->createDocx('example_table');

Solution

  • I had the same problem. If you looking at CreateTable source you can see that method for aligning generateJC() is never called so passing a 'jc' parameter has no effect (this is the same with most of the options).

    You can override this creating a new class like:

    class SmCreateTable extends CreateTable{
        public function createTable()
        {
            $this->_xml = '';
            $args = func_get_args();
    
            if (is_array($args[0])) {
                $this->generateTBL();
                $this->generateTBLPR();
    
                if(!empty($args[1]['jc'])){
                    $this->generateJC($args[1]['jc']);
                }
    
                $this->generateTBLW();
                if (!empty($args[1]['border'])) {
                    $this->generateTBLBORDERS();
                    $this->generateTBLBOTTOM();
                    $this->generateTBLLEFT();
                    $this->generateTBLTOP();
                    $this->generateTBLRIGHT();
                    $this->generateTBLINSIDEH();
                    $this->generateTBLINSIDEV();
                }
    
                $this->generateTBLLOOK();
                $this->generateTBLOVERLAP();
                $intLine = 0;
                foreach ($args[0] as $datDepth) {
                    $this->generateTR();
                    $intLine++;
                    foreach ($datDepth as $cont) {
                        $this->generateTC();
                        $this->generateP();
                        $this->generateR();
                        if ($args[1]['font'] != '') {
                            $this->generateRPR();
                            $this->generateRFONTS($args[1]['font']);
                        }
                        $this->generateT($cont);
                    }
                    $this->cleanTemplateR();
                }
            }
        }
    
        private function cleanTemplateR()
        {
            $this->_xml = preg_replace('/__GENERATETR__/', '', $this->_xml);
        }
    }   
    

    and then calling:

    $table = new SmCreateTable();
    $table->createTable($valuesTable, $paramsTable);