2016-05-26 62 views
1

我想在yii2控制檯中生成pdf,但出現錯誤。代碼在web中正確執行,但不在console中執行。我正在使用mdf擴展名。在yii2控制檯中生成pdf

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, 

]。

+0

檢查控制檯配置文件一次。參考:http://stackoverflow.com/questions/34174750/yii2-getting-unknown-property-yii-console-applicationuser –

+0

好吧,我更新我的問題。現在你可以看到我的控制檯配置文件 –

回答

0

控制檯應用程序的默認響應類別爲yii\console\Response而不是yii\web\Response。因此:

  1. 沒有格式,因爲控制檯應用程序應返回純文本和
  2. 沒有標題,因爲這種呼叫是通過命令行界面,而不是一個網絡服務器。

因此,以下行應該被刪除:

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

我的錯誤。我需要保存它,所以我不需要頭格式:-) –