# Save multiple figures generated with TikZ as individual images

I am generating a set of figures inside a foreach loop. I would like to save each figure as an individual image (with any extension). How could I achieve this? Below is the code I use to generate the figures:

\documentclass[11pt]{article}
\usepackage{float}
\usepackage{tikz}
\begin{document}

\foreach \x/\y in {3.8/4,5.7/5,6.4/5 }
{
\begin{figure}[H]
\centering
\begin{tikzpicture}
\draw[draw=black, very thick, fill=gray!30] (0,0) rectangle ++(\x,\y);
\end{tikzpicture}
\caption{Base \x~cm and height \y~cm.}
\end{figure}
}

\end{document}


In reality I am generating over 200 complex figures inside the loop. Can anyone point me into the right direction?

• Maybe using the standalone document class. The PDF can be split using a PDF software. Dec 23 '20 at 3:37

By using tikz's external library all your images created inside tikzpicture will automatically be saved externally as separate files upon creation (in the case below, in /tikzpics in your working folder). This has the main advantage that subsequent compilations don't recreate each image, instead they are searched for in the save folder and loaded, unless they were modified in your source code.

\documentclass[11pt]{article}
\usepackage{float}
\usepackage{tikz}
\usetikzlibrary{external}

\tikzexternalize
\tikzsetexternalprefix{tikzpics/}

\begin{document}

\foreach \x/\y in {3.8/4,5.7/5,6.4/5 }
{
\begin{figure}[H]
\centering
\begin{tikzpicture}
\draw[draw=black, very thick, fill=gray!30] (0,0) rectangle ++(\x,\y);
\end{tikzpicture}
\caption{Base \x~cm and height \y~cm.}
\end{figure}
};

\end{document}


In this way, all the images you create will be found in the specified folder as separate pdf files.

You can take a look at section 52 of pgfmanual for more details on how it works. Beware that for the externalization to work, you have to enable system calls (you can refer to the manual for it).

• I would only add that you can have \tikzsetnextfilename{\x_\y} before every picture to give it a custom name based on the loop variables. Dec 23 '20 at 16:03