1. Install wkhtmltopdf
Find the download URL for the latest binary from the official Downloads page.
At the time of writing, this is v0.12.6, which was released on June 11, 2020.
Download the binary, and then install the package and its dependencies. For example:
wget https://github.com/wkhtmltopdf/packaging/releases/download/0.12.6.1-2/wkhtmltox_0.12.6.1-2.jammy_amd64.deb
sudo dpkg -i wkhtmltox_0.12.6.1-2.jammy_amd64.deb
This will give you an installation error - that's expected. To complete the install, run:
sudo apt install -f
2. Install xvfb package:
sudo apt-get install xvfb
3. Set up xvfb as service:
(Source: https://gist.github.com/nkm/91006178753df6f503c1)
Create file /etc/systemd/system/xvfb.service
and add the contents:
[Unit]
Description=Virtual Frame Buffer X Server
After=network.target
[Service]
ExecStart=/usr/bin/Xvfb :42 -screen 0 1x1x24 -ac +extension GLX +render -noreset
[Install]
WantedBy=multi-user.target
Activate the service and start it:
sudo systemctl enable xvfb.service
sudo systemctl start xvfb.service
sudo systemctl status xvfb.service
4. Test if it works at all
Try to do a test run, and fix any errors you have on the command line before trying to get things to work in PHP:
wkhtmltopdf https://google.com test.pdf
Expected output looks like this:
Loading pages (1/6)
Counting pages (2/6)
Resolving links (4/6)
Loading headers and footers (5/6)
Printing pages (6/6)
Done
5. PHP integration
Our library of choice for this is https://github.com/mikehaertl/phpwkhtmltopdf.
Typically integration is really simple once wkhtmltopdf is up and running:
$pdf = new Pdf(/** your html or url goes here **/);
$pdf->send('myfile.pdf');
If you're having trouble, you can try setting xserver options manually:
$pdf = new Pdf([
'use-xserver',
'commandOptions' => array(
'procEnv' => array( 'DISPLAY' => ':0' ),
),
]);
This still works on Ubuntu 17.10. There's a wkhtmltopdf package in the official repositories too, but I haven't had any luck getting that to work.