kartik-v / yii2-mpdf

A Yii2 wrapper component for the mPDF library which generates PDF files from UTF-8 encoded HTML.
http://demos.krajee.com/mpdf
Other
161 stars 150 forks source link

Using global component to create multiple files results in duplicating the same content #66

Closed tsdogs closed 6 years ago

tsdogs commented 6 years ago

Steps to reproduce the issue

  1. Define the pdf component in configuration
  2. In the code create a function which generates the pdf from a template (for specific model)
  3. call the function multiple times with different model

Expected behavior and actual behavior

The result is that the files are generated, but the content is the one associated to the first call of this function I was expecting it would generate with each content to be different

An example code would be something like this

view.php

ID: <?= $model->id ?> <br />
NAME: <?= $model->name ?>

controller.php


function generatePDF($model)
{
    $pdf = Yii::$app->pdf;
    $pdf->content = $this->renderPartial('view',['model'=>$model]);
    $pdf->destination = 'F';
    $pdf->filename = Yii::getAlias('@runtime/tmp').'/'.'example-'.$model->id.'.pdf';
    $pdf->render();
}

function actionGenerate()
{
    $models = Model::find()->where('active=1')->all();
    foreach ($models as $model) {
        $this->generatePDF($model);
    }
    return 'files where generated';
}

The files generated would contain all the data of the first model

If I use every time a new Mpdf object by replacing the line

$pdf = Yii::$app->pdf;

with

$pdf = new \kartik\mpdf\Pdf([
 ...
]);

Everything works as expected and I get different content based on the data contained into the models.

kartik-v commented 6 years ago

Not sure of the issue... it looks obvious that once you have used the global component and set its properties, the properties will continue to persist unless you reset them.

So if your content changes you need to reset and change $pdf->content everytime when you use it differently.

tsdogs commented 6 years ago

The problem is exactly this. If I set the $pdf->content to be different once it's been rendered, the content of the generated PDF does not change accordingly when I call rener() again.