GridView: Generate PDF of selected rows

Hi there,

I want to generate a pdf of the selected rows of a grid view like this:

JS of view:


 <?php JSRegister::begin(); ?>

        <script>

        

            (function () {

                document.getElementById('pdf').addEventListener('click', pdfSelectRows, true)




            function pdfSelectRows() {

                // javascript to call for your button on 

                // the view - which on click - will process the 

                // action for all selected rows

                var keys = $('#grid').yiiGridView('getSelectedRows');

                $.post({

                   url: 'notice/report', // your controller action

                   dataType: 'json',

                   data: {keylist: keys},

                   success: function(data) {

                      alert('I did it! Processed checked rows.')

                   },

                });

            }

        })();

        </script>

        

        <?php JSRegister::end(); ?>

    

…and Controller:


public function actionReport() {

    	

    	$this->layout = false;

    	

    	//var_dump($ids);

    	

	    // get your HTML raw content without any layouts or scripts

	    //$content = $this->renderPartial('_reportView');

	    

	    $content = "";

	    

	    foreach($_POST['keylist'] as $id)

	    {

	       $content = $content . '<br> ' . $this->render('_reportView', ['model' => $this->findModel($id),]); 

	    }

	    

	   	    // setup kartik\mpdf\Pdf component

	    $pdf = new Pdf([

	        // set to use core fonts only

	        'mode' => Pdf::MODE_CORE, 

	        // A4 paper format

	        'format' => Pdf::FORMAT_A4, 

	        // portrait orientation

	        'orientation' => Pdf::ORIENT_PORTRAIT, 

	        // stream to browser inline

	        'destination' => Pdf::DEST_BROWSER, 

	        // your html content input

	        'content' => $content,  

	        // format content from your own css file if needed or use the

	        // enhanced bootstrap css built by Krajee for mPDF formatting 

	        'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',

	        // any css to be embedded if required

	        'cssInline' => '.kv-heading-1{font-size:18px}', 

	         // set mPDF properties on the fly

	        'options' => ['title' => ''],

	         // call mPDF methods on the fly

	        'methods' => [ 

	            'SetHeader'=>[''], 

	            'SetFooter'=>['{PAGENO}'],

	        ]

	    ]);

	    

	    // return the pdf output as per the destination setting

	    return $pdf->render(); 

	}

The controller already get the selected keys and a pdf will be generated. But if I press my generate button in the grid view, no visible action (like a new site or pdf open) appears. With the object inspector I can the see the result. What code do I need to make the browser open the new generated pdf document?

Many thanks!

Toby

2days later, I solved it - to whom it may concern:

the controller:




    public function actionReport() {

    	

    	$this->layout = false;

    		    

        $keys = explode (',', Yii::$app->request->post('keys'));


        $content = "";

                

        // loop through the selected rows

        foreach($keys as $id)

	    {

	       $content .= '<br> ' . $this->render('_reportView', ['model' => $this->findModel($id),]); 

	    }	      

	    

	   	    // setup kartik\mpdf\Pdf component

	        $pdf = new Pdf([

	        // set to use core fonts only

	        'mode' => Pdf::MODE_UTF8, 

	        // A4 paper format

	        'format' => Pdf::FORMAT_A4, 

	        // portrait orientation

	        'orientation' => Pdf::ORIENT_PORTRAIT, 

	        // stream to browser inline

	        'destination' => Pdf::DEST_BROWSER, 

	        // your html content input

	        'content' => $content,  

	        // format content from your own css file if needed or use the

	        // enhanced bootstrap css built by Krajee for mPDF formatting 

	        'cssFile' => '@vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',

	        // any css to be embedded if required

	        'cssInline' => '.kv-heading-1{font-size:18px}', 

	         // set mPDF properties on the fly

	        'options' => ['title' => ''],

	         // call mPDF methods on the fly

	        'methods' => [ 

	            'SetHeader'=>[''], 

	            'SetFooter'=>['{PAGENO}'],

	        ]

	    ]);

	    

	    echo $pdf->render();

	}

	




to the view file (in addition to the gridview form element), the javascript component:




       <?php JSRegister::begin(); ?>

        <script>

        

            document.getElementById('pdf').addEventListener('click', pdfSelectRows, true);


            function pdfSelectRows() {

 

                let xhr = new XMLHttpRequest();

                //set the request type to post and the destination url to '/convert'

                xhr.open('POST', 'notice/report');

                //set the reponse type to blob since that's what we're expecting back

                xhr.responseType = 'blob';

                // let formData = new FormData(this);

                var data = new FormData();

                data.append('keys', $('#grid').yiiGridView('getSelectedRows'));

        

                xhr.send(data);//formData);


                xhr.onload = function(e) {

                  if (this.status == 200) {

                    var blob = this.response;

                    //TODO fallback needed for IE8 & IE9

                    if (navigator.appVersion.toString().indexOf('.NET') > 0) {

                    	//IE 10+

                    	window.navigator.msSaveBlob(blob, 'test.pdf');

                    } else {

                    	//Firefox, Chrome

                    	var win = window.open('', '_blank');

                    	var a = win.document.createElement("a");

                        var blobUrl = window.URL.createObjectURL(new Blob([blob], {type: blob.type}));

                        

                        document.body.appendChild(a);

                        a.style = "display: none";

                        a.href = blobUrl;

                        a.download = 'test.pdf';

                        a.click();

                        win.close();

                    }

                  }

                };

                            }

        </script>

        

        <?php JSRegister::end(); ?>

    



best regards from Munich,

Toby