Since you are setting secnumdepth
to zero, no anchors are generated for the hyperlinks and this produces the undesired effect mentioned; the following code works as expected:
\documentclass{report}
\usepackage[linktoc=all]{hyperref}
\usepackage{titlesec}
\hypersetup{
colorlinks,
citecolor=black,
filecolor=black,
linkcolor=black,
urlcolor=black
}
\begin{document}
\tableofcontents
\chapter{test}
Test text
\newpage
\section{A section}
Lorem Ipsum
\newpage
\subsection{This link is correct}
\end{document}
If you want to have all your sections and subsections to be unnumbered but included in the ToC and stll generating the correct hyperlinks, one option would be to use the \phantomsection
command to generate the anchors:
\documentclass{report}
\usepackage[linktoc=all]{hyperref}
\setcounter{secnumdepth}{0}
\usepackage{titlesec}
\hypersetup{
colorlinks,
citecolor=black,
filecolor=black,
linkcolor=black,
urlcolor=black
}
\begin{document}
\tableofcontents
\chapter{test}
Test text
\newpage
\phantomsection
\section{A section}
Lorem Ipsum
\newpage
\phantomsection
\subsection{This link is correct}
\end{document}
Another option would be to use the titlesec
and titletoc
packages to remove the numbering from both the document body and the ToC:
\documentclass{report}
\usepackage[linktoc=all]{hyperref}
\usepackage{titlesec}
\usepackage{titletoc}
\titleformat{\section}
{\normalfont\Large\bfseries}{}{1em}{}
\titleformat{\subsection}
{\normalfont\large\bfseries}{}{1em}{}
\titlecontents{section}
[1.5em] {}{}{}
{\titlerule*[1em]{.}\contentspage}
\titlecontents{subsection}
[3.8em] {}{}{}
{\titlerule*[1em]{.}\contentspage}
\hypersetup{
colorlinks,
citecolor=black,
filecolor=black,
linkcolor=black,
urlcolor=black
}
\begin{document}
\tableofcontents
\chapter{test}
Test text
\newpage
\section{A section}
Lorem Ipsum
\newpage
\subsection{This link is correct}
\end{document}
Yet another option would be to use the starred versions of the sectional units (i.e., \section*
, \subsection*
) and to use \addcontentsline
to manually add the entries to the ToC:
\documentclass{report}
\usepackage[linktoc=all]{hyperref}
\hypersetup{
colorlinks,
citecolor=black,
filecolor=black,
linkcolor=black,
urlcolor=black
}
\begin{document}
\tableofcontents
\chapter{test}
Test text
\newpage
\section*{A section}
\addcontentsline{toc}{section}{A section}
Lorem Ipsum
\newpage
\subsection*{This link is correct}
\addcontentsline{toc}{subsection}{This link is correct}
\end{document}
Package hyperref Warning: The anchor of a bookmark and its parent's must not be the same. Added a new anchor on input line 20.
gives you a hint to the anchor. The answer by Gonzalo Medina explains why.titlesec
is not compatible withhyperref
for unnumbered sections, seeREADME
ofhyperref
.