Export MailChimp Campaign as PDF
wkhtmltopdf
First, you have to use static build of wkhtmltopdf
because it contains a patched version of Qt. THIS is very important to benefit from real-world use case as clickable hyperlinks.
Mac users: the homebrew
package is not sufficient. Use the .dmg
file and then
sudo ln -s /Applications/wkhtmltopdf.app/Contents/MacOS/wkhtmltopdf /usr/bin/wkhtmltopdf
Basic command
So far so good, the command to convert a Webpage to PDF is simple
wkhtmltopdf http://eepurl.com/sjd5r ~/Desktop/dotjs-announce.pdf
One problem: we have useless stuff on board. No nice to distribute that.
Run Script
We have the ability to pass extra script to the remote URL before the rendering.
This is script you'll have to pass to the --run-script
argument as a string:
(function(document, undefined){
//Remove topbar and any stuff located in a .footer class (like MailChimp badge etc.)
Array.prototype.slice.call(document.querySelectorAll('#awesomewrap, [class*=footer]')).forEach(function(el){
el.parentNode.removeChild(el);
});
//Images wrapped in hyperlink are clickable at their full height
Array.prototype.slice.call(document.querySelectorAll('a img')).forEach(function(el){
el.parentNode.style.height = el.height || 'auto';
el.parentNode.style.display = 'inline-block';
});
//Removes the top border (used by #awesomewrap)
document.querySelector('html').style.border = 'none !important';
})(document);
The best way is to load the file from your build script, removing \n
chars and safely escape chars.
So the final stuff
wkhtmltopdf --run-script "`cat /path/to/above/script.js | tr '\n' ' '`" http://eepurl.com/sjd5r ~/Desktop/dotjs-announce.pdf
Enjoy
Written by Oncle Tom
Related protips
8 Responses
OSX Users should prefer the static build for production usage, to to VERY VERY large filesize PDF generation. Known bug: http://code.google.com/p/wkhtmltopdf/issues/detail?id=886
Could you suggest how can I get patched QT PDF library?
@pro100sanya yep sure, it's the Static build for OSX or example: https://code.google.com/p/wkhtmltopdf/downloads/detail?name=libwkhtmltox-OSX-0.10.0_rc2.tar.bz2&can=2&q= (avoid the DMG image).
Does patched QT PDF exist for another platforms? Basically i need generate pdf with urls
for linux.
@pro100sanya yup; I've updated to tip with this URL to link the latest static build for each platform: https://code.google.com/p/wkhtmltopdf/downloads/list?can=3&q=static
I am getting segmentation fault on some sites. Do you know how to cure that?
Nope; try without running any JS to see if it's the parsing/rendering; try another version of the software etc. Or look if there is any bug related to that on their bugtracker — https://code.google.com/p/wkhtmltopdf/issues/list?can=2&q=segmentation+fault
Thanks man, you've saved my day.