Seleccionar página

How to create and save PDF files with CakePHP 2 and TCPDF.

Download TCPDF and unzip.

Move folder to /app/Vendor and rename to tcpdf Create /app/Vendor/xtcpdf.php


class XTCPDF extends TCPDF{


Create app/View/Layouts/pdf/default.ctp


header("Content-type: application/pdf");

echo $content_for_layout;

In your Controller, for example in PostsController create a new action:

public function create_pdf(){

	$users = $this->User->find('all');


	$this->layout = '/pdf/default';



Create a new view file /app/View/Pdf/my_pdf_view.ctp



$pdf = new XTCPDF('L', PDF_UNIT, 'A4', true, 'UTF-8', false);


$html = '</pre>
<h1>hello world</h1>

foreach ( $posts as $post ){
	$html .= '

$pdf->writeHTML($html, true, false, true, false, '');


echo $pdf->Output(APP . 'files/pdf' . DS . 'test.pdf', 'F');

More details and examples about configuring the pdf you’ll find here:

Output ‘F’ will save the file to disk.
Make sure that /app/files/pdf/ exists and is writable for the Webserver user.

If you save in /app/files/pdf, the generated PDF’s are not accessible vía an URL.

If you don’t want to save the generated pdf file outside web root, you can save to WEBROOT_DIR/files/pdf instead of APP/files/pdf.
So the generated PDF’ are accessible vía

If you saved the PDF file outside webroot in /app/files/pdf/test.pdf, you can offer (for example only to logged in users) this link to download the PDF:

For this link you need to create this action in PostsController (or any other contoller you want to use):

public function download_pdf() {

	$this->viewClass = 'Media';

	$params = array(

		'id' => 'test.pdf',
		'name' => 'your_test' ,
		'download' => true,
		'extension' => 'pdf',
		'path' => APP . 'files/pdf' . DS



If you only want to show the PDF (without download), you can create the action public function show_pdf().

show-pdf() is the same as download_pdf(), but change ‘download’ => true to ‘download’ => false

More about media views in CakePHP you’ll find here

that’s all folks

Now you can create the pdf file with:

You’ll find the created .pdf file in /app/files/pdf/test.pdf
(every call overwrites the existing file. To avoid create for example file names with date and time the name.)

You can show the pdf file in the browser with:

You can download the pdf file with:

I hope that helps someone 🙂

Regards, Martin