Converting HTML to PDF with a JSON web service (Mojolicious + wkhtmltopdf)
I coded a simple JSON web service, which converts any HTML input to PDF (using the excellent wkthmltopdf software). You can supply HTML code or an URI where to get it.
Using the powerful Mojolicious web framework (Mojolicious::Lite is enough for this application, actually) framework it’s just roughly 100 lines of code for the whole thing:
Once you have this setup (via CGI, FastCGI, morbo, starman or whatever you like best), you just need to POST you data via JSON, and it could be something like:
and you get a JSON response such as this:
The PDF data is base64 encoded in order to be safely transferred without risking corruption because of character set encoding/decoding.
There are some configuration options (page size, …): take a look at the source code.
Not all wkhtmltopdf features are implemented, but it’s very easy to extend the software.
Authentication system is just an example, it should be way more robust.
Arguments should really be checked for safety, otherwise security issues could arise (well, provided the authentication system is broken before).
Error handling should be improved.
Why did I do this? Basically, I have some web apps hosted under a managed FreeBSD server, where compiling wkhtmltopdf does not work very well (and there are a lot of pre-requisites, anyway). This way I can “outsource” PDF generation easily.