[Tex/LaTex] Is it possible to use includegraphics with relative path inside subfiles

graphicssubfiles

Question

I have many documents that I want to be merged inside one document. It could be for example a kind of year recap, with many different sources that use the same preambule like lectures, labs, assignments, tests, …

I tried to use the subfiles package but I can't compile the main document because of relative path inside sub documents:

File `image.png' not found

Is it possible to include graphics inside a subfile using a relative path ?

Minimal working example

I want a file sub.tex to be included inside a bigger document main.tex:

main.tex
sub/sub.tex
sub/image.png

The main document is not in the same directory as the sub document and is as follows:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{subfiles}

\begin{document}
  Main file
  \subfile{sub/sub.tex}
\end{document}

My sub file sub.tex includes an image image.png with a relative path:

\documentclass[../main.tex]{subfiles}

\begin{document}
  Sub file
  \includegraphics{image.png}
\end{document}

What I tried

Following a comment below, I have defined two commands Subfile and IncludeGraphics in main.tex and I use them in both files:

\usepackage{xstring}

\def\SubfilePath{}
\def\Subfile#1{%
    \def\SubfilePath{\StrBefore{#1}{/}/}%
    \subfile{#1}}

\newcommand\IncludeGraphics[2][]{%
  \includegraphics[#1]{\SubfilePath #2}}

Unfortunately, I'm not able to compile main.tex whereas everything is fine with sub.tex:

Use of \Gin@ii doesn't match its definition

Best Answer

Package graphics provides \graphicspath that allows one to specify further directories for the search path of image files:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{subfiles}

\begin{document}
  Main file

  \graphicspath{{sub/}}
  \subfile{sub/sub.tex}
\end{document}

Or \graphicspath can be called automatically for each \subfile:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage[T1]{fontenc}
\usepackage{graphicx}
\usepackage{subfiles}

\makeatletter
\let\org@subfile\subfile
\renewcommand*{\subfile}[1]{%
  \filename@parse{#1}% LaTeX's file name parser
  \expandafter
  \graphicspath\expandafter{\expandafter{\filename@area}}%
  \org@subfile{#1}%
}
\makeatother

\begin{document}
  Main file
  \subfile{sub/sub.tex}
\end{document}
Related Question