Yii2 - Generate Pdf on the fly and attach to email
Asked Answered
D

3

5

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?

Dean answered 9/12, 2016 at 10:21 Comment(0)
S
7

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();
Sldney answered 9/12, 2016 at 12:19 Comment(4)
Good answer, would be even better with a code example.Xylina
@Xylina here you go ;)Sldney
shouldn't it be attach() instead of attachContent() if it's path to file?Immunochemistry
@Immunochemistry is right. I suggest you change attachContent with attach in your example. attachContent is useful when the file is created on the fly and it will not work as expected when the first parameter is a file path. For a file that already exists and it is available at some path, attach is the proper option. See the documentation: yiiframework.com/doc/guide/2.0/en/…Least
D
4

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'])
Dean answered 12/12, 2016 at 8:9 Comment(0)
M
1

This is how I sent mails in Yii2

private function sendPdfAsEmail($mpdf)
    {
        $mpdf->Output('filename.pdf', 'F');
        $send = Yii::$app->mailer->compose()
        ->setFrom('[email protected]')
        ->setTo('[email protected]')
        ->setSubject('Test Message')
        ->setTextBody('Plain text content. YII2 Application')
        ->setHtmlBody('<b>HTML content.</b>')
        ->attach(Yii::getAlias('@webroot').'/filename.pdf')
        ->send();
        if($send) {
            echo "Send";
        }
    }
  1. Pass the mpdf instance to our custom function.
  2. Use the F option in mpdf to save the output as a file.
  3. use the attach option in Yii mailer and set the path of the saved file.
Melleta answered 8/7, 2020 at 10:40 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.