phppdfyii2mdf

Generate pdf in yii2 console


I want to generate pdf in yii2 console but getting error. The code execute correctly in web but not in console. I am using mdf extension for it.

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(); 
}

Getting error Exception

'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'

Here is my console config file

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,

];


Solution

  • The default response class for console applications is yii\console\Response not yii\web\Response. As such:

    1. There is no format since console applications should return plain text and
    2. there are no headers since the call is via a command line interface and not to a webserver.

    Therefore the following lines should be removed:

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