Menus

Wednesday 16 September 2015

YII2 mPDF


HTML to PDF introduction


Setting paper size in FPDF


mPDF is a simple and popular tool for shared hosting users to create and convert UTF-8 encoded HTML pages to PDF files.


The yii2-mpdf extension is a Yii2 wrapper component for the mPDF library with enhancements. The mPDF library offers ability to generate PDF files from UTF-8 encoded HTML. This library is based on FPDF andHTML2FPDF, with a number of enhancements. The key features in the library are to be able to generate PDF files 'on-the-fly' from HTML content, handling different languages. See the list of features and/or examples for the library. The yii2-mpdf extension offers an easy way to integrate and use the mPDF library within your Yii application with subtle enhancements. 



Installation
The preferred way to install this extension is through composer. Either run:
  1. $ php composer.phar require kartik-v/yii2-mpdf "*"
or add:
  1. "kartik-v/yii2-mpdf": "*"
to the require section of your composer.json file. Then run:
  1. php composer.phar update
to get the updated package on your application install.


Install and  Use    




Settings \kartik\mpdf\Pdf


The extension includes the \kartik\mpdf\Pdf Component class (which extends and builds upon the yii/base/Component class).


mPDF Usage


How to set or resize margin in mPDF ?
How to change paper orientation in mPDF ?
How to change font size in mPDF ?
How to change paper size in mPDF ?


Answers:


If you want to be more specific about encoding and page size, you can put those parameters when initializing mPDF class like this:


1
$mpdf = new mPDF('utf-8', 'A4');

You can even specify actual page size in mm. In the example below the page size will be 190mm wide x 236mm height:

1$mpdf = new mPDF('utf-8', array(190,236));


If you want full functionality, you can even specify margins and if the page is landscape like this:


1
$mpdf = new mPDF('',    // mode - default ''
2 '',    // format - A4, for example, default ''
3 0,     // font size - default 0
4 '',    // default font family
5 15,    // margin_left
6 15,    // margin right
7 16,     // margin top
8 16,    // margin bottom
9 9,     // margin header
10 9,     // margin footer
11 'L');  // L - landscape, P - portrait




Example


* First find required data
* Create php file receipt-print.php. This file used to display format for pdf file.
* Use renderPartial funtion to send values to display receipt-print.php and assign object to $html variable
* Create mpdf object assign parameters.
* Write html and create output.




public function actionPrintCommonReceipt($receipt_no, $ccid)
    {
        
        if(!yii::$app->user->can('view-receipt'))   
        {        
            throw new ForbiddenHttpException;
            die();
        }
        
            $model = $this->findModel($receipt_no, $ccid);
                    
            $model->receipt_date=date('d-m-Y',strtotime($model->receipt_date));                   
            $modelsReceiptitems = $model->receiptitems;
            
            $student = $this->findStudentDetails($model->students_admission_number,$ccid);

            $cent = Center::findone(['ccid'=>$ccid]);
            
            $html = $this->renderPartial('receipt-print',[
                'model' => $model,
                'modelsReceiptitems' => $modelsReceiptitems,
                'student' => $student,
                'centerAddress'=>$cent['address'],
                ]);
                        
                //$imgSrc = Yii::$app->urlManager->createAbsoluteUrl('site/loadimage');
$mpdf = new mPDF('utf-8', 'A4',0,'',15,15,5,5,4,9,'P');
//$mpdf->WriteHTML('<watermarkimage src='.$imgSrc.' alpha="0.33" size="50,30"/>');
$mpdf->showWatermarkImage = true;
$mpdf->WriteHTML($html);
$mpdf->Output($title.'.pdf', "I");
            
        
    }



mPDF settings to Custom Paper Size

How to set the page in landscape mode in mpdf ?



// Define a Landscape page size/format by name
$mpdf=new mPDF('utf-8', 'A4-L');

mPDF set to half of paper size A4 


They even give an example with custom size:
Example with a custom 210x148 mm page size:
$pdf = new FPDF('P','mm',array(210,148));

$mpdf = new mPDF('utf-8', array(210,148),0,'',15,15,5,5,4,9,'P');






YII2 Grid View Advanced Options


INDEX
Karthik Grid View
How to group data in Grid View
Grid View Export Configuration



Karthik Grid View


GridView Demo yii2-grid

GridView yii2-grid Installation and more options


           Karthik Gridview Expand







How to group data in Grid View

Demonstration examples and scenarios for Grouping data using \kartik\grid\GridView





Grid View Export Configuration


Example Grid Code:

