【问题标题】:Convert SVG/PDF to EMF将 SVG/PDF 转换为 EMF
【发布时间】:2016-05-23 21:28:33
【问题描述】:

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

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

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

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

【问题讨论】:

标签: python python-2.7 svg matplotlib


【解决方案1】:
  • 对于仍然需要此功能的任何人,我编写了一个基本函数,可以让您将文件保存为 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'
  • 知道了。它适用于figFolder = savePath + r"{}.{}"
  • -M 是做什么的?
  • 对于 Ubuntu,请尝试 stackoverflow.com/a/66450399/7842910
【解决方案2】:

我认为该功能很酷,但在我的情况下,inkscape 语法似乎不起作用。我在其他帖子中搜索并找到它:

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

因此,如果我在 subprocess 参数中将 -M 替换为 --export-filename,一切正常。

【讨论】:

  • 这(“--export-filename”)对我有用。知道为什么 emf 输出用黑色背景填充空圆圈吗?
  • 对不起,我对此一无所知。但在另一个问题上,我认为最好将 fig="fig" 指定为默认值,以便函数内部的“if loop”可以工作。这是为了避免每次应用函数时都指定“fig”参数。
猜你喜欢
  • 2013-06-29
  • 2011-05-06
  • 1970-01-01
  • 2014-11-26
  • 2016-01-20
  • 2015-10-04
  • 2017-03-17
  • 2020-12-14
相关资源
最近更新 更多