0

I have a LaTeX document in which I used "hyperref" package for creating links between different parts of my document. The links are from a word to some piece of text in another section. I use the "book" document class. Links were working fine before I created the table of contents. As soon as I created toc, the links no longer point to the piece of text in target but to the corresponding section in the table of contents.

How can I keep using the table of contents and yet create links that refer directly to a piece of text in my document?


Edit: A Minimum Working Example

\documentclass{book}

\usepackage[dvipdfm]{hyperref}

% Defining a new command for safely creating targets in the section title
\newcommand{\targetInTitle}[2]{\texorpdfstring{\protect\hypertarget{#1}{#2}}{}}

\begin{document}

\tableofcontents
\newpage

\section{\targetInTitle{section1}{Section 1}}

Here is a \hyperlink{section1}{link} which suppose to show me the title of this section on the top of page 2 but, instead, it refers me to the table of contents on page 1.

\end{document}

There is also a warning in dvipdfm operation,

$ dvipdfm test.dvi
test.dvi -> test.pdf
[1][2
xdvipdfmx:warning: Object @section1 already defined.
]
9131 bytes written

1 Answers1

1

You are creating the target twice as it is moved to the table of contents too. You could e.g. use the NoHyper environment to suppress the target in the table of contents:

\documentclass{book}

\usepackage[dvipdfm]{hyperref}
% Defining a new command for safely creating targets in the section title
\newcommand{\targetInTitle}[2]{\texorpdfstring{\protect\hypertarget{#1}{#2}}{}}

\begin{document}

\begin{NoHyper}
\tableofcontents
\end{NoHyper}
\newpage

\section{\targetInTitle{section1}{Section 1}}

Here is a \hyperlink{section1}{link} which suppose to show me the title of this section on the top of page 2 but, instead, it refers me to the table of contents on page 1.

\end{document}

Ulrike Fischer
  • 327,261
  • Thanks. Neat and simple. Is there any way to keep the links of the table of contents but make them separate from the links I define within the text so that both of them will refer to a section? – Saeed Ahadian Jan 18 '20 at 17:45
  • 1
    You can also avoid that the target ends in the toc by using \section[Section 1]{\targetInTitle{section1}{Section 1}}, or you can define your command to be a dummy first and redefine it after the tableofcontents and so activate the hypertarget. – Ulrike Fischer Jan 18 '20 at 18:25