5

I'm working on Sweave and using includegraphics for include image in report dynamically.

Pseudocode:

 <<>
     for ( i to 100)   # run loop 1 to 100
     {
          includegraphics(image.i)    # include image in article.
     }
 @

In the above code I am adding 100 images using loop but I need to check that image.i exists or not first before including the image in report. Is there any way to check it first.

lockstep
  • 250,273
manish
  • 9,111

1 Answers1

6

Put this into your preamble:

\newcommand\includegraphicsifexists[2][width=\linewidth]{\IfFileExists{#2}{\includegraphics[#1]{#2}}{}}

Then you can can safely use the following, the only problem is that you always have to add the extension:

\includegraphicsifexists[width=\linewidth]{nonexistingfile.pdf}

-------------------------------------------------------------------

You can make a version that makes a whole figure appear or not depending on the file presence (again, this goes to the preamble):

% arguments: [parameters for includegraphics]{filename}[float placement]{caption}
\makeatletter
\def\FIF@nopl[#1]#2#3{\IfFileExists{#2}{\begin{figure}\centering
  \includegraphics[#1]{#2}\caption{#3}\end{figure}}{}}
\def\FIF@pl[#1]#2[#3]#4{\IfFileExists{#2}{\begin{figure}[#3]\centering
  \includegraphics[#1]{#2}\caption{#4}\end{figure}}{}}
\newcommand\FigureIfExists[2][width=\linewidth]{\@ifnextchar[%
  {\FIF@pl[#1]{#2}}%
  {\FIF@nopl[#1]{#2}}%
}

Notice that I consider [width=\linewidth] as a good default argument to \includegraphics but you might change it of course. The usage is simple:

\FigureIfExists{myfile.pdf}[!t]{Caption of this nice figure.\label{fig:myfile}}

\FigureIfExists[scale=0.3]{nofile.pdf}[p]{This figure won't exist,
  nor the label.\label{fig:nofile}}
yo'
  • 51,322