[Tex/LaTex] From inside a LaTeX article, I want to render several parts of the code into a separate png (a “render pass”)

pngtikz-external

I have a long article with many, say, TikZ images. Let's say it looks like:

\documentclass{article}
\usepackage{tikz}
\begin{document}
    ...much more stuff...
\begin{tikzpicture}
    \draw[red] (0,0) -- (1,1);
\end{tikzpicture}
    ...much more stuff...
\end{document}

Now from this file, I want to render the whole article into a pdf and also the tikzpicture into a PNG. This has to happen automatically with latex since I want to write a package that uses this.

(So answering "Oh, just copy and paste the image code to a separate file." is not helpful.)

Best Answer

You can use the TikZ external library to automatically generate PNGs of your tikzpictures.

The style

\tikzset{
    png export/.style={
        external/system call={
            pdflatex \tikzexternalcheckshellescape -halt-on-error -interaction=batchmode -jobname "\image" "\texsource";
            convert -density 300 -transparent white "\image.pdf" "\image.png"
        }
    }
}

specifies that after the tikzpicture is compiled using pdflatex, ImageMagick (convert) is used for generating a PNG from the PDF. This requires pdflatex to be called with -shell-escape.

Here's a complete example:

\documentclass[11pt]{article}
\usepackage{tikz}
\usetikzlibrary{external}
\tikzset{
    png export/.style={
        external/system call={
            pdflatex \tikzexternalcheckshellescape -halt-on-error -interaction=batchmode -jobname "\image" "\texsource";
            convert -density 300 -transparent white "\image.pdf" "\image.png"
        }
    }
}
\tikzexternalize
\tikzset{png export}

\begin{document}

\tikzset{external/force remake}
\begin{tikzpicture}
\node [orange,scale=10] {1};
\end{tikzpicture}
\begin{tikzpicture}
\node [cyan,scale=10] {2};
\end{tikzpicture}
\end{document} 
Related Question