将SVG/PDF转换为EMF

9
我正在寻找一种将matplotlib图形保存为EMF文件的方法。Matplotlib允许我将其保存为PDF或SVG矢量文件,但无法保存为EMF。
在长时间搜索后,我仍然找不到用Python实现此功能的方法。希望有人能给我一个建议。
我的解决方法是使用子进程调用inkscape,但这远非理想,因为我想避免使用外部程序。
我正在运行Python 2.7.5和使用wx后端的matplotlib 1.3.0。

看起来 EMF 支持在 matplotlib v1.3 中被移除了。 - tmdavison
我在考虑使用pyEMF和一个svg解析器来编写一个小型库,将svg转换为emf格式 - 有人能够给出更好的建议并制止我吗? - Shmack
2个回答

10
  • 如果仍需要此功能,我编写了一个基本函数,可以让您从matplotlib将文件保存为emf格式,只要您安装了inkscape

我知道原帖作者不想使用inkscape,但是后来看到这篇文章的人只是想让它正常工作。

import matplotlib.pyplot as plt
import subprocess
import os
inkscapePath = r"path\to\inkscape.exe"
savePath= r"path\to\images\folder"

def exportEmf(savePath, plotName, fig=None, keepSVG=False):
    """Save a figure as an emf file

    Parameters
    ----------
    savePath : str, the path to the directory you want the image saved in
    plotName : str, the name of the image 
    fig : matplotlib figure, (optional, default uses gca)
    keepSVG : bool, whether to keep the interim svg file
    """

    figFolder = savePath + r"\{}.{}"
    svgFile = figFolder.format(plotName,"svg")
    emfFile = figFolder.format(plotName,"emf")
    if fig:
        use=fig
    else:
        use=plt
    use.savefig(svgFile)
    subprocess.run([inkscapePath, svgFile, '-M', emfFile])
 
    if not keepSVG:
        os.system('del "{}"'.format(svgFile))

#示例用法
import numpy as np
tt = np.linspace(0, 2*3.14159)
plt.plot(tt, np.sin(tt))
exportEmf(r"C:\Users\userName", 'FileName')

我遇到了一个“PermissionError: [Errno 13] Permission denied: '\filename.svg'”的错误。 - Stücke
明白了。它可以与 figFolder = savePath + r"{}.{}" 一起使用。 - Stücke
1
-M 是什么作用? - Stücke
对于Ubuntu,请尝试访问https://dev59.com/Fa_la4cB1Zd3GeqPwKid#66450399。 - Sam Macharia
我在让这个解决方案正常运行上遇到了很多麻烦。我不得不修改脚本,将subprocess.run这一行替换为proc = subprocess.Popen([inkscapePath, svgFile, '--export-type=emf'], stdout=subprocess.PIPE, stderr=subprocess.STDOUT)并且加入print(proc.communicate()[0])。除了成功导出emf格式外,这些代码还会将错误信息输出到命令行中,以便进行故障排除。 - nrp1000

3

我认为这个函数很酷,但Inkscape语法在我的情况下似乎不起作用。我在其他帖子中搜索并找到了以下内容:

inkscape filename.svg --export-filename filename.emf 

所以,如果我在子进程参数中将-M替换为--export-filename ,一切都能正常工作。


这个("--export-filename")对我有用。你知道为什么EMF输出会用黑色背景填充空心圆吗? - banbar
抱歉,我对此一无所知。但是在另一个问题上,我认为最好将fig="fig"指定为默认值,这样函数内部的“if循环”可以正常工作。这是为了避免每次应用函数时都要指定“fig”参数。 - Chenyao

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接