Archive for February, 2009

Creating PDF Documents in PHP Using Tcpdf

When developing websites, it is not going to be too long before you are required to generate a pdf for users to download. One usually searches for a suitable library for this and in php, there are a few options out there. My personal favourite, and one that is still receiving regular updates and improvements, is tcpdf.

There always seems to be a trade-off between flexibility and ease of use with these libraries and tcpdf seems to lean more towards the flexibility side of things. I prefer this, as there would be nothing worse that committing oneself to a particular library, only to find that it is not possible to generate a particulr report further down the track. On top of this, the library is available in PHP4 and PHP5 versions and is open source, should one need to tweak it any way.

Installation is pretty straight forward for and there are suitable instructions telling you how. In my case, however, I am using the CodeIgniter framework and needed to take some additional steps in order to use it. If anyone else is also using CodeIgniter, here is how I do it:

  1. Unpack the tcpdf installation package into your  system/plugins folder. This will give you a tcpdf directory in the plugins directory.
  2. Create a tcpdf_pi.php file inside the plugins directory. Place the following code in it:
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
require_once('tcpdf/config/lang/eng.php');
require_once('tcpdf/tcpdf.php');
 
// Extend the TCPDF class to create custom Header and Footer
class OnemoretakePDF extends TCPDF {
}
 
function tcpdf(){
    return new OnemoretakePDF (PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true);
}
 
?>

Here, we basically instantiate tcpdf and pass in a few of the default values. You may be wondering why I have extended the TCPDF class and have not just instantiated it directly. Well, I shall come to that later.

To use this in CodeIgniter, you load the plugin and then create an instance of  it as follows:

1
2
$this->load->plugin( 'tcpdf' );
$pdf = tcpdf();

The next step really, is to visit the documentation for tcpdf. It is not the easiest to follow set of documentation there is, as it has been generated directly from the code, although there are several examples that you can pull apart to learn more. The premise here is to create a new pdf page and plot what you want on that page. This can be done directly with commands like Text() and Line() which use coordinates directly or you can also use Cell() and MultiCell() which allow you to draw using a cell system like a table and utilise borders and alignment appropriately. For those who just cannot get their heads around plotting on a page, there are commands to plot HTML, although support for styles is limited, so don’t expect to recreate a fancy webpage layout by throwing the html at it. I found that with a little bit of lateral thinking, most jobs can be done without the HTML methods anyhow.

What took me a little time to get used to, is that the coordinate system is not in pixels but by default, in millimetres. This actually makes a lot of sense, as we are creating for print here, not screen. This makes it very awkward if you are working off a design done in photoshop or similar and want to get the dimensions just right. However, a trick I soon learned was to print that image directly to a pdf and then you can use the measurement tools in your pdf reader (Foxit reader has such a tool) to measure the correct distance in millimetres.

The API for tcpdf is extensive and with it, one can achieve most tasks. One thing to note, however is that to create a standard header and footer for your document, you need to override the default header and footer methods in the main tcpdf class. This is why, in the code above, I extended the tcpdf class. It will give us the opportunity to override these methods as follows:

1
2
3
4
5
6
7
8
9
10
11
class OnemoretakePDF extends TCPDF {
    //Page header
    public function Header() {
        //header plotting code here
    }
 
    // Page footer
    public function Footer() {
      //footer plotting code here
    }
}

My biggest gripe about this library is that the documentation does not give enough detail. Coupled with that, the forum is a SourceForge forum, which frankly I find very difficult to find anything in. It would be great if there was a way to get more detail, perhaps a wiki would benefit the project a great deal – I am sure there is a lot of detailed knowledge out there about the ins and outs of the library, its just that there is no way to tap into it.

You can’t complain too much however, this project provides a very powerful pdf creation library. I have had experience with Microsoft.Net libraries of a similar nature and you can end up paying quite a lot for them. Not to mention they tend be way more restricted as to what is possible.

The Technical Debt

I have spent the last few days at work doing some intense refactoring of a seemingly complex jQuery plug-in. I managed to cut it down by 140 lines and speed it up immensely. Whilst it would have saved time if I had written the plug-in myself in the first place, I cannot be expected to do everything and nobody else at work would improve their jQuery and javascript writing skills if I did so. I therefore label my time spent as paying of some of the technical debt that we create, in the process of releasing the software as quickly as we can. If you have not come across this metaphor before, here it is:

It really nails the reason that as developers, we try to refactor regularly. Unfortunately refactoring is not something that people outside of the development community tend to understand and it is considered a waste of time all too often. I think use of this metaphor may just help those people understand.

Sorting Elements with jQuery

Whilst refactoring a jQuery plugin today, I came across a method that placed a list item into an unordered list at a specific point, so that all the items remained in alphabetic order. This long method seemed completely convoluted and slow to me and I decided that there must be an easier way to keep the list in alphabetical order.

There are existing plugins for sorting elements but I never like to just pile on the 3rd party plugins as that means more javascript files to include in a page. Besides, I was sure it should not be difficult.

It soon occured to me that jQuery has the built-in ability to return the elements as an array, using the .get() method and from there, it was not too long before I had my streamlined code to sort the list element alphabetically:

var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

I utilise the javascript array.sort method to sort the elements in the array and then using the jQuery append() method,  reorder them in the actual list element.

Easier Cross Browser Testing

Every web developer will spend a sufficient chunk of their time testing and fixing webpages so that they work across as many browsers as possible. We all groan at the mention of IE6, which is here to stay for a little while yet, even with the various efforts to change that.

I like to keep my computer as lean and mean as possible and installing all the browsers frustrates me. On top of that, one must keep an additional installation of XP as a virtual machine, just to test IE6. Don’t get me wrong, I cheered at the day that IE Tester was released but unfortunately progress on that project is slow and bugs are large, so the virtual machine tends to win.

Today all that changed for me. I came across Xenocode, who are in the virtualization space. Instead of creating entire virtual machines, OS and all, Xenocode software allows you to create a virtual environment for a single piece of software. This means that everything that is required to run that piece of software is all neatly wrapped up in a bite-sized executable. So what does this mean? All the major browsers as single executables. Awesome.

Just click on the browser you want, download the executable and run it. No more installing or virtual machines to clog up your machine.

Is Atlas So New?

Slipping musically into my twitter stream earlier this morning came an excited remark by John Resig. He seemed all hyped about the new Atlas product from 280 North that they announced at Future of Web Apps, Miami.

Given John’s reputation in web development, I immediately followed the link and watched the introductory video on the site, expecting to be amazed. It looked all very pretty and the creation of an rss reader with just a few clicks of the mouse gave suitable wow-factor to the demonstration.

However, I could not help thinking that I had seen this idea somewhere before. I use it at work every day – Microsoft Visual Studio. The same concepts are there for web development – a drag-and-drop interface, with built-in controls that are supposed to take most of the grunt work away from you.

At first look, this idea is great – creating fully-fledged application in no time at all. However, in my experience with Visual Studio, this ends up being more of a hindrance than a help. I avoid the drag-drop functionality of VS like the plague, not because I am a glutton for punishment but because of the intrinsic limitation it places on you and because most of the time the same functionality can (and should) be achieved in a faster, more flexible and more maintainable way. The biggest gripe I have with web development in VS is the constant struggle to make it produce tidy html that is standards compliant.

Atlas might not be like that at all. I have only seen the video. However, I don’t think it is revolutionary as the buzz today would lead us into thinking and it may not be all that people hope it is. It could endup just being a Visual Studio type development environment based in a browser.