更改列宽Yii

时间:2015-11-11 08:46:24

标签: php css yii

如何更改以PDF格式保存的表格的列宽 我有这个代码

<?php
   $data_provider = $model->viewEmployees($search, $from, $to);
   $data_provider->pagination = false;   

$this->widget('ext.pdfGrid.EPDFGridPortrait', array(
        'id' => 'employee-pdf',
        'fileName' => 'Employees',
        'dataProvider' => $data_provider,
        'columns' => array(
            array('name' => '#', 'value'=>'$row+1',  
                  'htmlOptions' => array('style'=>'width:30px')
                 ),

            array('name' => 'ID Number','value' => '$data->company_id', 
                  'htmlOptions'=>array('style'=>'width:150px'),                      
                 ),

            array('name' => 'Name', 'header' => 'Name', 'value' => '$data->getNameWithMiddleInitial()', 
                  'htmlOptions' => array('style'=>'width:200px'),
                  ),

            array('name' => 'Date Employed', 'value' => '$data->date_employed' ,
                  'htmlOptions'=>array('style'=>'width:200px'),
                  ),            
        ),
        'config' => array(
            'subTitle' => 'List of Employees',
            'headerDetails' => true,
            'showLogo' => true,
            'colAligns' => array('C', 'L', 'C'),
        ),
    ));

  ?>

我已尝试在我的代码中使用此'htmlOptions' => array('style'=>'width:30px'),但似乎无效。请帮忙。

似乎它只是调用EPDFGridPortrait.php这是代码..

<?php

Yii::import('zii.widgets.grid.CDataColumn');
Yii::import('ext.pdfGrid.fpdf.PDF');

class EPDFGridPortrait extends CWidget {

    private $_debug = false;
    protected $_pdf;
    protected $_fill = false;
    protected $_columnWidths = array();
    protected $_visibleColumns = 0;
    public $dataProvider;
    public $fileName;
    public $config = array();
    public $columns = array();
    public $labels = array();
    public $orientation = 'P';

    public $showTableOnEmpty = true;           
    public $nullDisplay = ' ';
    public $emptyText;
    public $hideHeader = false;
    public function init() {
        if ($this->columns === array()) {

            if ($this->dataProvider instanceof CActiveDataProvider)
                $this->columns = $this->dataProvider->model->attributeNames();
            else if ($this->dataProvider instanceof IDataProvider) {

                $data = $this->dataProvider->getData();
                if (isset($data[0]) && is_array($data[0]))
                    $this->columns = array_keys($data[0]);
            }
        }
        $id = $this->getId();
        foreach ($this->columns as $i => $column) {
            if (is_string($column))
                $column = $this->createDataColumn($column);
            else {
                if (!isset($column['class']))
                    $column['class'] = 'CDataColumn';
                $column = Yii::createComponent($column, $this);
            }
            if (!$column->visible) {
                unset($this->columns[$i]);
                continue;
            }
            $this->_visibleColumns++;
            if ($column->id === null)
                $column->id = $id . '_c' . $i;
            $this->columns[$i] = $column;
        }

        $default = array(
            'pdfSize' => 'A4',
            'title' => '',
            'subTitle' => '',
            'headTitle' => '',
            'amount' => '',
            'tableWidth' => 190,
            'rowHeight' => 6,
            'colAligns' => null,
            'colWidths' => null,
            'showLogo' => false,
            'imagePath' => YiiBase::getPathOfAlias('webroot') . '/images/logo.jpg',
            'headerDetails' => false,
        );

        $this->config = array_merge($default, $this->config);

        $this->_pdf = new PDF('L', 'mm', $this->config['pdfSize']);
        $this->_pdf->title = $this->config['title'];
        $this->_pdf->subTitle = $this->config['subTitle'];
        $this->_pdf->headTitle = $this->config['headTitle'];
        $this->_pdf->amount = $this->config['amount'];
        $this->_pdf->tableWidth = $this->config['tableWidth'];
        $this->_pdf->rowHeight = $this->config['rowHeight'];
        $this->_pdf->imagePath = $this->config['imagePath'];
        $this->_pdf->showLogo = $this->config['showLogo'];
        $this->_pdf->headerDetails = $this->config['headerDetails'];
        $this->_pdf->SetAligns($this->config['colAligns']);
        $this->_pdf->SetFont('Arial', 'B', 10);
        $this->_pdf->SetLineWidth(0.5);
        $this->_columnWidths = $this->_calcWidths();
        $this->_pdf->SetWidths($this->_columnWidths);
        $this->_pdf->AliasNbPages();
        $this->_pdf->AddPage('P');

        foreach ($this->columns as $column)
            $column->init();

        $this->renderItems();
    }    

    protected function createDataColumn($text) {
        if (!preg_match('/^([\w\.]+)(:(\w*))?(:(.*))?$/', $text, $matches))
            throw new CException(Yii::t('zii', 'The column must be specified in the format of "Name:Type:Label",
                where "Type" and "Label" are optional.'));
        $column = new CDataColumn($this);
        $column->name = $matches[1];
        if (isset($matches[3]) && $matches[3] !== '')
            $column->type = $matches[3];
        if (isset($matches[5]))
            $column->header = $matches[5];
        return $column;
    }
    protected function renderItems() {
        if ($this->dataProvider->getItemCount() > 0 || $this->showTableOnEmpty) {
            $this->renderTableHeader();
            $this->renderTableBody();
        }
        else
            $this->_renderEmptyText();

        if ($this->_debug)
            Yii::app()->end();
        else {
            // $this->_pdf->Output($this->fileName . ' (' . date('Y-m-d') . ').pdf', 'D');
            $this->_pdf->Output($this->fileName . '.pdf', 'D');
            exit();
        }
    }

    protected function renderTableHeader() {
        if (!$this->hideHeader) {
            // Colores y fuente en negrita
            $this->_pdf->SetFillColor(245, 185, 120);
            $this->_pdf->SetTextColor(0);
            $this->_pdf->SetBold();

            $rowHeader = array();
            if ($this->labels != array()) {
                $rowHeader = $this->labels;
            } else {
                foreach ($this->columns as $i => $column) {
                    if ($column->name == 'Id') {
                        $rowHeader[] = strtoupper($column->name);
                    } else {
                        $rowHeader[] = $column->name;    
                    }                    
                    // $rowHeader[] = $column->grid->dataProvider->model->getAttributeLabel($column->name);
                    //$this->_pdf->Cell($this->_columnWidths[$i],$this->headerHeight,$data,0,0,'C',true);
                }
            }
            $this->_pdf->Row($rowHeader, array('fill' => true, 'header' => true));
        }
    }

    protected function renderTableBody() {
        $data = $this->dataProvider->getData();
        $n = count($data);

        $this->_pdf->SetFillColor(255, 242, 208);
        $this->_pdf->SetTextColor(0);
        $this->_pdf->SetFont('');
        if ($n > 0) {
            for ($row = 0; $row < $n; ++$row)
                $this->renderTableRow($row);
        }
        else
            $this->_renderEmptyText();
    }

    protected function renderTableRow($row) {
        //var_dump($this->dataProvider);
        $rowData = array();
        foreach ($this->columns as $i => $column) {
            $data = $this->dataProvider->data[$row];

            if ($column->value !== null)
                $value = $column->evaluateExpression($column->value, array('data' => $data, 'row' => $row));
            else if ($column->name !== null)
                $value = CHtml::value($data, $column->name);

//          $rowData[] = $value===null ? $this->nullDisplay : $this->_formatString($value); 
            $rowData[] = $value === null ? $this->nullDisplay : utf8_decode($value);
        }
        $this->_pdf->Row($rowData, array('fill' => $this->_fill));
        $this->_fill = !$this->_fill;
    }

    protected function _renderEmptyText() {
        $emptyText = $this->emptyText === null ? Yii::t('zii', 'No results found.') : $this->emptyText;
        $this->_pdf->Cell(array_sum($this->_columnWidths), $this->config['rowHeight'], $emptyText, 0, 0, 'L');
    }

    protected function _calcWidths() {
        $widths = array();
        $params = $this->config['colWidths'];
        $visibleCols = $this->_visibleColumns;

        if (!$params) {

            $w = $this->_pdf->tableWidth / $visibleCols;
            for ($i = 0; $i < $visibleCols; $i++)
                $widths[] = $w;
        } else if (is_array($params)) {   
            if (count($params) > $visibleCols)
                throw new Exception('La cantidad de parametros supera a las columnas visibles');
            if (array_sum($params) > $this->_pdf->tableWidth)
                throw new Exception('La suma de los parametros supera a la longitud max de la tabla');

            $nulls = 0; //cantidad de columnas que no se configuraron
            $confWidth = 0; 
            for ($i = 0; $i < $visibleCols; $i++) {
                if (empty($params[$i]))
                    $nulls++;
                else
                    $confWidth += $params[$i];
            }

            $w = $nulls ? ($this->_pdf->tableWidth - $confWidth) / $nulls : 0;    
            for ($i = 0; $i < $visibleCols; $i++) {
                $widths[] = empty($params[$i]) ? $w : $params[$i];
            }
        }
        else
            throw new Exception('El parametro $config[widths] debe ser un array');

        return $widths;
    }

    protected function _formatString($string) {
        $string = strtolower(utf8_decode($string));
        return ucwords($string);
    }    
    protected function _combineColumns($print = '', $config = array()) {
        $default = array(
            'from' => 0,
            'to' => $this->_visibleColumns - 1,
            'border' => 0,
            'align' => 'L',
            'fill' => $this->_fill,
            'ln' => 1,
        );

        $config = array_merge($default, $config);

        $b = $this->$config['border'];
        $a = $this->$config['align'];
        $f = $this->$config['fill'];
        $ln = $this->$config['ln'];

        $w = 0;
        for ($i = $this->$config['from']; $i <= $this->$config['to']; $i++) {
            $w += $this->_columnWidths[$i];
        }

        $this->_pdf->Cell($w, $this->config['rowHeight'], $print, $b, $ln, $a, $f);
        if ($f)
            $this->_fill = !$this->_fill;
    }

}
抱歉长码。我只是困惑为什么这一行

'htmlOptions' => array('style'=>'width:30px'), 

无法正常工作..

1 个答案:

答案 0 :(得分:0)

我已经弄清楚了列的宽度是如何工作的。

我在'config'数组

中添加了这一行
'colWidths' => array(10, 30, 85, 65),

给了我

'config' => array(
            //'title' => 'Sprobe Inc. Information Management System',
            'subTitle' => 'List of Employees',
            'header' => false,
            'showLogo' => true,
            'colAligns' => array('C', 'C', 'L',/* 'L',*/ 'C'),
            'colWidths' => array(10, 30, 85, 65),
        ),

colWidths操纵每个列的宽度,它依赖于我的EPDFGridPortrait.php函数_calcWidths中的参数