[Tex/LaTex] tikz external use png as default instead of pdf

tikz-externaltikz-pgf

I have somewhat successfully set up my tikz external code using zeroth's very helpful advise Externalization to other format, Makefile. Add new rules to the makefile

My aim is to generate pngs for some files instead of pdfs. The problem with the above method is that it generates the pdf's as well (with the same name) and hence the \pgfimage command will always include the pdf instead of the png. I have some rather large plots, which are very easily generated with tikz but are much quicker to render in their bitmap format.

I have come as far as generating the pdf, converting to png and then deleting the pdf. But this now will re-generate the deleted pdfs everytime I rerun the makefile. I'm not too familiar with the tikz external code. Is there a convenient way to set it up to generate the pngs only?

Here is my current setup:

\documentclass{minimal}
\usepackage{tikz}
\usetikzlibrary{external}

\tikzsetexternalprefix{tikz/}
\tikzexternalize[mode=list and make]

%pdf setup
\tikzset{external/system call=%
    {xelatex \tikzexternalcheckshellescape -halt-on-error -interaction=batchmode -jobname "\image" "\texsource"}}

%optional png setup
\tikzset{
    png export/.style={
        external/system call=%
        {xelatex \tikzexternalcheckshellescape -halt-on-error -interaction=batchmode -jobname "\image" "\texsource";%
         convert -density 300 -transparent white "\image.pdf" "\image.png"; rm -f "\image.pdf"},
    }
}

\begin{document}
    \begin{tikzpicture}
        \draw (0,0) circle (2);
    \end{tikzpicture}
    %now png export
    \bgroup
    \tikzset{png export}
    \begin{tikzpicture}
        \draw (0,0) circle (2);
    \end{tikzpicture}
    \egroup 
\end{document}

Best Answer

The easiest thing is to alter the import statements to prefer the png images.

As you already have an png export style, you could add an png import statement.

This would prefer the png's over the pdf.

Basically you alter the external command for including images (see the manual for better explanation)

\tikzset{%
    % Add size information to the .dpth file (png is in density not size)
    /pgf/images/external info,
    % Use the png export AND the import
    use png/.style={png export,png import},
    png import/.code={%
        \tikzset{%
            /pgf/images/include external/.code={%
                % Here you can alter to whatever you want
                % \pgfexternalwidth is only available if /pgf/images/external info
                % is set
                \includegraphics%
                [width=\pgfexternalwidth,height=\pgfexternalheight]%
                {{##1}.png}%
            }%
        }%
    }%
}

Then simply do this:

\bgroup
\tikzset{use png}
\begin{tikzpicture}
    \draw (0,0) circle (2);
\end{tikzpicture}
\egroup 

And when exporting it will generate the png as well as preferring the png when importing.

Related Question