TCPDF php package for pdf writing

I recently had opportunity to implement the TCPDF package for a midsized project. This article attempts to document my experiences with the API, its strengths, weaknesses, and ease of use.

The package is quite simple to implement at a high level, and following the included examples I was able to create a writer for my project in a matter of days. I appreciated the flexibility of being able to use HTML for layout. Also appreciated was the ability to override the TCPDF class to create custom headers and footers. I utilized this to place a reference to the company logo in the website’s image directory rather than in the tcpdf package’s image directory. I also was able to create a more detailed header layout than the default using this method. Once the pdf document is constructed, TCPDF provides some helpful output options including posting the document directly to the browser. This is a nice option because it allows previewing in an iframe, and doesn’t take up space on the server.

Initially I constructed a string containing inline style and the data in one large HTML table, and wrote the pdf document using one writeHTML call. An example of this follows:

$style="<style type=\"text/css\">\n";
$style=" table {\n";
$style=" color:red;";
$style=" }\n";
$style=" td {\n";
$style=" border:none;";
$style=" }\n";
$table=" <tr>\n";
$table=" <td>example</td>\n";
$table=" </tr>\n";
$tcpdfObj=new TCPDF('L','pt',true,'letter',false);
$tcpdfObj->SetHeaderData("logo.png", 100, 'pdf title', 'header text');

This first implementation worked for a small test database, but failed when I tested it for larger ones producing out of memory errors. Raising php’s mem_limit didn’t solve the problem. I was able to work around this by dividing the writeHTML call into several smaller calls each with a copy of the inline style and a HTML table containing several rows of the original HTML table, but this added to the running time. writeHTML seemed to work with about 2500 cells at a time. Having overcome the memory limitation, I found that running time for large datasets was unnacceptable. It was in the range of 10 minutes or more for a 50000 cell document. Fortunately tcpdf has faster Cell, and MultiCell functions, however when using them layout becomes much more restrictive. Using these faster calls reduced the running time by 50%, but this was still too slow for my project.

To summarize, the tcpdf package works, offers some flexibility of layout and output, is quickly implemented, but doesn’t scale well.