让cairosvg在windows中工作

时间:2017-09-17 15:18:14

标签: python gtk cairo pycairo

尝试使此代码正常工作:

import cairosvg
import os

path = "D:/PyProjects/Bla/Temp"
os.chdir(path)

cairosvg.svg2pdf(url='Pic.svg', write_to='image.pdf')

但是会遇到与此post类似的错误:

Traceback (most recent call last):
  File "D:/work/lean_python/pdf/other.py", line 2, in <module>
    import cairosvg
  File "D:\env_python352\lib\site-packages\cairosvg\__init__.py", line 29, in <module>
    from . import surface
  File "D:\env_python352\lib\site-packages\cairosvg\surface.py", line 24, in <module>
    import cairocffi as cairo
  File "D:\env_python352\lib\site-packages\cairocffi\__init__.py", line 46, in <module>
    cairo = dlopen(ffi, 'cairo', 'cairo-2')
  File "D:\env_python352\lib\site-packages\cairocffi\__init__.py", line 43, in dlopen
    raise OSError("dlopen() failed to load a library: %s" % ' / '.join(names))
OSError: dlopen() failed to load a library: cairo / cairo-2

帖子提到:

CairoSVG (the python library and bindings) needs Cairo (The C library, part of GTK+) to run. It appears you don't have it an it's headers installed on your system.

所以我按照步骤1 - 5描述了here。我现在有cairo头文件:

C:\msys64\mingw64\include\cairo

我还安装了另一个来源推荐的pycairo:

pip install pycairo-1.15.2-cp36-cp36m-win_amd64.whl

我仍然遇到上述错误。有什么想法吗?

3 个答案:

答案 0 :(得分:2)

以下变通办法适用于我:

  • 安装cairosvg(python -m pip install cairosvg
  • 在脚本中运行import cairosvg
  • 如果有效,您已设置好。否则(OSError: no library called "cairo" was found):
  • 获取libcairo-2.dll的副本
  • 假设路径为C:\path\cairo\dlls\libcairo-2.dll
  • 在脚本中添加到顶部(在导入cairosvg之前)

import os os.environ['path'] += r';C:\path\cairo\dlls'

  • import cairosvg现在应该可以成功工作了。

(假设您正在运行64位版本的Python,否则请使用win32_headless.msi

答案 1 :(得分:1)

我只是没有让cairosvg工作。我找到了一种使用svglib包将svg转换为png的替代方法。

from svglib.svglib import svg2rlg
from reportlab.graphics import renderPDF, renderPM
import os

path = "D:/Bla/Temp"
os.chdir(path)

drawing = svg2rlg("Pic.svg")
renderPM.drawToFile(drawing, "Pic.png")

答案 2 :(得分:1)

请使用libcairo-2.dll检查ctypes.util的路径。
就我而言,它是旧软件的目录,名为Graphviz

python
>>> import ctypes.util
>>> path = ctypes.util.find_library('libcairo-2')
>>> print(path)
C:\Program Files (x86)\Graphviz 2.28\bin\libcairo-2.dll

卸载Graphviz后。

python
>>> import ctypes.util
>>> path = ctypes.util.find_library('libcairo-2')
>>> print(path)
C:\msys64\mingw64\bin\libcairo-2.dll