Creating PDF files with CakePHP and TCPDF
TCPDF is an Open Source PHP class for generating PDF documents. It continues where FPDF stopped, and contains all its goodies plus support of UTF-8 Unicode and Right-To-Left languages! Especially the missing UTF-8 Unicode support in FPDF is a problem for everyone living outside the English language only countries.
Step 1: Download and install TCPDF
- Go to http://www.tcpdf.org and download the latest version of TCPDF.
- Extract to one of your vendors folders, such as app/vendors. It will create a directory tcpdf there with tcpdf.php and more in it. You need at least the folders tcpdf/config and tcpdf/fonts in your application.
- Configure TCPDF, see its documentation. You want at least to have a look at tcpdf/config/tcpdf_config.php.
Step 2: Extend TCPDF to customize your header and footer
There is a default header and footer in TCPDF, defined in a header() and a footer() method, which is supposed to be overwritten by you, if needed. This can be done by extending TCPDF and then calling this extended TCPDF class from your application.
In app/vendors create the file xtcpdf.php with this content:
Download code
<?php
App::import('Vendor','tcpdf/tcpdf');
class XTCPDF extends TCPDF
{
var $xheadertext = 'PDF created using CakePHP and TCPDF';
var $xheadercolor = array(0,0,200);
var $xfootertext = 'Copyright © %d XXXXXXXXXXX. All rights reserved.';
var $xfooterfont = PDF_FONT_NAME_MAIN ;
var $xfooterfontsize = 8 ;
/**
* Overwrites the default header
* set the text in the view using
* $fpdf->xheadertext = 'YOUR ORGANIZATION';
* set the fill color in the view using
* $fpdf->xheadercolor = array(0,0,100); (r, g, b)
* set the font in the view using
* $fpdf->setHeaderFont(array('YourFont','',fontsize));
*/
function Header()
{
list($r, $b, $g) = $this->xheadercolor;
$this->setY(10); // shouldn't be needed due to page margin, but helas, otherwise it's at the page top
$this->SetFillColor($r, $b, $g);
$this->SetTextColor(0 , 0, 0);
$this->Cell(0,20, '', 0,1,'C', 1);
$this->Text(15,26,$this->xheadertext );
}
/**
* Overwrites the default footer
* set the text in the view using
* $fpdf->xfootertext = 'Copyright © %d YOUR ORGANIZATION. All rights reserved.';
*/
function Footer()
{
$year = date('Y');
$footertext = sprintf($this->xfootertext, $year);
$this->SetY(-20);
$this->SetTextColor(0, 0, 0);
$this->SetFont($this->xfooterfont,'',$this->xfooterfontsize);
$this->Cell(0,8, $footertext,'T',1,'C');
}
}
?>
Of course, customize this to show your organization's name etc., and modify the code as you like. See the TCPDF documentation for details.
Step 3: Create your layout for PDF
You cannot use your default layout, as it would wrap the PDF file in your HTML page code. You need a layout such as this one, save it as app/views/layouts/pdf.ctp :
Download code
<?php
header("Content-type: application/pdf");
echo $content_for_layout;
?>
Step 4: For your Controller
In your controller you will have a method which will output the PDF. This here is the code as it is used in one of my real world applications to print a nice PDF page with data and pictures about a property:
Download code
function viewPdf($id = null)
{
if (!$id)
{
$this->Session->setFlash('Sorry, there was no property ID submitted.');
$this->redirect(array('action'=>'index'), null, true);
}
Configure::write('debug',0); // Otherwise we cannot use this method while developing
$id = intval($id);
$property = $this->__view($id); // here the data is pulled from the database and set for the view
if (empty($property))
{
$this->Session->setFlash('Sorry, there is no property with the submitted ID.');
$this->redirect(array('action'=>'index'), null, true);
}
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
}
Adapt to your needs. The critical part is just to select the PDF layout before rendering.
Download code
$this->layout = 'pdf'; //this will use the pdf.ctp layout
$this->render();
Step 5: For your View
Here is where the magic happens. Because with CakePHP we can load the vendor directly in the view we do not need to wrap it in a helper. So the big TCPDF library with currently 9600 lines of code in the main class tcpdf.php alone will only get loaded when we really need it, that is when we actually create the PDF file. The vendor is now used here like an external helper. Note: I do not know if that was intended or not, but the more I think about it the more I like it, it's so elegant and efficient, and demonstrates the power and flexibility of CakePHP.
But enough said, here's the code for the view:
View Template:
Download code
<?php
App::import('Vendor','xtcpdf');
$tcpdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed than 'dejavusans'
$tcpdf->SetAuthor("KBS Homes & Properties at http://kbs-properties.com");
$tcpdf->SetAutoPageBreak( false );
$tcpdf->setHeaderFont(array($textfont,'',40));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'KBS Homes & Properties';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All rights reserved.';
// Now you position and print your page content
// example:
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',20);
$tcpdf->Cell(0,14, "Hello World", 0,1,'L');
// ...
// etc.
// see the TCPDF examples
echo $tcpdf->Output('filename.pdf', 'D');
?>
That was easy! Yes, that's all.
The Questions and Answers below are only of interest for users of the FPDF helper.
Why not FPDF?
For me the main reason is that there is no Unicode support. You can add a limited unicode support to it, as described on the Dievolution blog, by hacking the Cell method of FPDF, but then, why not go for TCPDF right away. No hack needed, and the TCPDF author, Nicola Asuni, is very active, releasing a new update almost every week.
How about the FPDF helper, as shown here in the bakery?
I used this helper quite a lot, it worked fine with CakePHP 1.1. Somewhere between the 1.2 beta and 1.2 RC it stopped working though. The reason IMHO is that it is not implemented correctly.
It extends the FPDF class directly, but a Helper should extend a Helper, such as the AppHelper class.
This is what the FPDF helper does, works worked with CakePHP 1.1, but wrong:
class FpdfHelper extends FPDF
This would be correct but it does not work:
Download code
class FpdfHelper extends AppHelper
Somewhere in the CakePHP 1.2 development a change happened which was that helpers receive an array as first argument when they are initialized. A Helper which extends AppHelper expects that and handles it correctly, but FPDF does not know what to do with that array, as it expects as first argument the page orientation.
Can the FPDF Helper be hacked to continue working with CakePHP 1.2?
Yes, it can, but this should be not the solution, as it is not needed (as shown above). Simply add this line in the FPDF code (the one in your vendors directory, not the helper), as first line of the FPDF method, which is in my FPDF version at line 78:
Download code
if (is_array($orientation)) return;
it will then be:
Download code
function FPDF($orientation='P',$unit='mm',$format='A4')
{
if (is_array($orientation)) return;
...
This will make it ignore the Helper initialization, but let it run fine when it is called later, via
Download code
$this->FPDF($orientation, $unit, $format);
in the FPDF helper's setup() method.
Why is this FPDF hack not needed in CakePHP 1.2?
FPDF and TCPDF are external libraries, which you can integrate in CakePHP under Vendors. Now CakePHP 1.2 changed the way Vendors are included from
Download code
vendor("fpdf/fpdf")
to Download code
App::import('Vendor','fpdf/fpdf');
- or for TCPDF: -
App::import('Vendor','tcpdf/tcpdf');
This alone does not change too much though. Still, you would need a helper to wrap the TCPDF calls to use them in your view, similar to:
Helper Class:
Download code
<?php <?php
App::import('Vendor','xtcpdf');
class TcpdfHelper extends AppHelper {
var $pdf;
function setup() {
$this->pdf = new XTCPDF();
}
}
?>?>
and then call $tcpdf->pdf->whatevertcpdfmethodyouneed() from your view.Fortunately this is not needed, because in CakePHP 1.2 RC2 you can now use App::import directly in the view. As shown above :)
Comments
Comment
1 TCPDF path configuration
maybe you should spent a little more on how you set tcpdf paths in configuration file.
I tried to make it run bur I always got "TCPDF error: Could not include font definition file".
Nice post, really interesting.
Bye!!
Comment
2 Error: Fatal error: Class 'XTCPDF' not found in C:\xampp\htdocs\cake12\CakePHP\app\views\books\view_pdf.ctp on line 3
I followed the tutorial but having some problem:
Following is the error...
Question
3 Always get an empty page
Any help would be appreciated.
draikin
Comment
4 Reverse in Persian problem
Comment
5 I only get a blank page
Comment
6 permissions
I had a problem getting it to work at the beginning until I gave the whole tcpdf dir a 755 permission. the instructions are not clear on the TCPDF site about how to set the permissions and it would not work for me easily until I did this. I use XAMPP
Comment
7 Only get an empty page
draikin
Comment
8 Hints to troubleshoot problems
* www-data (or whatever user your webserver is running as) has read access to tcpfg/ -R
* increase memory limit in php.ini
* remove "echo" before "$tcpdf->Output"
Bug
9 No 'Hello, world' until I added AddPath()...
Example worked OK, but didn't see "Hello, world." until I added
$tcpdf->AddPath();in the view in front of the SetTextColor() bit.Also, it showed up inside the header, until I repositioned it from Cell(0,14, ...); to Cell(75,75, ...); May just need $tcpdf->lastPath(); ahead of the AddPath();
Using writeHTML() for now to keep it 'easy' making invoices and POs, but when I learn about headers and footers, I'll figure out why "Hello, world" was inside the header...
regards,
oh4real
Comment
10 Great article
Comment
11 Great article
Question
12 How to print table data?
However, it would be very nice to go one step further and show how to use this thing in a more productive way - say how would you print your models to pdf? How would you print tabe data?
Comment
13 Why not as a component? Help fight climate warming!
Of course this depends on your content, but if you have an article or a newsitem or a tutorial like this page and the content will not change very fast or maybe never - it would be much better design to generate the pdf after inserting or updating and keep the generated pdf downloadable and link to it.
I do not understand cake very well right now, but I think a component would be the right place for this kind of thing... I will check that out later.
Comment
14 Don't forget AddPage()
$tcpdf->AddPage();
in the view right before:
$tcpdf->SetTextColor(0, 0, 0);
in the view fixed it.
Comment
15 Apology
Comment
16 @Muhammad Mohsin Ali:
View Template:
before you callApp::import('Vendor','xtcpdf');
View Template:
If xtcpdf.php with the Class XTCPDF is in app/vendors, and no typos etc, then it will be found.$tcpdf = new XTCPDF();
Comment
17 Problems with some TCPDF versions
A few moths ago I needed to move a site with this code running from one server to another, and used the opportunity to update cake and tcpdf. All fine on the development server, but not on the production server.
Similar problems as you saw, it just didn't work, something with the fonts was messed up. It printed lines, borders, but no fonts. Which is kinda stupid :(
The solution was to rollback TCPDF to the old version. And again, working like a charm :) for an example see http://kbs-properties.com/properties/view/46 - click on the PDF icon at the top right above the content.
The working version was TCPDF 4.0.017 with release date 2008-08-05, the problematic one TCPDF 4.5.023 with release date: 2009-03-06.
Comment
18 clearing header area
View Template:
$pdf->SetAutoPageBreak( true, 25 );
$pdf->SetTopMargin(34);
Comment
19 How to print table data?
Comment
20 Saving CPU cycles
However, as you say, such code should only be used for dynamic data, such as vouchers, or price lists with limited validity. If you have static data, then offer a static PDF file for download.
FPDF has a problem with unicode, it cannot mix e.g. English and Thai. A big thank to Nicola Asuni to have bloated ;) TCPDF to fix that..
Comment
21 AddPage()
As mentioned earlier, TCPDF is seeing a lot of development, so that might be just one visible result.
The code in the view, as I use it now, has changed to:
View Template:
App::import('Vendor','xtcpdf');
$pdf = new XTCPDF();
$textfont = 'freesans'; // looks better, finer, and more condensed than 'dejavusans'
$footerHeight = 25;
$tcpdf->SetAuthor("KBS Homes & Properties at http://kbs-properties.com ");
$tcpdf->SetAutoPageBreak( true, $footerHeight );
$tcpdf->SetTopMargin(34);
$tcpdf->setHeaderFont(array($textfont,'',40));
$tcpdf->xheadercolor = array(150,0,0);
$tcpdf->xheadertext = 'KBS Homes & Properties';
$tcpdf->xfootertext = 'Copyright © %d KBS Homes & Properties. All rights reserved.';
// Now you position and print your page content
// example:
$tcpdf->AddPage();
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',20);
$tcpdf->Cell(0,14, "Hello World", 0,1,'L');
// ...
// etc.
// see the TCPDF examples
echo $tcpdf->Output('filename.pdf', 'D');
?>
Question
22 Download error
Using the code as is in this tutorial, I see only this error message:
" TCPDF ERROR: Some data has already been output, can't send PDF file". Only when I change the output type 'D' to 'S', in the Output method of the $tcpdf method, can I see the PDF file in the browser.
I have reviewed the files of PHP controllers, models and helpers, and I've removed all the spaces that were before " Php", but I do not get a direct download of the PDF file.
What can be wrong?
Comment
23 < >
The comment above was posted May 11, 2009 by Claudio Juan Böhm but it is not displayed completely because he uses < > in it and the bakery comment validation lets it through without sanitation. Konqueror gets a big hiccup, Firefox not so much. Anyway, see the missing part in the quote in the next comment, which is my reply to it.
Comment
24 @Claudio Juan Böhm
You mention that you checked "controllers, models and helpers", but how about view and layout? See the pdf.ctp in app/views/layouts/pdf.ctp which should look as described above, and then set in the controller with $this->layout = 'pdf'; before calling $this->render();
oh yes, and check also for spaces after the PHP closing tag, not just before the PHP opening tag
Comment
25 about __view() and AddPath()
// Configure::write('debug',0)The first problem was caused by this line:
$property = $this->__view($id); // here the data is pulled from the database and set for the viewThis '$this->__view()' function is an author function, not Cake native, as I'd supposed it was. This is the error:
The second detail is about using the AddPath() in the view:
$tcpdf->AddPath();Because it generates this error:
This can resolve the problem of the blank screen.
I hope this comment could be useful to save time. These little details make programmers lose hours or even days to find the solution.
Sorry for the mediocre english :P
Comment
26 $this->__view($id);
Of course it is! Please have a look at whats written right above that sample code:
So in your controller you need to do whatever is needed to pull any data you might want to publish from your database and set it.
In my application the "view" and the "viewPdf" share the same data, and while the "view" optimizes it for screen display, "viewPdf" optimizes for PDF display. They share the same code to pull and set the data, which I have combined in $this->__view($id); as said there:
So adapt that to your data and your needs please.
As you might have seen, my sample code above does not contain $tcpdf->AddPath() so I don't know where and why you have added it.
There are many different versions of TCPDF out there, and many different server environments. Some seem to need it (see comment 9 from Dec 24, 2008 by ohforreal), others not.
In any case, if you get a blank screen, your approach to re-enable debug output by commenting the line
Configure::write('debug',0)
is a good and fast way to see any error messages.
Comment
27 View to pdf
Comment
28 @umit celik
If you explain where you're stuck I can try to answer more specific.
Comment
29 TCPDF 4.6.013 needs PHP set to more than 16 MB
However if you want to use one of the best features, Unicode support, and the included font which supports it best, freeserif, you might run into internal server errors, resulting in nice white pages. The reason is that freeserif has been doubling its size, probably supporting more and more, but with the side effect of using more memory. if your server is configured to allow PHP 16 MB RAM, then that is not enough.
Even without using freeserif, but freesans, after half a page of content the same error seems to be happening.
Either adjust the value in your php.ini on your server, or add the line
php_value memory_limit 36M
to your .htaccess and all is fine, the error is gone and the pages are not so white anymore.
Comment
30 Output files don't seem to be recognized by adobe
The first few lines of the pdf file when I open it up in a text editor look like:
%PDF-1.7
3 0 obj
<</Type /Page
/Parent 1 0 R
/MediaBox [0 0 595.28 841.89]
/Resources 2 0 R
/Contents 4 0 R>>
endobj
4 0 obj
<</Filter /FlateDecode /Length 245>>
stream
Comment
31 scratch my last comment
my version of Adobe Reader was the problem.
Question
32 Merging PDFS?
Comment
33 Check for spaces in all the files included in the controller
I had the same problem, but I found spaces after the closing ?> tag in one of the models included in the controller that uses the tcpdf and the vendor class xtcpdf.php file.
So take the time and check all the included views, controllers and models. Do not forget to check the app_controller.php and the app_model.php as well.
Just thought this might help someone that get the same error.
Comment
34 Problem forcing save on pdf
$tcpdf->Output('filename.pdf', 'F');Using the F parameter in the output function to force the save to disk, creates the pdf, and saves it to disk properly, however, i am still left with a popup error everytime from Adode Reader..."File does not begin with '%PDF-'" ...almost like it is still trying to display the pdf to the screen as well. Does anyone know how i can just save it to disk, for future use, without ever outputting anything to the screen?
Comment
35 @Robert, saving pdf to disk instead of download
Robert, you probably still send the layout as shown in the article to the browser, with
header("Content-type: application/pdf");This will make your browser start your PDF viewer, and then you send nothing, because you save to disk only. Thus the error message of your PDF viewer.In your case you need neither the layout as shown in this article, nor the call for it in the controller as shown in this article.
$this->layout = 'pdf'; //this will use the pdf.ctp layoutJust take it off.The easiest way to get what you want is probably to add in the view, after your
$tcpdf->Output('filename.pdf', 'F');a regular cake view code, such as for a confirmation page saying that the pdf file was saved, or whatever else you want to display after you saved that pdf.Comment
36 how to create the pdf form using tcpdf
I have installed the tcpdf and watch the examples of that but the example number 14 is not working. please help me ..to get pdf form..
Thank you..
Comment
37 The view will not open as pdf file
I just have a simple view with lots of characters not adobe.
Comment
38 what version od Adobe did you use?
Comment
39 Every (more or less recent) PDF Reader should work
Azita, TCPDF produces PDF code, which should be readable with every PDF reader. I have testet several Adobe PDF reader versions on various OS', such as Linux, Mac, Windows Vista and XP, and other PDF readers such as KPDF (Linux's KDE 3.x) and Okular (Linux's KDE 4.x). I have neither encountered this problem, nor has a customer using one of my real life applications using TCPDF reported it.
I have not tested it with very old versions of Adobe reader though.
Azita, which version did you use which showed this problem?
Comment
40 basic questions
Questions:
1 - what should the controller class name be? (class name XtcpdfsController? file name xtcpdfs_controller.php?)
2 - does the controller class need to import XTCPDF?
3 - what should the view directory be named? (xtcpdfs? pdfs?)
4 - what should the view file name be? (view.ctp?)
5 - Any chance you could post a working barebones version of the whole thing?
Thanks!
Comment
41 Re: basic questions
This really depends on your application. It has nothing to do with XTCPDF.
In my real life applications it is for example BookingsController / bookings_controller.php or PropertiesController / properties_controller.php. If you follow one of the blog tutorials it could be PostsController / posts_controller.php.
No, why would it?
There is nothing in the controller which uses TCPDF or XTCPDF, it only gets the data you will use in the view from the Model, and selects the PDF layout.
We only load the TCPDF stuff when we need it, in the PDF view, thanks to App::import('Vendor','xtcpdf'); there.
Same answer as to your question 1. This really depends on your application. It has nothing to do with XTCPDF.
Again, if you follow a blog tutorial it could be "/app/views/posts"
Follow cakePHP conventions. You might have noticed that the view in cakePHP is having the name depending on the function in the controller which renders that view.
You could name it in the controller "function view()" and then use as view "view.ctp". In my tutorial I use "function viewPDF()" and consequently the view is "view_pdf.ctp". I would not use "view" here because that usually displays the record on screen (in your browser) and now we show a different view (of the same data), a view in PDF format.
Considering the answers above, do you really still need it?
If yes, and if you follow a tutorial published somewhere, point me to it, and I see if I can find the time to add it to that.
You're welcome :)
Comment
42 Re: basic questions
Comment
43 using a pdf as the background of the new pdf
Thanks!
Question
44 blank page problem
Do I actually have to set anything in the 'tcpdf_config.php'?
I red all the comments here, but nothing helped out. I don't find any older version of TCPDF, as you suggested in comment #17.
What can I do?
Comment
45 Call to undefined method XTCPDF::AddPath()
Call to undefined method XTCPDF::AddPath()
Comment
46 was all my fault
Comment
47 Happy to see that you got it working
I'm happy to see that you got it working.
In hindsight I think the older version of TCPDF versus new version issue was just a memory issue, see my comment 33 TCPDF 4.6.013 needs PHP set to more than 16 MB Some fonts covering a lot of the unicode chars got quite big, and the fonts used by the older versions have less unicode chars, thus they are smaller and need less memory when used.
Comment
48 Same ID
And this is used in the view like so: $tcpdf->Cell(50,5,$n, 0, 0);function card($id = null) {
$this->set('n', $this->Patient->field('name', $id));
$this->layout = 'pdf';
$this->render();
}
The links that point to this function are:
/cake/patients/card/1
/cake/patients/card/2
when follow either one of these link, I get the same ID 1, meaning when generating the pdf, it contains the ID 1 in both cases.
WHat could i be doing wrong ?
Comment
49 @noregret: id or name?
@noregret: I don't really know what you try to do, because you talk about the ID, but you read the field "name".
However I guess that you want this:
function card($id = null) {
// sanitize $id
$this->Patient->id = $id;
$this->set('n', $this->Patient->field('name'));
$this->layout = 'pdf';
$this->render();
}
And keep in mind that that should give you the name, not the ID.
Question
50 Blank Page
function view_pfd ($slug)
$id = $this->User->slugToId($slug);
$userData = $this->User->getTestInfo($id);
$this->set('user', $userData);
$this->layout = 'pdf';
$this->render();
But the pdf is empty. Where do i put the formatting for the view to be renderd in the pdf?
Thanks,
Dave
Comment
51 Re: Blank Page
View Template:
// Now you position and print your page content
// example:
$tcpdf->SetTextColor(0, 0, 0);
$tcpdf->SetFont($textfont,'B',20);
$tcpdf->Cell(0,14, "Hello World", 0,1,'L');
// ...
// etc.
// see the TCPDF examples
This you need to replace with whatever you want to have displayed. Because it is not an html page but a PDF page you use tcpdf to format and position, such as $tcpdf->Cell(...) in the example shown. See the tcpdf documentation for details.
Otherwise, to see if there are any errors causing what you see (or not see ;) ), temporarily set debug to 1. You can do that either globally or in your function viewPdf() with Configure::write('debug',1);
Comment
52 Thank you!
I'm running Cake on a server which has not configured PHP to run with the pdf library, so this has provided an excellent solution.
To the person above who was getting
I had this too, and then realised I had renamed the file xtcpdf.php to xtcpdf.php5 in an early attempt to get the server to run PHP5 instead of PHP4. It might be that something similar has happened to you - make sure you have a file called xtcpdf.php in app/vendors and that it contains the code in the article above.
Comment
53 One option for the blank page problem
Hi this was the solution for the blank page problem but it's better to change memory_limit inside a single php script because you have more control and you only use it on the place you need it.
So add the following code if you get a blank page when trying to create a pdf.
ini_set('memory_limit', '64M');Question
54 Passing view html to writeHTML
I just have a regular html table in my view and I'd like to just pass that html to the tcpdf class for output. Is this do-able?