In yii2, we can generate pdf using yii2-mpdf (kartik).
So, in this tutorial i will show you how to generate a pdf included with text, image, and link.
Let’s start the tutorial :
INSTALL
1) Install kartik-mdpf by composer :
composer require kartik-v/yii2-mpdf "dev-master"
HOW TO USE
3) Now, create file MpdfController.php inside fronted/controllers/ and copy script below :
<?php
namespace frontend\controllers;
use Yii;
use yii\web\Controller;
use kartik\mpdf\Pdf;
use yii\helpers\Url;
class MpdfController extends Controller
{
public function actionReport() {
// get your HTML raw content without any layouts or scripts
$content = "
<b style='color:red'>bold</b>
<img src='".Url::to('@web/img/ava.gif', true)."'/>
<a href='http://latcoding.com'>Latcoding.com</a>
";
// 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',
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>['THIS IS REPORT'],
'SetFooter'=>['{PAGENO}'],
]
]);
// http response
$response = Yii::$app->response;
$response->format = \yii\web\Response::FORMAT_RAW;
$headers = Yii::$app->response->headers;
$headers->add('Content-Type', 'application/pdf');
// return the pdf output as per the destination setting
return $pdf->render();
}
}
– Line 6, we must put kartik\mpdf\Pdf to call the class of PDF.
– Line 14, we can put (HTML and CSS) to making the content.
** To include an image, you have to put your image in frontend/web/img/
– Line 21 is configuration of mpdf. You can set format of letter, orientation, header, page number and etc.
– Line 43 is response header. It is used so that the pdf file can be downloaded.
– Line 49 is output your pdf.
4) The last, test your pdf. Open :
http://localhost/yii2advanced/frontend/web/index.php?r=mpdf/report
After you open that url, it will be downloaded an pdf :

This contain :




