[Tex/LaTex] How to import separate standalone latex documents and assemble into one document

import

I am not asking about \include or \input here. I know all about these.

Here is the setup. I'd like to be able to build as standalone one of my HW reports which sits in its own folder. Then I also like to include this latex file and others in the main latex file in some parent folder, for my whole course to assemble everything into one document.

The problem is that to build the one HW on its own, I need to have it as a complete separate Latex document. So, when it comes to importing it into the main document, I have to go comment out all the preamble from each HW document otherwise one gets an error.

Note that I have to use the import package for this, and not the \include, since the import package handles relatives paths correctly. So I can't use things like \includeonly{A/a} since a.tex include images using relative paths in them, and I'll get an error about image not find if I just use \input or \include.

I have to use \subimport.

Better to give a simple example than all this rambling. Given this layout

 main.tex
     +
     |
     A/
   a.tex
   a.png

a.tex is

 \documentclass{article}
 \usepackage{graphicx}    
 \begin{document}    
 \includegraphics{a.png}
 \end{document}

and main.tex is

\documentclass{article}
\usepackage{graphicx}
\usepackage{import}
\begin{document}    
\subimport{A/}{a}  %notice that images included by a.tex are OK now
\end{document}

I can build a.tex ok. But to build main.tex, I have to comment a.tex as follows

 %\documentclass{article}
 %\usepackage{graphicx}    
 %\begin{document}    
 \includegraphics{a.png}
 %\end{document}

And to use a.tex again on its own, go back and uncomment the lines. This is getting tiring.

It will be nice if there was an option during an import to tell it to strip out all the latex preamble as it imports the file!

Any suggestions how to do this without this manual step?

I really do not want to collapse all my course tree into one folder just to do this. I like to keep each project and HW in its own folder so I can build each as a separate document, but I like to also be able to build the whole tree documents into one document.

Best Answer

The standalone package got written to do exactly that, i.e. remove preambles from sub-files. For this it redefines \documentclass (after \begin{document}) to strip everything until \begin{document} and ignore any additional document environments. The package works fine without the accompanying standalone class. However, I didn't explicitly tested it with the import package yet, but it should work.