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

<?php
App::import('Vendor','tcpdf/tcpdf');

class XTCPDF extends TCPDF{

}

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

<?php

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->set(compact('users'));

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

	$this->render('/Pdf/my_pdf_view');

}

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

<?php

App::import('Vendor','xtcpdf');

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

$pdf--->AddPage();

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

foreach ( $posts as $post ){
	$html .= '
'.$post['Post']['title'];
}

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

$pdf->lastPage();

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

More details and examples about configuring the pdf you’ll find here:
http://www.tcpdf.org/examples.php.

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 www.yourdomain.com/files/pdf/test.pdf

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:
www.yourdomain.com/posts/download_pdf/your_test.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
	);

	$this->set($params);

}

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 http://book.cakephp.org/2.0/en/views/media-view.html

that’s all folks

Now you can create the pdf file with:
www.yourdomain.com/posts/create_pdf

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:
www.yourdomain.com/posts/show_pdf

You can download the pdf file with: www.yourdomain.com/posts/download_pdf

I hope that helps someone 🙂

Regards, Martin
www.martin-schenk.es