The technology blog of Neil Thompson

I’m working on a side project at the moment that requires the conversion programatically of a page of html to something that can be consumed by an Amazon Kindle. I did a quick search to see if anything existed as a PHP class library that I could use and while there was they were either hugely bloated or too alpha for my needs.

I then stumbled upon Amazon’s command line tool KindleGen which allows conversion of HTML and ePub docs to the MOBI format that the Kindle requires. This is a multi-platform too and, crucially, a version for Linux is available.

Installation is a simple case of copying the single file to an appropriate place on your server, such as /usr/local/bin. Then create a new folder somewhere and make sure that the web process has write access to it. On Ubuntu this would be, for example, by :

sudo chown www-data:www-data /var/www/kindle

In my case I needed to convert some HTML to MOBI format and while experimenting found that it was very important to have well formed code, particularly with html and body tags. The other thing that you might like to consider is including a title tag as this is what is used as the name in the Kindle library and if this is omitted Amazon will use the name of the attached file instead.

To convert the file you simply need to pass to kindlegen the name of the html file and the output filename – note that you don’t need to give the path for the output file as it is created in the same place as the source. In PHP you can use “exec” to call a Linux command: