0

Assume the following scenario. Some user is required to complete a macro ImagePath{} in order to automatically include an image at some predefined place of the document. No hypothesis is done about its extension. The MWE below fails to compile with error ! LaTeX Error: File `images/logo.png' not found. even if the file does exist.

\documentclass{report}
\usepackage{graphicx}
\makeatletter
\def\ImagePath#1{\def\@ImagePath{#1}}
\def\printImagePath{\@ImagePath}
\makeatother
\ImagePath{images/logo.png}
\begin{document}
\IfFileExists{\printImagePath}{
    \includegraphics{\printImagePath}
}{
    File \texttt{\printImagePath} does not exist
}
\end{document}

Surprisingly, if one imposes the extension, e.g. PNG, there is no more compilation error :

\documentclass{report}
\usepackage{graphicx}
\makeatletter
\def\ImagePath#1{\def\@ImagePath{#1}}
\def\printImagePath{\@ImagePath}
\makeatother
\ImagePath{logo}
\begin{document}
\IfFileExists{\printImagePath.png}{
    \includegraphics{\printImagePath.png}
}{
    File \texttt{\printImagePath.png} does not exist
}
\end{document}

Thus, is there a way to get the full image path from the user, whatever the extension is?

2 Answers 2

1

I do not know the details of the implementation, but as far as I know, \includegraphics expands its argument only once before trying to include the image. (I assume, this is a side effect of allowing active characters and such in the file name.)

If you design your macro in such a way that the macro used in \includegraphics immediately contains the image path, it works.

\documentclass{report}

\usepackage{graphicx}

\def\ImagePath#1{\def\theimagepath{#1}}

\ImagePath{images/logo.png}

\begin{document}

\IfFileExists{\theimagepath}{
    \includegraphics[width=.8\textwidth]{\theimagepath}
}{
    File \texttt{\theimagepath} does not exist
}

\end{document}
3
  • Also see this answer.
    – schtandard
    Commented Jun 3, 2019 at 13:22
  • Based on the answer you point out, \meaning\printImagePath produces macro:->\@ImagePath, which is not images/logo.png as expected. Commented Jun 3, 2019 at 13:34
  • By the way, this solution is far better than mine since it does not rely on any other packages. One even can avoid \makeatletter/\makeatother. Commented Jun 3, 2019 at 13:37
1

I finally found a solution (thanks to this comment), but I can't figure out how it works: loading grffile package in the preamble prevents from the compilation error…

\documentclass{report}
\usepackage{graphicx}
\usepackage{grffile}
\makeatletter
\def\ImagePath#1{\def\@ImagePath{#1}}
\def\printImagePath{\@ImagePath}
\makeatother
\ImagePath{images/logo.png}
\begin{document}
\IfFileExists{\printImagePath}{
    \includegraphics{\printImagePath}
}{
    File \texttt{\printImagePath} does not exist
}
\end{document}

Somebody able to explain why this works can comment this post.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .