Yii Framework Forum

Use twig with Mpdf

(Jonny) #1


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()
        ->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:

(Alirz23) #2

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

(Jonny) #3

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

(Alirz23) #4

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

(Jonny) #5

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]);