Skip to main content
 首页 » 编程设计

python之将 SVG/PDF 转换为 EMF

2025年05月04日19luoye11

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

经过长时间的搜索,我似乎仍然无法找到使用 python 执行此操作的方法。希望任何人都有想法。

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

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

请您参考如下方法:

  • 对于仍然需要这个的人,我写了一个基本函数,可以让你从 matplotlib 中将文件保存为 emf,只要你有 inkscape。安装。

我知道运算符(operator)不想要 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')