HTML TO PDF

This post will help you generate a pdf files in yii framework. I used tcpdf to create a pdf file. Pdf file based on html page. What you see in html page, You can download as pdf using this.

Download TCPDF

Download the tcpdf files using below link to generate html to PDF files.
Download HTML2PDF
Extract the download files and you will get following folders and files Folder

FOLDER:
_class     
_tcpdf_5.0.002
locale

FILES:
html2pdf.class

Create HTML2PDF Extension

After extracted folder, Create new folder inside extension of yiiframework as “tcpdf”.
Copy above files (html2pdf.class) and folders (_class, _tcpdf_5.0.002, locale) and paste it into “tcpdf” folder. “html2pdf.class” has contains “HTML2PDF” class. I rename “html2pdf.class” file name as “HTML2PDF” (For my use)

Controller: HtmltopdfController.php

<?php
class HtmltopdfController extends Controller
{    
	public function actionIndex()
	{
		$this->render('index');
	}
    public function actionPdf()
	{
		$this->renderPartial('html2pdf');
	}
}
?>

View: html2pdf.php

<?php
    ob_start();
    echo $this->renderPartial('htmlpage'); 
    $content = ob_get_clean();

    Yii::import('application.extensions.tcpdf.HTML2PDF');
    try
    {
        $html2pdf = new HTML2PDF('P', 'A4', 'en');
//      $html2pdf->setModeDebug();
        $html2pdf->setDefaultFont('Arial');
        $html2pdf->writeHTML($content,false);
        $html2pdf->Output("pdfdemo.pdf");
        
    }
    catch(HTML2PDF_exception $e) {
        echo $e;
        exit;
    }
?>

View: htmlpage.php

<style type="text/css">
h1{
    color:red;
    text-align: center;
}
table{
    margin: auto;
    border: 1px solid gray;
}
table td,table th{
    border: 1px solid gray;
    border-collapse: collapse;
    padding: 5px;
}
</style>
<page>
<div>
<img src="https://static.yiiframework.com/files/logo/yii.png" title="yii logo" />
<h1>
YII HTML TO PDF DEMO
</h1>
</div>
<br /><br /><br />
<table>
    <tr><th>TITLE</th><th>LINK</th></tr>
    <tr><td>BSOURCECODE</td><td><a href="https://www.bsourcecode.com/">https://www.bsourcecode.com</a></td></tr>
    <tr><td>DEMO BSOURCECODE</td><td><a href="http://demo.bsourcecode.com/">http://demo.bsourcecode.com</a></td></tr>
    <tr><td>YII FRAMEWORK</td><td><a href="http://www.yiiframework.com">http://www.yiiframework.com</a></td></tr>
</table>
</page>    

Leave a Reply

Your email address will not be published. Required fields are marked *