Python – Install WeasyPrint on a linux (Webfaction) server
WeasyPrint is a great python library to generate PDFs from HTML. It beats hands down xhtml2pdf, by interpreting CSS and HTML the right way.
However, it has a lot of dependencies and it just can’t fit in a simple python virtual environment. It took me a whole day to install on Webfaction, so I think it would be helpful to show how to do it properly.
These steps has been tested on a Webfaction CentOS 6 server (python2.7), and they should be the same for others Linux systems. If your system is not exactly the same, you might have to install other dependencies manually. Linux From Scratch is your helpful friend in this kind of situation.
Log to ssh, and let the magic begin.
Dependencies
WeasyPrint relies on the following dependencies:
- Pango >= 1.29.3 (with introspection)
- pycairo
- GdkPixbuf >= 2.25 (with introspection, required for images other than PNG)
- PyGObject 3.x
Of course, these dependencies have their own dependencies. It becomes really hard to install all of them by hand, so I made a small shell script to do it automatically. It will install all of them in your home directory (with --prefix=$HOME
).
1 | $ curl -fsSkL https://raw.github.com/gist/3438324/weasyprint_webfaction.sh | sh |
Then, add the following lines to your ~/.bashrc
:
1 2 | export LD_LIBRARY_PATH=$HOME/lib export PYTHONPATH="$HOME/lib/python2.7/site-packages/:$PYTHONPATH" |
And source it:
1 | $ source ~/.bashrc |
Virtual environment
As we will install global python libraries, we need a virtual environment that is aware of system packages. If you didn’t create one yet:
1 2 | $ cd /path/to/project $ virtualenv --system-site-packages ./venv |
If your virtual env is already created:
1 2 | $ cd /path/to/project $ mv ./venv/lib/python2.7/no-global-site-packages.txt ./venv/lib/python2.7/_no-global-site-packages.txt |
WeasyPrint
Here we are. Install WeasyPrint using the following lines:
1 2 | $ source ./venv/bin/activate $ pip install weasyprint |
Finally, test it:
1 | $ weasyprint http://weasyprint.org ./weasyprint-website.pdf |
If there is an import error, please check that you correctly sourced your ~/.bashrc
.
Thanks to Ilias Romanos from the Webfaction Q/A forum for the pyCairo part ! Don’t hesitate to improve the install script on github:gist.