[Tex/LaTex] Using hyperref with \addcontentsline

bookmarkshyperref

I have a document with a (logical) section that does not have a standard heading (i.e., no \section or whatever), and I would like it to appear in the table of contents and in the PDF bookmarks. I can almost do it by using \addcontentsline: It is detected by hyperref, but the bookmark that it generates is broken. Clicking on it takes me to the previous bookmark.

I know how to generate a working bookmark with \pdfbookmark[1]{Section without standard heading}{uniqueID}, but I also want to see the section in the TOC. (Naturally, using both commands gives me two bookmarks, one of them broken.)

The problem is unchanged when I set hypertexnames=false (which is supposed to generate unique identifiers). Here is a complete example:

\documentclass{article}

\usepackage[bookmarks,hypertexnames=false,debug]{hyperref}

\begin{document}
\section{First page}

\newpage
\textbf{Text on page 2}

\addcontentsline{toc}{section}{Section without standard heading} % broken bookmark
% This will work, but I still need the TOC
%\pdfbookmark[1]{Section without standard heading}{page2}
Second page text

\newpage
\section{Third section}

\end{document}

Best Answer

You need an anchor for \addcontentsline. The anchor is usually set by a section command. This allows the bookmark by \addcontentsline to point to the section title and not to the place, where \addcontentsline is issued.

An anchor can be set by \phantomsection. If the bookmark should point to the bold text on page 2, then put \phantomsection right after \newpage:

\documentclass{article}

\usepackage[bookmarks,hypertexnames=false,debug]{hyperref}
\usepackage{bookmark}

\begin{document}
\section{First page}

\newpage
\phantomsection
\textbf{Text on page 2}

\addcontentsline{toc}{section}{Section without standard heading}
Second page text

\newpage
\section{Third section}

\end{document}

I have added package bookmark for faster updated bookmarks.

Related Question