Python: OSError: cannot load library libcairo.so.2

I just had the same issue ("OSError: cannot load library libcairo.so.2: error 0x7e"), and this is how I solved the problem on Windows (Windows 7 x64, Python 3.4.2 x86 (MSC v.1600 32 bit)):

  • downloaded an all-in-one bundle of the GTK+ stack including 3rd-party dependencies (which contains libcairo-2.dll and other Cairo-related libraries)
  • extracted this archive to a path which does NOT contain spaces (e.g. C:\Programs\gtk+)
  • added the extracted directory's bin subdirectory (which contains the mentioned libcairo-2.dll and other necessary files) to the PATH
    • Win+R, SystemPropertiesAdvanced
    • Environment Variables...
    • added this directory to the Path variable (either to the user variables or system variables, after a semicolon) (e.g. ...;C:\foo;C:\Programs\gtk+)
    • OK
  • pip install cairosvg
  • tested it with a very simple code, which already had worked:
import cairosvg
testsvg = '<svg height="30" width="30">\
    <text y="10">123</text>\
    </svg>'
svgConvertedToPng = cairosvg.svg2png(bytestring=testsvg)
print(svgConvertedToPng)

On Mac OS X using homebrew:

brew install cairo
brew install pango

It seems cairo depends a shared library which is not in standard search library, however, the python is calling dlopen to dynamic load the library, so you could try to put the libcairo.so.2(if it's a link, then make sure the reference locates at the same folder) in the working directory. You can also try pkg-config to set the environment. see here http://people.freedesktop.org/~dbn/pkg-config-guide.html