[Tex/LaTex] PDF bookmark going to the bottom of the previous page in case when caption header is on the top of a page

hyperreflinkspositioning

\documentclass[12pt,a4paper]{mwrep}
\usepackage{lipsum}
\usepackage[nodisplayskipstretch]{setspace} \setstretch{1.3}
\usepackage[hidelinks,unicode,pdfencoding=auto]{hyperref}
\usepackage[all]{hypcap}
\begin{document}
\tableofcontents
\chapter{Chapter A}
\section{Section AA}
\lipsum
\section{Section AB}
\lipsum
Text

Text

Text

Text

Text

Text

\subsection{Subsection ABA}
\lipsum
\chapter{Chapter B}
\section{Section BA}
\lipsum
\subsection{Subsection BAA}
\lipsum
\end{document}

Try to click on PDF bookmark or hyperlink in table of contents (Section AB, Subsection ABA, Subsection BAA). It leads to the bottom of the previous page in case when appropriate [sub]section header is at the top of a page. This is annoying when reading PDF documents in "full page mode" as it goes to the wrong page (the previous one). For some reason the problem does not affect chapter headers. How can it be fixed?

Best Answer

Here is an automated solution using the hack that I commented earlier using the needspace package. The \section command is redefined to insert \needspace{3\baselineskip} before each section. This ensures that there ar at least three lines available, otherwise the section is begun on a new page. I think three should be adequate, but if not it can be increased.

So adding this to the preamble fixes the problem with your MWE:

\usepackage{needspace}
\let\OldSection\section%
\renewcommand{\section}{\needspace{3\baselineskip}\OldSection}%

Here is the complete MWE:

\documentclass[12pt,a4paper]{mwrep}
\usepackage{lipsum}
\usepackage[nodisplayskipstretch]{setspace} \setstretch{1.3}
\usepackage[hidelinks,unicode,pdfencoding=auto]{hyperref}
\usepackage[all]{hypcap}

\usepackage{needspace}
\let\OldSection\section%
\renewcommand{\section}{\needspace{3\baselineskip}\OldSection}%

\begin{document}
\tableofcontents
\chapter{Chapter A}
\section{Section AA}
\lipsum
\section{Section AB}
\lipsum
Text

Text

Text

Text

Text

Text

\subsection{Subsection ABA}
\lipsum
\chapter{Chapter B}
\section{Section BA}
\section*{Section BB}
\lipsum
\subsection{Subsection BAA}
\lipsum
\end{document}
Related Question