使用kartik-mPDF扩展名以PDF格式打印gridview搜索

时间:2019-02-04 23:58:05

标签: yii2 yii2-basic-app

我正在使用kartik-mpdf库生成我的gridviews的pdf,问题是我想将$ dataProvider和$ searchModel从index.php传递到将作为pdf文档(pdf.php)呈现的视图,因此,当我搜索索引并单击“ Generar pdf”按钮时,它将在AlumnoController上调用动作GenerarPdf,并将索引动作的相同$ searchModel和$ dataProvider加载到pdf.php gridview中并生成pdf文件。

这是代码。 AlumnoController.php-actionGenerarPdf

public function actionGenerarPdf($searchModel, $dataProvider) 
    {
        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        $formatter = \Yii::$app->formatter;
        $pdf = new Pdf([
            'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
            'destination' => Pdf::DEST_BROWSER,
            //Se renderiza la vista "pdf" (que abrirá la nueva ventana)
            'content' => $this->renderPartial('pdf', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider
                ]),
            'options' => [
            // any mpdf options you wish to set
            ],
            'methods' => [
                'SetTitle' => 'SIE: Sistema de Informacion Estudiantil',
                'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
                'SetHeader' => ['SIE: Sistema de Información Estudiantil||Generado el: ' . $formatter->asDate(date("r"))],
                'SetFooter' => ['|Página {PAGENO}|'],
                'SetAuthor' => 'SIE: Sistema de información Estudiantil',
                'SetCreator' => 'Juan Carlos Reyes Suazo',
//              'SetKeywords' => 'Sie, Yii2, Export, PDF, MPDF, Output, yii2-mpdf',
            ]
        ]);
        return $pdf->render();
    }

index.php

<p>
        <?php 
            if (User::isSuperAdmin(Yii::$app->user->identity->id)){
                echo Html::a('Crear Alumno', ['create'], ['class' => 'btn btn-success']); 
                echo Html::a('Ver PDF', [
                    '/alumno/generar-pdf', 
                    'searchModel' => $searchModel, 
                    'dataProvider' => $dataProvider
                        ], 
                        [
                    'class' => 'btn btn-success', 
                    'target'=>'_blank', 
                    'data-toggle'=>'tooltip', 
//    'title'=>'Will open the generated PDF file in a new window'
                ]);
            }
        ?>
    </p>

pdf.php

<?= GridView::widget([
        'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'columns' => [
            ['class' => 'yii\grid\SerialColumn'],
            //'id',
            ['attribute' => 'nombre',
             'format' => 'raw',
             'value'=>function ($data) {
                        return Html::a($data['nombre'],['alumno/view', 'id' => $data['id']]);
                      },
             ],
            //'rut',
            ['attribute' => 'curso_id',
             'format' => 'raw',
             'value'=>function ($data) {
                        return Html::a($data['curso_id'],['curso/view', 'id' => $data['curso_id']]);
                      },
             ],
            //'fecha_nacimiento',
            //'fono',
            //'direccion',
            //'email:email',
            //'apoderado',
            ['attribute' => 'apoderado',
             'format' => 'raw',
             'value'=>function ($data) {
                          if ($data->apoderado_id != null)
                              return Html::a($data->apoderado->nombre, ['apoderado/view', 'id' => $data['apoderado_id']]);
                          else
                              return null;

                      },
             ],
            //'apoderado_suplente',
            //'fono_apoderado',
            //'fono_apoderado_sup',
            //'antecedentes_medicos',
            //'grupo_sanguineo',
            //'programa_integracion',
            //'taller_artistico',
            //'anotaciones',

            ['class' => ActionColumn::className(), 'template' => '{update} {delete}'],
        ],
    ]); ?>

我收到了错误的请求(#400)

Se recibieron datoserróneospara elparámetro“ searchModel”

任何帮助将不胜感激。

1 个答案:

答案 0 :(得分:0)

我通过使用会话解决了这个问题,并在actionGenerarPdf中生成了$ searchModel和$ dataProvider,而不是通过按钮发送了它们。

我将在yii论坛中引用@softark

  

“您不能将$ searchModel和$ dataProvider作为查询参数传递给操作方法,因为它们不是可以转换为简单字符串的简单变量。

     

因此,您必须在actionGenerarPdf方法中创建搜索模型和数据提供程序。

     

为了获取索引操作中使用的搜索参数,可以将查询参数存储在会话中,然后在actionGenerarPdf中检索它们。”

https://forum.yiiframework.com/t/print-gridview-search-in-pdf-using-kartik-mpdf-extension-solved/124925

这是代码

public function actionIndex()
    {

        $searchModel = new AlumnoSearch();
        $dataProvider = $searchModel->search(Yii::$app->request->queryParams);

        $session = Yii::$app->session;
        $session->open();
        $session['query_params'] = json_encode(Yii::$app->request->queryParams);
        $session->close();

        return $this->render('index', [
            'searchModel' => $searchModel,
            'dataProvider' => $dataProvider,
        ]);
    }
public function actionGenerarPdf() 
    {
        $session = Yii::$app->session;
        $session->open();
        $queryParams = isset($session['query_params']) ? json_decode($session['query_params'], true) : [];
        $session->close();
        $searchModel = new AlumnoSearch();
        $dataProvider = $searchModel->search($queryParams);
        Yii::$app->response->format = \yii\web\Response::FORMAT_RAW;
        $formatter = \Yii::$app->formatter;
        $pdf = new Pdf([
            'mode' => Pdf::MODE_CORE, // leaner size using standard fonts
            'defaultFontSize' => 18,
            'orientation' => Pdf::ORIENT_PORTRAIT,
            'destination' => Pdf::DEST_BROWSER,
            //Se renderiza la vista "pdf" (que abrirá la nueva ventana)
            'content' => $this->renderPartial('pdf', ['searchModel' => $searchModel, 'dataProvider' => $dataProvider]),
            'options' => [
            // any mpdf options you wish to set
            ],
            'methods' => [
                'SetTitle' => 'SIE: Sistema de Informacion Estudiantil',
                'SetSubject' => 'Generating PDF files via yii2-mpdf extension has never been easy',
                'SetHeader' => ['SIE: Sistema de Información Estudiantil||Generado el: ' . $formatter->asDate(date("r"))],
                'SetFooter' => ['|Página {PAGENO}|'],
                'SetAuthor' => 'SIE: Sistema de información Estudiantil',
                'SetCreator' => 'Juan Carlos Reyes Suazo',
//              'SetKeywords' => 'Sie, Yii2, Export, PDF, MPDF, Output, yii2-mpdf',
            ]
        ]);
        return $pdf->render();
    }

我希望这对希望达到相同目标的人有所帮助