在yii2控制台中生成pdf

时间:2016-05-26 09:52:30

标签: php pdf yii2 mdf

我想在yii2控制台中生成pdf但是收到错误。代码在web中正确执行,但在console中未执行。我正在使用mdf扩展名。

public function actionInvoicePdf($invoice) {
     $content = $this->renderPartial('_invoicePdf',['invoice'=>$invoice]);
     Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
     $headers = Yii::$app->response->headers;
     $headers->add('Content-Type', 'application/pdf');
     $path = Yii::getAlias('@uploadPath').'/pdf/commission-invoice/';
    // setup kartik\mpdf\Pdf component
    $pdf = new Pdf([
        'mode' => Pdf::MODE_CORE, 
        'format' => Pdf::FORMAT_A4, 
        'filename' => 'test.pdf', //$path.$invoice->invoice_filename,
        'orientation' => Pdf::ORIENT_PORTRAIT, 
        'destination' => Pdf::DEST_FILE, //Pdf::DEST_FILE
        'content' => $content,  
        'cssInline' => '.kv-heading-1{font-size:18px}', 
         // set mPDF properties on the fly
        'options' => ['title' => 'Invoice #'],
         // call mPDF methods on the fly
        'methods' => [ 
            'SetHeader'=>['Invoice:buyold'], 
            'SetFooter'=>['{PAGENO}'],
        ]
    ]);
    return $pdf->render(); 
}

获取错误异常

'yii\base\UnknownPropertyException' with message 'Setting unknown prop
erty: yii\console\Response::format'

Exception 'yii\base\UnknownPropertyException' with message 'Getting unknown prop
erty: yii\console\Response::headers'

这是我的控制台配置文件

return [
'id' => 'app-console',
'basePath' => dirname(__DIR__),
'bootstrap' => ['log'],
'controllerNamespace' => 'console\controllers',
'components' => [
    'log' => [
        'targets' => [
            [
                'class' => 'yii\log\FileTarget',
                'levels' => ['error', 'warning'],
            ],
        ],
    ],
    'session' => [ // for use session in console application
        'class' => 'yii\web\Session'
    ],
],

'params' => $params,

];

1 个答案:

答案 0 :(得分:0)

控制台应用程序的默认响应类是yii\console\Response而不是yii\web\Response。就这样:

  1. 由于控制台应用程序应返回纯文本和
  2. ,因此没有格式
  3. 没有标题,因为调用是通过命令行界面而不是网络服务器。
  4. 因此应删除以下行:

    Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
    $headers = Yii::$app->response->headers;
    $headers->add('Content-Type', 'application/pdf');