[Tex/LaTex] Wrapfig doesn’t detect new page

wrapfigure

MWE:

\documentclass[a4paper]{article}
\usepackage{mwe}
\usepackage{wrapfig}
\usepackage{blindtext}

\begin{document}

\blindtext \blindtext \blindtext \blindtext 

\begin{wrapfigure}{l}{0.5\textwidth}
\centering
\includegraphics[height=150pt,width=0.5\textwidth]{example-image-a}
\caption{A caption}
\end{wrapfigure}

\blindtext 

\end{document}

PICTURE

Undesidered space on new page

I want wrapfig do detect new page and start the text from the left margin of the page. Instead, the margin is such like the figure was still there

I would prefer an automated solution, as not to manually specify the number of narrow lines using the optional argument of wrapfig. I frequently change the text before the wrapfig.

Best Answer

Use package needspace and then:

\documentclass[a4paper]{article}
\usepackage{mwe}
\usepackage{wrapfig}
\usepackage{blindtext}
\usepackage{needspace}

\begin{document}

\blindtext \blindtext \blindtext \blindtext 

\Needspace{150pt}%% Same as image height 
\begin{wrapfigure}{l}{0.5\textwidth}
\centering
\includegraphics[height=150pt,width=0.5\textwidth]{example-image-a}
\caption{A caption}
\end{wrapfigure}
\blindtext 

\end{document}

I used only the image height for \needspace. In reality it should include the caption height.

enter image description here