Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 - Generate Pdf on the fly and attach to email

This is how I can generate pdf page

public function actionPdf(){
    Yii::$app->response->format = 'pdf';
    $this->layout = '//print';
    return $this->render('myview', []);
}

And this is how I send emails

$send = Yii::$app->mailer->compose('mytemplate',[])
    ->setFrom(Yii::$app->params['adminEmail'])
    ->setTo($email)
    ->setSubject($subject)
    ->send();

How I can generate pdf as a file and attach it to my emails on the fly?

like image 319
Anna Avatar asked Dec 09 '16 10:12

Anna


2 Answers

Mailer have method called attachContent(), where you can put pdf file.

PDF should be rendered with output destination set as string, and then pass it as param to attachContent().

Sample:

Yii::$app->mail->compose()
   ->attachContent($pathToPdfFile, [
        'fileName'    => 'Name of your pdf',
        'contentType' => 'application/pdf'
   ])
   // to & subject & content of message
   ->send();
like image 169
Yupik Avatar answered Nov 13 '22 22:11

Yupik


This is how I did it

In my controller:

$mpdf=new mPDF();
$mpdf->WriteHTML($this->renderPartial('pdf',['model' => $model])); //pdf is a name of view file responsible for this pdf document
$path = $mpdf->Output('', 'S'); 

Yii::$app->mail->compose()
->attachContent($path, ['fileName' => 'Invoice #'.$model->number.'.pdf',   'contentType' => 'application/pdf'])
like image 4
Anna Avatar answered Nov 13 '22 21:11

Anna