[Tex/LaTex] How to automatically determine the remaining width of the text field in this form

formshyperrefmacros

I have this form made with the aid of hyperref package using the form environment:

\documentclass[pagesize=pdftex,DIV=16]{scrartcl}
\usepackage{xcolor}
\usepackage{hyperref}

% \newlength\TextFieldLength
% \newcommand\TextFieldFill[2][]{%
%   \setlength\TextFieldLength{\linewidth}%
%   \settowidth{\dimen0}{#2 }%
%   \addtolength\TextFieldLength{-\dimen0}%
%   \TextField[#1,width=\TextFieldLength]{\raisebox{2pt}{#2}}%
% }

\begin{document}
\begin{Form}
\section*{Principal Investigator}
\TextField[backgroundcolor=gray!10,borderwidth=0,width=.95\linewidth]{Full Name:}\\[1ex]
% \TextFieldFill[backgroundcolor=gray!10,borderwidth=0]{Full Name:}\\[1ex]
\TextField[backgroundcolor=gray!10,borderwidth=0,width=6cm]{Department:}
\TextField[backgroundcolor=gray!10,borderwidth=0,width=7cm]{Institute:}\\[1ex]
% \TextFieldFill[backgroundcolor=gray!10,borderwidth=0]{Institute:}\\[1ex]
\TextField[backgroundcolor=gray!10,borderwidth=0,width=.95\linewidth]{E-Mail:}\\
\end{Form}
\end{document}

Output:
enter image description here

as you can see, the space of the text fields: Full Name, Institute, and E-Mail do not align well at their right end.

Searching for a solution I stumbled over this post which solved this problem when there is only one text field sitting in one line like that of the Full Name and E-Mail, but not for the Institute. This half solution is provided in the MWE as commented code lines.

Question: How to let LaTeX automatically compute and apply the remaining space of the text field till the end of the linewidth for Institute as well as for Full Name and E-Mail?

Best Answer

\documentclass[pagesize=pdftex,DIV=16]{scrartcl}
\usepackage{xcolor}
\usepackage{hyperref}

\newsavebox\TBox

\begin{document}
    \begin{Form}
        \section*{Principal Investigator}
        \sbox\TBox{Full Name: }%
        \TextField[backgroundcolor=gray!30,borderwidth=0,width=\dimexpr\linewidth-\wd\TBox]{Full
         Name:}\\[1ex]
        \sbox\TBox{Department: }%
        \TextField[backgroundcolor=gray!30,borderwidth=0,width=\dimexpr0.5\linewidth-\wd\TBox]{Department:}
        \sbox\TBox{ Institute: }%
        \TextField[backgroundcolor=gray!30,borderwidth=0,width=\dimexpr0.5\linewidth-\wd\TBox]{Institute:}\\[1ex]
        \sbox\TBox{E-Mail: }%
        \TextField[backgroundcolor=gray!30,borderwidth=0,width=\dimexpr\linewidth-\wd\TBox]{E-Mail:}
    \end{Form}
\end{document}

enter image description here