# If No Image Is Found, An Empty Page Will Be Removed

I tried to do the following code... what I want is that Latex will remove the second page if there is no "image2" in the directory that I'm using (I want it to be such a "dynamic" doc), is it possible?

\documentclass[10pt,a4paper]{article}
\usepackage{graphicx}
\usepackage{subfig}
\usepackage{float}
\usepackage{textpos}
\usepackage[margin=0.5in,includefoot]{geometry}

\begin{document}

\begin{textblock}{2.5}(0,0)
\raggedright
\begin{figure}[H]
\includegraphics[height=3.2in]{image1}
\centering
\end{figure}
\end{textblock}

\newpage
\begin{textblock}{2.5}(0,0)
\raggedleft
\begin{figure}
\includegraphics[height=3.2in]{image2}
\centering
\end{figure}
\end{textblock}

\end{figure}
\end{document}

• Related: Can I test if a file exists? – Werner Jan 14 '15 at 7:37
• Welcome to TeX.SX! It's not clear why you're using the figure environment. It's not necessary to place \includegraphics in a figure, TeX just considers it as a big character. – egreg Jan 14 '15 at 8:00

You have to test all the possible extensions, if you don't want to give it explicitly.

\documentclass[10pt,a4paper]{article}
\usepackage{graphicx}
\usepackage{textpos}
\usepackage[margin=0.5in,includefoot]{geometry}

\makeatletter
\newcommand{\IfImageExists}[1]{%
\@tempswafalse
\@for\IIE@temp:=\Gin@extensions\do{% a similar test is in graphics.sty
\IfFileExists{#1\IIE@temp}{\@tempswatrue}{}%
}%
\if@tempswa
\expandafter\@firstoftwo
\else
\expandafter\@secondoftwo
\fi
}
\makeatother

\begin{document}

\IfImageExists{example-image}{%
\begin{textblock}{2.5}(0,0)
\raggedright
\includegraphics[height=3.2in]{example-image}
\end{textblock}}
{}

\newpage

\IfImageExists{./example-image}{%
\begin{textblock}{2.5}(0,0)
\raggedright
\includegraphics[height=3.2in]{./example-image}
\end{textblock}}
{}

\end{document}


This prints only one image, because I have no example-image.??? file with a suitable extension for graphic inclusion, but there is (part of the mwe package) in a global search directory (first call).

The third argument to \IfImageExists can contain code to be executed if the image file is not found.

If you have a fixed extension, say .png, you can use

\IfFileExists{./image1.png}{<true>}{<false>}


insteand of \IfImageExists.

Use the \IfFileExists command. The block of code that generates the second figure becomes

\IfFileExists{image2}{%
\newpage
\begin{textblock}{2.5}(0,0)
\raggedleft
\begin{figure}
\includegraphics[height=3.2in]{image2}
\centering
\end{figure}
\end{textblock}%
}{}

• This tests for the existence of image2.tex. – egreg Jan 14 '15 at 8:01