Argument of \pgfkeys@temp has an extra }. (tikz and hyperref incompatibility?)

hyperrefpdftextikz-pgf

I'm trying to use TikZ in a section heading, following the answers to TikZ in section heading, but for some reason it fails to build whenever hyperref is involved:

\documentclass{article}
\usepackage{hyperref}
\usepackage{tikz}

\DeclareRobustCommand\circled[1]{\fbox{\tikz[baseline=(char.base)]{
        \node[shape=circle,draw,inner sep=2pt] (char) {#1};}}}

\begin{document}

\section{Custom \circled{word} in Section heading}

\end{document}

pdflatex reports:

! Argument of \pgfkeys@temp has an extra }.
<inserted text>
                \par
l.10 ...{Custom \circled{word} in Section heading}

If I remove the hyperref import everything works. What's wrong here?

I'm using:

  • pdfTeX 3.14159265-2.6-1.40.20 (TeX Live 2019/Debian)
  • texlive 2019.20200218-1

I also tried reordering the tikz and hyperref imports to no avail.

Best Answer

As suggested by @muzimuzhiZ, the solution is to hide the tikz commands from hypertex's PDF metadata using \texorpdfstring, e.g.:

\DeclareRobustCommand{\circled}[1]{\texorpdfstring{\fbox{\tikz[baseline=(char.base)]{
        \node[shape=circle,draw,inner sep=2pt] (char) {#1};}}}{#1}}