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 http://google.com 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:

server:
    install: '1'
    packages:
        - 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:

https://github.com/mikehaertl/phpwkhtmltopdf

From within your PHP, you can say:

        use mikehaert\wkhtmlto\Pdf;

        $pdf = new Pdf(array('tmpDir' => '/optional/tmp/folder/here'));
        $pdf->addPage('http://google.com');

        // 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

XVFB=/usr/bin/Xvfb
XVFBARGS=":0 -screen 0 1024x768x24 -ac +extension GLX +render -noreset"
PIDFILE=/var/run/xvfb.pid
case "$1" in
  start)
    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 "."
    ;;
  stop)
    echo -n "Stopping virtual X frame buffer: Xvfb"
    start-stop-daemon --chuid www-data --stop --quiet --pidfile $PIDFILE
    echo "."
    ;;
  restart)
    $0 stop
    $0 start
    ;;
  *)
        echo "Usage: /etc/init.d/xvfb {start|stop|restart}"
        exit 1
esac

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!

Advertisements