[Tex/LaTex] wrapfig – Make wrapped image respect margins and page ends

marginspage-breakingwrapwrapfigure

I need to insert images wrapped in text. wrapfig obviously comes to mind. The problem is the wrapped figure, by default, ignores margins and even page ends.

I mean, if I put the image less than its height from the page end, the image trespasses margins and even page dimensions, getting cut out, instead of going in the next page like graphicx does.

Here's an example:

\documentclass[a4paper]{article}
\usepackage{graphicx}
\usepackage{lipsum}
\usepackage{wrapfig}

\begin{document}

Text at the top

\vspace{17cm}

\begin{wrapfigure}{r}{9cm}
\includegraphics[width=9cm]{zappa}
\end{wrapfigure} 

\lipsum[5]

\end{document}

Which, looking where the first page ends and the second begins, results in this

Image cut out

As you can see, the image goes beyond the lower margin, where the text ends, gets cut out where the page ends.

Also, the rest of the text, which gets in the next page as the first is finished, presents the shape of the part of the image which wasn't counted in the indentation of text in page 1.

This forces me to manually adjust the block by putting, for example, a newpage before \begin{wrapfigure}. If I latter change something above it, I may have to manually change my adjustment maybe by removing the newpage and so on.

Is there a way to make wrapfig automatically adjust the layout, like graphicx does when it has the [H] option?

Best Answer

You can use R rather than r and then wrapfig will allow the figure to float to a certain extent to avoid falling off the end of a page.