I have a project where I need to create a PDF from a web page dynamically created on the back-end. Normally I use TCPDF, but I was having some issues in the way the PDF was looking being created from the HTML.
So, after some searching, I came across wkhtmltopdf. It is described as a “Simple shell utility to convert html to pdf using the webkit rendering engine, and qt.” Looked promising. I went ahead and installed the last production version, which was wkhtmltopdf-0.9.9-static-i386.tar.bz2, but this had some functionality a few tutorials mentioned. So I grabbed the most featured version wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2 and installed on my CentOS 6.4 (Final) server:
# wget http://wkhtmltopdf.googlecode.com/files/wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2 # tar xvjf wkhtmltopdf-0.11.0_rc1-static-i386.tar.bz2 # mv wkhtmltopdf-i386 /usr/bin/wkhtmltopdf # which wkhtmltopdf /usr/bin/wkhtmltopdf
From there, I could run the following command and get a decent PDF with bookmarks, based on the H1 – H3 tags I had in the HTML:
wkhtmltopdf -q --margin-bottom 5 --margin-top 5 --margin-left 3 --margin-right 3 --disable-smart-shrinking /tmp/test.html /tmp/test.pdf
This produced the PDF with the desired results, except for 1 issue: the images (all PNG’s) looked distorted. After searching, I found this thread explaining to use larger images and resize it in the HTML. As a developer, that was a “no no” for me, but tried it.
In the HTML I wanted the images to be displayed at 16 pixels high by 16 pixels wide. So, instead of using images sized at 16×16, I grabbed the original images that were 128×128 and 256×256, respectively. I use those in the <img /> tag, and set the height and width to 16. The resulting PDF looked awesome!
So, if you are trying to use wkhtmltopdf to save an HTML file with images and they look stretched or choppy, try this. It may help you out!