Improve wkhtmltopdf Issues
On several of the projects that I maintain we have to create a PDF export of something (usually reports and invoices). I always find that the quickest, least painful way of doing this is to use wkhtmltopdf to convert an HTML page to a PDF. Until recently, it's been an abandoned project (I've been using 0.11 for years) and I'm happy to say that it's been updated to 0.12 recently! I also learned a couple new things.
Run the process through x11
I've run into a couple of problems with pages not rendering correctly and in order to fix them I had to run the process with an X11 server. I don't want a GUI running on my server so I run the process through xvfb.
First you need to install the executable:
## Unbuntu
sudo apt-get install xvfb
## RHEL
sudo yum install xorg-x11-server-Xvfb
And then the command line is a little more complicated:
xvfb-run --server-args="-screen 4, 1280x1024x24" wkhtmltopdf --use-xserver http://www.google.com/ output.pdf
Debug Javascript
If you're like me and have to run some JavaScript in order to generate graphs you can run into problems that are hard to troubleshoot because of the headless nature of wkhtmltopdf
. You can add the --debug-javascript
option and it will print any console
functions to stderr.
xvfb-run --server-args="-screen 4, 1280x1024x24" wkhtmltopdf --use-xserver --debug-javascript http://www.google.com/ output.pdf
Specify print media type
If you run wkhtmltopdf
normally it will create a PDF of the screen exactly as you see it. This is nice but you can also specify that wkhtmltopdf
set the media type to print (@media print
) so you can specify a different look for the PDF:
xvfb-run --server-args="-screen 4, 1280x1024x24" wkhtmltopdf --use-xserver --print-media-type http://www.google.com/ output.pdf
The other nice thing about this is that then if someone prints the page it will also have a nice layout.
Scott Keck-Warren
Scott is the Director of Technology at WeCare Connect where he strives to provide solutions for his customers needs. He's the father of two and can be found most weekends working on projects around the house with his loving partner.
Top Posts
- Working With Soft Deletes in Laravel (By Example)
- Fixing CMake was unable to find a build program corresponding to "Unix Makefiles"
- Upgrading to Laravel 8.x
- Get The Count of the Number of Users in an AD Group
- Multiple Vagrant VMs in One Vagrantfile
- Fixing the "this is larger than GitHub's recommended maximum file size of 50.00 MB" error
- Changing the Directory Vagrant Stores the VMs In
- Accepting Android SDK Licenses From The OSX Command Line
- Fixing the 'Target class [config] does not exist' Error
- Using Rectangle to Manage MacOS Windows