Use twig with Mpdf

Hi

I have a template that is written in twig which I’m trying to send as an email, but I’m finding that the PDF sends the content as the twig content.

$content = $this->renderPartial(Yii::getAlias('@twigrelative') . '/screen.twig', ['model' => $var, 'site' => 20]);
        $doc->WriteHTML($content, 2);
        
        $pdf = $doc->Output('this is ignored', \Mpdf\Output\Destination::STRING_RETURN);

        $user = User::find()->where(['username' => $this->email ])->one();

        $mail = Yii::$app->mailer->compose()
        ->setFrom($user->username)
        ->setTo("jonny@email.com")
        ->setSubject("stuff")
        ->attachContent($pdf, ['fileName' => 'report.pdf', 'contentType' => 'application/pdf']);

Am I missing anything here or can I not use twig to render a PDF as an attachment? Because it works in the browser fine, because it uses a View object. :slight_smile:

what does your $content print out, maybe echo it out and make sure it is rendered as html.

It’s rendered as Twig {% if site == 305 %} {% set..

you need to run through the twig engine to render it into html before you can pass it to the pdf library

I figured out how to do it:

            // build content and write to PDF
            $twig = new \yii\twig\ViewRenderer() ;
            $content = $twig->render(new \yii\web\View(), Yii::getAlias('@twigrelative') . '/screen.twig', ['model' => $var, 'site' => 20]);