Make Pdf in Cakephp with UTF-8 for print in label printer

mobin shaterian
3 min readSep 17, 2020

Cakephp is one of the PHP frameworks that famous for agile. in this article demonstrate step by step make Pdf file with Tcpdf library in Cakephp for label print invoice of the customer with UTF-8 characters and using label print size for pdf.

at this moment I realize that CakePHP 4 has come and I still using cakephp3 . one the big nightmare of the developer is changing everything in any minute and I should update my system immediately.

Tcpdf is powerfull library of PHP can make easily pdf and it’s open source.

tcpdf has composer for cakephp4, with command below can install it easly.

composer require friendsofcake/cakepdf

unfortunately, composer is not compatible with Cakephp version 3 so let’s do it in another way.

download Tcpdf

it’s very easy, just going to github of Tcpdf and git clone codes.

put download folder in Vendor folder of cakephp.I make folder /vendor/TCPDF and put file in there.

layout

as you know very page has layout format. for print PDF file make file in /src/Template/Layout/pdf.ctp

and put code below :

<?php
header(“Content-type: application/pdf”);
echo $this->fetch(‘content’);

?>

Controller

in controller using TCPDF library by calling vendor class.

require_once(ROOT . DS . ‘vendor’ . DS . ‘TCPDF’ . DS . ‘tcpdf.php’);

Declare page Size

define instant of Tcpdf class and setup page size 350 X 250 . using l for landscape pdf page. using UTF-8 for using Persian words.

$width = 350;
$height = 200;
$pageLayout = array( $height , $width); // or array($height, $width)
$pdf = new \TCPDF(‘l’, ‘pt’, $pageLayout, true, ‘UTF-8’, false);

remove header and footer

I want to make some kind of invoice that print on package so remove the footer and header of pdf.

$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);

Set some language dependent data:

$lg = Array();
$lg[‘a_meta_charset’] = ‘UTF-8’;
$lg[‘a_meta_dir’] = ‘rtl’;
$lg[‘a_meta_language’] = ‘fa’;
$lg[‘w_page’] = ‘page’;

$pdf->setLanguageArray($lg);

Set a font:

// set font
$pdf->SetFont(‘dejavusans’, ‘’, 12);
$pdf->SetAutoPageBreak(true, 0);

add a page:

$pdf->AddPage();

write Text:

$text = “گیرنده :” . $variable[‘user’][‘name’];

// Persian and English content
$pdf->WriteHTML($text, true, 0, true, 0);

// set LTR direction for english translation
$pdf->setRTL(true);

$pdf->SetFontSize(10);

next Line:

$pdf->Ln();

Make pdf file:

$pdf->Output(‘test.pdf’, ‘I’);

--

--