当 \includegraphics 返回警告“文件未找到”时避免打印文件名

当 \includegraphics 返回警告“文件未找到”时避免打印文件名

我在表格中使用\includegraphics如下内容:

\documentclass[a4paper,11pt]{article}
\usepackage{graphicx}


\begin{document}
\begin{table}
    \centering
    \begin{tabular}{ccc}
        \includegraphics[width=.3\textwidth]{image1.png} &
        \includegraphics[width=.3\textwidth]{image2.png} &
        \includegraphics[width=.3\textwidth]{image3.png} \\
        \includegraphics[width=.3\textwidth]{image3.png} &
        \includegraphics[width=.3\textwidth]{image4.png} &
        \includegraphics[width=.3\textwidth]{image3.png} \\
    \end{tabular}
\end{table}
\end{document}

Latex 通常会抛出一个Warning Error不会阻止编译但会打印文件名作为结果的错误,这会导致如下结果: 示例代码的结果

这通常非常有用,但在这个特殊情况下,我想避免这种情况,只需将单元格留空即可。有没有简单的方法可以做到这一点?

答案1

如果您删除文件名的扩展名,它应该可以按您希望的方式工作:

\documentclass[a4paper,11pt]{article}
\usepackage{graphicx}


\begin{document}
\begin{table}
    \centering
    \begin{tabular}{ccc}
        \includegraphics[width=.3\textwidth]{image1} &
        \includegraphics[width=.3\textwidth]{image2} &
        \includegraphics[width=.3\textwidth]{image3} \\
        \includegraphics[width=.3\textwidth]{image3} &
        \includegraphics[width=.3\textwidth]{image4} &
        \includegraphics[width=.3\textwidth]{image3} \\
    \end{tabular}
\end{table}
\end{document}

答案2

您可以\IfFileExits{<file>}{<what to do if so>}{<what to do otherwise>}在使用之前检查文件是否存在\includegraphics

请注意,以下示例仅在使用文件扩展名时才有效。没有此限制的宏也是可行的,但会更加复杂。

\documentclass[a4paper,11pt]{article}
\usepackage{graphicx}

\newcommand\includeexistinggraphics[2][]{%
    \IfFileExists{#2}{%
        \includegraphics[#1]{#2}%
    }{}%
}

\begin{document}
\begin{table}
    \centering
    \begin{tabular}{ccc}
        \includeexistinggraphics[width=.3\textwidth]{image1.png} &
        \includeexistinggraphics[width=.3\textwidth]{image2.png} &
        \includeexistinggraphics[width=.3\textwidth]{image3.png} \\
        \includeexistinggraphics[width=.3\textwidth]{image3.png} &
        \includeexistinggraphics[width=.3\textwidth]{image4.png} &
        \includeexistinggraphics[width=.3\textwidth]{image3.png} \\
    \end{tabular}
\end{table}
\end{document}

相关内容