Yii2:在控制器操作中覆盖mpdf的全局pdf方向设置

时间:2017-08-07 07:37:06

标签: yii2 mpdf

我正在使用mpdf扩展来生成pdf文件。我在配置文件中为mpdf设置了全局设置,因此每次我想从控制器操作生成pdf时,我都可以调用该函数。但是,由于全局设置中设置的默认方向为portrait,因此我发现很难使用需要横向方向的数据更改pdf的方向。以下是代码:

main.pdf全局设置代码

'pdf' => [
    'class' => Pdf::classname(),
    'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
    'format' => Pdf::FORMAT_A4,
    'orientation' => Pdf::ORIENT_PORTRAIT,
    'destination' => Pdf::DEST_BROWSER,
    'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
    // any css to be embedded if required
    'cssInline' => '.kv-heading-1{font-size:18px}',
    'options' => [
        'shrink_tables_to_fit' => 0
    ],
    // refer settings section for all configuration options
],

Controller Action调用全局设置:

public function actionReservationsList()
{
    $searchModel = new ReservationsSearch();
    $dataProvider = $searchModel->search(Yii::$app->session->get('repquery'));
    $dataProvider->pagination = false;

    $pdf = Yii::$app->pdf;
    $pdf->content = $this->renderPartial('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    $pdf->methods = [
        'SetHeader' => [Yii::$app->user->identity->company->name.'||Date: ' . date("r")],
        'SetFooter' => ['User: '.Yii::$app->user->identity->username.'||Page {PAGENO}'],
    ];
    return $pdf->render();
}

因此,我需要帮助覆盖控制器操作中全局设置'orientation' => Pdf::ORIENT_PORTRAIT,文件中的main.php设置。

3 个答案:

答案 0 :(得分:1)

这项工作对我来说:

<?php
namespace backend\controllers;

use Yii;
use yii\web\Controller; 
use kartik\mpdf\Pdf;

class InformesController extends Controller
{
   ...
    public function actionImprimirInforme($id,$key)
    {       
        $html = $this->renderPartial('informe-pdf', [ 
            'title' => 'Informe'
        ]);

        $pdf = new Pdf([
           'format' => Pdf::FORMAT_A4,
           'orientation' => Pdf::ORIENT_LANDSCAPE,
           'destination' => Pdf::DEST_BROWSER,
           'options' => [
               'showImageErrors' => true,
            ]
        ]);

        $pdf->configure([
            'title' => 'Informe ',
        ]);

        $pdf->content = $html; 

        $pdf->orientation = Pdf::ORIENT_LANDSCAPE;
        $pdf->execute('SetFooter', ['{PAGENO} de {nbpg}']);
        $pdf->filename = "Informe.pdf";
        return $pdf->render();
    }
}

我的第一个回答是错误的,我一直将属性'orientation'设置为pdf组件,因此动态分配无法正常工作。

Here you have the documentation example

答案 1 :(得分:0)

您需要通过addPage添加内容。因此,如果您使用内容等构建一个页面数组 - 您应该能够指定每页的方向。

<?php

$mpdf = new mPDF('', 'Legal');
$mpdf->WriteHTML('
    Hello World
');

$mpdf->AddPage('L'); // Adds a new page in Landscape orientation

$mpdf->WriteHTML('
    Hello World
');

$mpdf->Output();

?>

答案 2 :(得分:0)

尝试添加以下行:

$pdf = Yii::$app->pdf;
$pdf->orientation = Pdf::ORIENT_LANDSCAPE;