$exportFilename = 'custom-filename_' . date("Y-m-d_H-m-s");

        $exportConfig = [

            GridView::HTML  => [
                'label'           => 'HTML',
                'icon'            => 'file-text',
                'iconOptions'     => ['class' => 'text-info'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The HTML export file will be generated for download.',
                'options'         => ['title' => 'Hyper Text Markup Language'],
                'mime'            => 'text/html',
                'config'          => [
                    'cssFile' => 'http://netdna.bootstrapcdn.com/bootstrap/3.1.0/css/bootstrap.min.css'
                ]
            ],
            GridView::CSV   => [
                'label'           => 'CSV',
                'icon'            => 'file-code-o',
                'iconOptions'     => ['class' => 'text-primary'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The CSV export file will be generated for download.',
                'options'         => ['title' => 'Comma Separated Values'],
                'mime'            => 'application/csv',
                'config'          => [
                    'colDelimiter' => ",",
                    'rowDelimiter' => "\r\n",
                ]
            ],
            GridView::EXCEL => [
                'label'           => 'Excel',
                'icon'            => 'file-excel-o',
                'iconOptions'     => ['class' => 'text-success'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The EXCEL export file will be generated for download.',
                'options'         => ['title' => 'Microsoft Excel 95+'],
                'mime'            => 'application/vnd.ms-excel',
                'config'          => [
                    'worksheet' => 'Worksheet',
                    'cssFile'   => ''
                ]
            ],
            GridView::PDF   => [
                'label'           => 'PDF',
                'icon'            => 'file-pdf-o',
                'iconOptions'     => ['class' => 'text-danger'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The PDF export file will be generated for download.',
                'options'         => ['title' => 'Portable Document Format'],
                'mime'            => 'application/pdf',
                'config'          => [
                    'mode'          => 'c',
                    'format'        => 'A4-L',
                    'destination'   => 'D',
                    'marginTop'     => 20,
                    'marginBottom'  => 20,
                    'cssInline'     => '.kv-wrap{padding:20px;}' .
                        '.kv-align-center{text-align:center;}' .
                        '.kv-align-left{text-align:left;}' .
                        '.kv-align-right{text-align:right;}' .
                        '.kv-align-top{vertical-align:top!important;}' .
                        '.kv-align-bottom{vertical-align:bottom!important;}' .
                        '.kv-align-middle{vertical-align:middle!important;}' .
                        '.kv-page-summary{border-top:4px double #ddd;font-weight: bold;}' .
                        '.kv-table-footer{border-top:4px double #ddd;font-weight: bold;}' .
                        '.kv-table-caption{font-size:1.5em;padding:8px;border:1px solid #ddd;border-bottom:none;}',
                    'methods'       => [
                        'SetHeader' => [
                            ['odd' => $ourPdfHeader, 'even' => $ourPdfHeader]
                        ],
                        'SetFooter' => [
                            ['odd' => $ourPdfFooter, 'even' => $ourPdfFooter]
                        ],
                    ],
                    'options'       => [
                        'title'    => 'Custom Title',
                        'subject'  => 'PDF export',
                        'keywords' => 'pdf'
                    ],
                    'contentBefore' => '',
                    'contentAfter'  => ''
                ]
            ]
        ];



Example and usage


echo GridView::widget([

    'dataProvider' => $dataProvider,
    'formatter' => ['class' => 'yii\i18n\Formatter','nullDisplay' => ''],
    'columns' => $gridColumns,   
    
    'containerOptions' => ['style'=>'overflow: auto',], // only set when $responsive = false
    
    'pjax' => true,
      
    'beforeHeader'=>[
            [
            'columns'=>[
            ['content'=>$content, 'options'=>['colspan'=>count($gridColumns), 'class'=>'text-left warning']],            
            ],
            //'options'=>['class'=>'skip-export'] // remove this row from export
            ]
            ],
    
    
    'bordered' => true,
    'striped' => false,
    'condensed' => false,
    'responsive' => true,
    'hover' => true,
    'floatHeader' => true,
    //'floatHeaderOptions' => ['scrollingTop' => $scrollingTop],
    //'showPageSummary' => true,
    'panel' => [
        'type' => GridView::TYPE_PRIMARY,    
        'before' => 'Date : '.date('d-m-Y'),
        'heading' => '<i class="glyphicon glyphicon-user"></i>&nbsp;<b>UNIVERSITY PAYMENT REPORT</b>',
        //'after' => 'Search Criteria : '.$query,
        //'showFooter' => false,
    ],
    
    
    'exportConfig' => [
                 GridView::CSV   => [
                'label'           => 'CSV',
                'icon'            => 'file-code-o',
                'iconOptions'     => ['class' => 'text-primary'],
                'showHeader'      => FALSE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The CSV export file will be generated for download.',
                'options'         => ['title' => 'Comma Separated Values'],
                'mime'            => 'application/csv',
                'config'          => [
                    'colDelimiter' => ",",
                    'rowDelimiter' => "\r\n",
                ]
            ],
            GridView::EXCEL => [
                'label'           => 'Excel',
                'icon'            => 'file-excel-o',
                'iconOptions'     => ['class' => 'text-success'],
                'showHeader'      => TRUE,
                'showPageSummary' => TRUE,
                'showFooter'      => TRUE,
                'showCaption'     => TRUE,
                'filename'        => $exportFilename,
                'alertMsg'        => 'The EXCEL export file will be generated for download.',
                'options'         => ['title' => 'Microsoft Excel 95+'],
                'mime'            => 'application/vnd.ms-excel',
                'config'          => [
                    'worksheet' => 'Worksheet',
                    'cssFile'   => ''
                ]
            ],
            ],

   
      
     // set your toolbar
    'toolbar'=> [
        ['content'=>
            Html::a('<i class="glyphicon glyphicon-plus"></i>',['universitypayment/index'], ['title'=>'Add New Criteria', 'class'=>'btn btn-success']), 
            
        ],
        '{export}',
        //'{toggleData}',
    ],
        
]);




Some examples of grid export
http://demos.krajee.com/grid#grid-export





Wednesday 2 September 2015

Yii2 Validation

Yii2 Validate value without model

Ad Hoc Validation


Yii2 email Validate without model


Sometimes you need to do ad hoc validation for values that are not bound to any model.
If you only need to perform one type of validation (e.g. validating email addresses), you may call the validate() method of the desired validator, like the following:

$email 'test@example.com';$validator = new yii\validators\EmailValidator();

if ($validator->validate($email$error)) {
    echo 'Email is valid.';
} else {
    echo $error;
}




PHP Code for email validation

Validating email addresses with filter_var()

<?php

$email_a = 'joe@example.com';
$email_b = 'bogus';

if (filter_var($email_a, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_a) email address is considered valid.";
}
if (filter_var($email_b, FILTER_VALIDATE_EMAIL)) {
    echo "This ($email_b) email address is considered valid.";
}

?>