Correct hyperlinks by phantomsection

In forums, users frequently complain that some hyperlinks are incorrect; the target is pointing below the section start, not directly at the section or chapter title. This will happen if starred sectioning commands like \chapter* and \section* are used together with \addcontentsline, like in this short book class example 1:

\documentclass[a4paper,10pt]{book}
\usepackage{hyperref}
\begin{document}
\tableofcontents
\chapter{Test}
Text
\listoffigures
\addcontentsline{toc}{chapter}{listfigurename}
\listoftables
\addcontentsline{toc}{chapter}{listtablename}
\clearpage
Text
\end{document}

If you don’t want to compile that example by yourself you can view it here. Click the links and check the target.

The same problem appears with KOMA classes. Here’s a scrreprt example:

\documentclass[a4paper,10pt,liststotoc,bibtotoc]{scrreprt}
\usepackage{hyperref}
\begin{document}
\tableofcontents
\chapter{Test}
Text
\listoffigures
\listoftables
\clearpage
Text
\end{document}

If you click the links you will get to a place below the list headings.

To solve this problem, we can use the \phantomsection command. This command sets an anchor at the location where it’s called, that anchor can be used afterwards.

The first example can be corrected this way:

\documentclass[a4paper,10pt]{book}
\usepackage{hyperref}
\begin{document}
\tableofcontents
\chapter{Test}
Text
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{listfigurename}
\listoffigures
\cleardoublepage
\phantomsection
\addcontentsline{toc}{chapter}{listtablename}
\listoftables
\clearpage
Text
\end{document}

04. January 2014 by stefan
Categories: General | Leave a comment

Leave a Reply