Convert HTML to pdf using mpdf plugin in cakePHP

|
| By Webner

How to use mpdf plugin in cakePHP to convert HTML documents to pdf?

mPDF is a PHP library which is used to generate PDF files from HTML Documents. It converts utf-8 encoded documents and also supports almost all languages including Arabic and Hebrew. It includes css stylesheets and images in JPG, GIF, PNG, SVG, BMP or WMF format. It can also be used for protection of the document using a password.

Sample code in cakephp that is used for converting HTML document to pdf :-

use mpdf;  // add mpdf library to the controller

// path of mpdf library included
require_once (ROOT .DS. 'vendor' .DS. 'mpdf' .DS. 'mpdf.php'); 

//Mpdf class containing pdf parameters which defines page size (A4-L),character set(utf-8), margin,padding,orientation(L- Landscape) etc.	
$mpdf = new mpdf('utf-8','A4-L','','','0','0','0','0','L');

//Cakephp set method to set the dynamic value of the variable declared in pdf html.
$this->set('courseName', $this->request->data['courseName']); $this->set('primaryColor', $this->request->data['primaryColor']);	

 //Cakephp method to render the ctp file containing pdf html that needs to be converted.
$pdfHtml = $this->render('course_certificate');         

$pdfHtml = $pdfHtml->body();    // get only the html from complete rendered element.

$pdfName = 'Certificate.pdf'; //name of the pdf file

$mpdf->SetAuthor('CustomGuide'); // author added to pdf file

$mpdf->SetTitle('Certificate’); // title that is shown when pdf is opened in browser

$mpdf->WriteHTML($pdfHtml);	//function used to convert HTML to pdf

$mpdf->showImageErrors = true;    // show if any image errors are present

$mpdf->debug = true;	// Debug warning or errors if set true(false by default)
$mpdf->Output($pdfName,'I'); 	//output the pdf file

Output function includes two parameters:-
->name of pdf file
->Destination where to send the file
->Inline(‘I’) i.e. used to open in the same browser window
->Download(‘D’) i.e. used for downloading of pdf file
-> File(‘filepath’) i.e save to a local file path
-> String_return i.e. returns the document as a string

Note:- If the Destination is not given in output function it is included Inline by default.

Leave a Reply

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