# Filling blank space with optional images

Let's have some book. Due to the typesetting, there is some blank space, maybe even some blank pages.

I'd like to fill it with some images related to the place, i.e., the image is selected specifically for the previous chapter/song/whatever. The purpose of such images is just to fill some blank space with something related, but they aren't essential for the content.

Of course, one can insert images manually using includegraphics, but when something changes (paragraph inserted, margin changed, font changed, …), some blank space can disappear. In that case, I do not want the image to be there – it should be just skipped.

I believe there must be some way to do this, but I haven't found it.

I do not know if there exists a standard command or package for that, but it is not too difficult to come up with a slight modification of this answer that does something along those lines.

\documentclass[a4paper,12pt]{article}
\usepackage[top=2cm,bottom=2cm,hmargin=2cm]{geometry}
\usepackage{graphicx}

\newsavebox\myfig

\newcommand{\IfSpaceAllowsShowGraphics}[1]{%
\par
\edef\measurepage{\the\dimexpr\pagegoal-\pagetotal-\baselineskip\relax}%
\savebox\myfig{#1}%
\ifdim\measurepage>\ht\myfig
\usebox{\myfig}%
\fi
}

\usepackage{lipsum}

\begin{document}

\section*{Firstpage}

\lipsum[1-6]

\IfSpaceAllowsShowGraphics{\includegraphics{example-image-duck}}
%%The value seems to be calculated correctly

\newpage

\section*{Secondpage}
%% Skip the measured space from the page before

\lipsum[5]

%%This is not the value stored above
\IfSpaceAllowsShowGraphics{\includegraphics{example-image-duck}}

\end{document}


• I added a \par at the outset, just for being sure that the page builder has been exercised. Probably some vertical space should be added before the picture. Sep 23 '18 at 14:49
• @egreg Mille grazie! Yes, you are right, and I expect other modifications to be asked for like centered images or even a caption. Let's see what the OP says.
– user121799
Sep 23 '18 at 14:53