3

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}

2 Answers2

3

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.

egreg
  • 1,121,712
1

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}%
}{}
ChrisS
  • 13,529