将 SVG/PDF 转换为 EMF

Jus*_*tMe 6 python svg matplotlib python-2.7

我正在寻找一种将 matplotlib 图保存为 EMF 文件的方法。Matplotlib 允许我保存为 PDF 或 SVG 矢量文件,但不能保存为 EMF。

经过长时间的搜索,我似乎仍然找不到用 python 来做到这一点的方法。希望有人有想法。

我的解决方法是使用子进程调用inkscape,但这远非理想,因为我想避免使用外部程序。

我正在使用 wx 后端运行 python 2.7.5 和 matplotlib 1.3.0。

小智 7

  • 对于仍然需要此功能的任何人,我编写了一个基本函数,只要您安装了inkscape,就可以让您将文件保存为来自 matplotlib 的 emf 。

我知道 op 不想要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))
Run Code Online (Sandbox Code Playgroud)

#示例用法

import numpy as np
tt = np.linspace(0, 2*3.14159)
plt.plot(tt, np.sin(tt))
exportEmf(r"C:\Users\userName", 'FileName')
Run Code Online (Sandbox Code Playgroud)