Last Updated: February 25, 2016
·
24.37K
· oncletom

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

8 Responses
Add your response

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

over 1 year ago ·

Could you suggest how can I get patched QT PDF library?

over 1 year ago ·
over 1 year ago ·

Does patched QT PDF exist for another platforms? Basically i need generate pdf with urls

for linux.

over 1 year ago ·

@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

over 1 year ago ·

I am getting segmentation fault on some sites. Do you know how to cure that?

over 1 year ago ·

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

over 1 year ago ·

Thanks man, you've saved my day.

over 1 year ago ·