如何将 tikzpictures 导出为 png(使用 GraphicsMagick?)

如何将 tikzpictures 导出为 png(使用 GraphicsMagick?)

我想将我的一些 LaTeX 图形导出为具有清晰背景的 .png,以便可以在 PowerPoint 演示文稿中使用它们。我在 Windows 10 上使用 TexStudio 和 MikTex。@Harald Hanche-Olsen 向我推荐了 GraphicsMagick,但我们都不知道它在 Windows 中是如何工作的。

如何将我的 LaTeX 图形(以 PDF 输出)转换为具有清晰背景的 .png?

例图:

\PassOptionsToPackage{table,dvipsnames,svgnames}{xcolor}
\documentclass[11pt, twoside, a4paper]{report}
\usepackage[inner = 30mm, outer = 20mm,  top = 30mm, bottom = 20mm, headheight = 13.6pt]{geometry}
\usepackage{tikz}
\usepackage[pdfpagelayout=TwoPageRight]{hyperref}
\usepackage[export]{adjustbox}
%\usepackage{showframe}
\hypersetup{colorlinks=true, linktoc=all, allcolors=green!30!black,}

\usepackage{pgfplots}
\pgfplotsset{
    compat=1.16,
    %made the beginnings of a second axis style, because I figured it needs to be different for grouped
    my second axis style/.style={
    width=\linewidth,
    height=0.35\linewidth,
    bar width=0.2, %<- changed
    enlarge x limits={abs=0.45},    % <-- changed to absolute coordinates
    ymin=0,
    legend style={
        at={(0.5,1.15)},    % <-- adapted
        anchor=north,       % <-- changed from `north'
        legend columns=3,
    },
    ylabel={PR\textsubscript{A}},
    xtick=data,
    axis lines*=left,
    ymajorgrids,
    %
    table/x=x,
    },
    % created a style for the common `ybar' options
    my second ybar style/.style={
        ybar,
        my ybar legend,            % <-- change legend image accordingly
        #1!50!black,
        fill=white!70!black,, %<- changed back
        nodes near coords,      % <-- moved from `axis' options here
        % state absolute positions for the `nodes near coords'
        scatter/position=absolute,
        node near coords style={
            % state where the nodes should appear
            at={(\pgfkeysvalueof{/data point/x},0.5*\pgfkeysvalueof{/data point/y})},
            anchor=center,rotate=90, %<-added
            % make the font a bit smaller
            font=\footnotesize,
            /pgf/number format/.cd,
            fixed,
            precision=2,
            zerofill,
        },
    },
    my ybar legend/.style={
        /pgfplots/legend image code/.code={
            \draw [
            ##1,
            /tikz/.cd,
            yshift=-0.25em,
            ] (0cm,0cm) rectangle (3pt,0.8em);
        },
    },
}



%data for the grouped bar chart
\pgfplotstableread{
    x          SP_cSi_2_3   SP_cSi_2_4  Reference
    1   0.500   0.627   0.868
    2   0.781   0.778   0.859
    3   0.819   0.868   0.871
    4   0.732   0.824   0.876
    5   0.853   0.873   0.954
    6    0.813   0.838   0.940
    7    0.712   0.759   0.876
    8    0.864   0.894   0.887
    9    0.465   0.614   0.891
}{\loadedtablesppr}


\begin{document}

    \begin{figure}
        \begin{tikzpicture}
        \begin{axis}[my second axis style,
        ybar,
        ylabel={PR\textsubscript{A}},
        xtick= data,
        ]
        \addplot [my second ybar style=blue!50!black,] table [y=SP_cSi_2_3] {\loadedtablesppr};
        \addplot [my second ybar style=orange!50!black,] table [y=SP_cSi_2_4] {\loadedtablesppr};
        \addplot [my second ybar style=red!50!black,] table [y=Reference] {\loadedtablesppr};
        \legend{Floating 2.3~~ , Floating 2.4~~ , Reference}
        \end{axis}
        \end{tikzpicture}
    \end{figure}

\end{document}

是否有类似的命令 \savefig{'my_export_image.png', clear = True}

答案1

如果您有大量图,那么为所有图制作独立文件可能会很麻烦。另一种方法是使用externalTikz 或pgfplots(根据文档,后者通常更为最新)中的库。

\usepgfplotslibrary{external}

下面将打开外部化,tikz_external/在当前目录中为所有生成的图形加上前缀,并且仅外部化tikzpicture已用 命名的图形\tikzsetnextfilename{<name>}

\tikzexternalize[
    prefix={tikz_external/},
    only named,
]

请注意,如果当前目录中不存在子文件夹tikz_external,则可能需要手动创建。我不需要这样做(在 Windows 上也是如此),但正如 @knut 在评论中所述,这显然不是标准的 Windows 行为。

或者,您可以将以下行添加到序言中,如果目录不存在则创建该目录。

\immediate\write18{if not exist tikz_external mkdir tikz_external}

然后我们定义一个新样式,在 Tikz 用于编译外部图形的命令中添加一行。如果您使用的是 Ubuntu 或它的一个同类系统,您可能希望将 替换&&;

% Make the 'export as png' a seperate style, with default density 200
\tikzset{
    export as png/.style={
        external/system call/.add={}{
            && convert -density #1 -transparent white "\image.pdf" "\image.png"
        },
    },
    export as png/.default={200},
}

然后通过在内部调用以下命令figure,下一个tikzpicture将被外部化,并且在当前范围内,每个外部化的图形也将转换为文件.png

\tikzset{export as png=<optional density>}
\tikzsetnextfilename{my_externalized_plot}

然后,您可以使用启用的选项来编译整个文档--shell-escape,瞧,您的文件就可以作为.pngs 使用。

完成 MWE:

\PassOptionsToPackage{table,dvipsnames,svgnames}{xcolor}
\documentclass[11pt, twoside, a4paper]{report}
\usepackage[inner = 30mm, outer = 20mm,  top = 30mm, bottom = 20mm, headheight = 13.6pt]{geometry}
\usepackage{tikz}
\usepackage[pdfpagelayout=TwoPageRight]{hyperref}
\usepackage[export]{adjustbox}
%\usepackage{showframe}
\hypersetup{colorlinks=true, linktoc=all, allcolors=green!30!black,}

\usepackage{pgfplots}
\pgfplotsset{
    compat=1.16,
    %made the beginnings of a second axis style, because I figured it needs to be different for grouped
    my second axis style/.style={
    width=\linewidth,
    height=0.35\linewidth,
    bar width=0.2, %<- changed
    enlarge x limits={abs=0.45},    % <-- changed to absolute coordinates
    ymin=0,
    legend style={
        at={(0.5,1.15)},    % <-- adapted
        anchor=north,       % <-- changed from `north'
        legend columns=3,
    },
    ylabel={PR\textsubscript{A}},
    xtick=data,
    axis lines*=left,
    ymajorgrids,
    %
    table/x=x,
    },
    % created a style for the common `ybar' options
    my second ybar style/.style={
        ybar,
        my ybar legend,            % <-- change legend image accordingly
        #1!50!black,
        fill=white!70!black,, %<- changed back
        nodes near coords,      % <-- moved from `axis' options here
        % state absolute positions for the `nodes near coords'
        scatter/position=absolute,
        node near coords style={
            % state where the nodes should appear
            at={(\pgfkeysvalueof{/data point/x},0.5*\pgfkeysvalueof{/data point/y})},
            anchor=center,rotate=90, %<-added
            % make the font a bit smaller
            font=\footnotesize,
            /pgf/number format/.cd,
            fixed,
            precision=2,
            zerofill,
        },
    },
    my ybar legend/.style={
        /pgfplots/legend image code/.code={
            \draw [
            ##1,
            /tikz/.cd,
            yshift=-0.25em,
            ] (0cm,0cm) rectangle (3pt,0.8em);
        },
    },
}

\immediate\write18{if not exist tikz_external mkdir tikz_external} % Only tested on Windows

\usepgfplotslibrary{external}
\tikzexternalize[
    prefix={tikz_external/},
    only named,
]

%\pgfkeys{/pgf/images/include external/.code=\includegraphics{#1}}

% Make the 'export as png' a seperate style, with default density 200
\tikzset{
    export as png/.style={
        external/system call/.add={}{
            && convert -density #1 -transparent white "\image.pdf" "\image.png"
        },
    },
    export as png/.default={200},
}

%data for the grouped bar chart
\pgfplotstableread{
    x          SP_cSi_2_3   SP_cSi_2_4  Reference
    1   0.500   0.627   0.868
    2   0.781   0.778   0.859
    3   0.819   0.868   0.871
    4   0.732   0.824   0.876
    5   0.853   0.873   0.954
    6    0.813   0.838   0.940
    7    0.712   0.759   0.876
    8    0.864   0.894   0.887
    9    0.465   0.614   0.891
}{\loadedtablesppr}


\begin{document}

    \begin{figure}
        \tikzset{export as png}
        \tikzsetnextfilename{my_externalized_plot}
        \begin{tikzpicture}
        \begin{axis}[my second axis style,
        ybar,
        ylabel={PR\textsubscript{A}},
        xtick= data,
        ]
        \addplot [my second ybar style=blue!50!black,] table [y=SP_cSi_2_3] {\loadedtablesppr};
        \addplot [my second ybar style=orange!50!black,] table [y=SP_cSi_2_4] {\loadedtablesppr};
        \addplot [my second ybar style=red!50!black,] table [y=Reference] {\loadedtablesppr};
        \legend{Floating 2.3~~ , Floating 2.4~~ , Reference}
        \end{axis}
        \end{tikzpicture}
    \end{figure}

\end{document}

请注意,我使用的是 ImageMagick。我不确定这是否也适用于 GraphicsMagick,但想法是一样的。external/system call/.add可能只有密钥会略有不同。此外,GhostScript是 ImageMagick 读取 PDF 文件所必需的。

答案2

  1. 下载图像魔法
  2. 安装Ghostscript
  3. 在 Magick 安装目录中,复制 2 份魔法精灵转换程序图像转换工具(参考这个帖子
  4. 在 tex 文件中按以下方式指定 documentclass

    \documentclass[border=5mm, convert]{独立}

  5. 使用以下命令生成 pdf 和 png

    pdf-latex --shell-escape 文件.tex

相关内容