HTML to PDF using wkhtmltopdf

Converting web pages to PDF? Sick of various libs and their various quirks and complexity? Wkhtmltopdf is a linux program that can reliably generate pdfs from html content. It’s as easy as running:

wkhtmltopdf google.pdf

from the command line. However, we want it in our web site! First off though, you’ll need it installed. If you are using puPHPet and vagrant, add the following in your config.yaml under server: packages:

    install: '1'
        - wkhtmltopdf

Then run vagrant provision. Standard linux servers will install by using yum or apt-get:

sudo apt-get install wkhtmltopdf

You can get the PHP wrapper class here:

From within your PHP, you can say:

        use mikehaert\wkhtmlto\Pdf;

        $pdf = new Pdf(array('tmpDir' => '/optional/tmp/folder/here'));

        // Save the PDF
        // $pdf->saveAs('/tmp/new.pdf');

        // ... or send to client for inline display
        if (!$pdf->send()) {echo $pdf->getError();}
        // ... or send to client as file download
        // $pdf->send('test.pdf');

You may get an error saying it cannot connect to the X server. If you get this, you probably don’t have X installed! I didn’t, it’s a web server, not a desktop machine!

In the event that you have no X server, go into the Command.php class, you will see the following option:

     * @var bool whether to enable the built in Xvfb support (uses xvfb-run)
    public $enableXvfb = false;

Change this to true, and try again. This time it should work!

If it still doesn’t, then possibly you also need to install xvfb, again with apt-get or yum, then add a startup script for it. I didn’t have to do any of this, but for those of you who may need to, complete the following steps:

sudo nano /etc/init.d/xvfb

XVFBARGS=":0 -screen 0 1024x768x24 -ac +extension GLX +render -noreset"
case "$1" in
    echo -n "Starting virtual X frame buffer: Xvfb"
    start-stop-daemon --chuid www-data --start --quiet --pidfile $PIDFILE --make-pidfile --background --exec $XVFB -- $XVFBARGS
    echo "."
    echo -n "Stopping virtual X frame buffer: Xvfb"
    start-stop-daemon --chuid www-data --stop --quiet --pidfile $PIDFILE
    echo "."
    $0 stop
    $0 start
        echo "Usage: /etc/init.d/xvfb {start|stop|restart}"
        exit 1

exit 0

Enable the init script:

update-rc.d xvfb defaults 10

Start it up:

/etc/init.d/xvfb start

Check its running:

ps auxU www-data | grep [X]vfb

Now try reloading your page, and with a bit of luck you should see a PDF version of the google home page! Play around with it and have fun!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s