# How to obtain width of longtable?

I need to create multiple tables of the same width, one of them needs to be a longtable due to spanning multiple pages. I could set the width of all of them to a predefined value. However, I would rather like to take it from the natural width of one of the tables. How could I do this?

-

Inside the threeparttablex package I use this construction to detect the width from within the table itself

\noalign{\begingroup
\setlength\TPTL@width{0pt}
\@nameuse{LT@\roman{LT@tables}}
\endgroup}


Then the width is then stored in \TPTL@width globally. It takes a few compilations before it is stable.

-

Write the longtable into an external file and read it in with \LTXtable:

\documentclass{article}
\usepackage{filecontents}
\usepackage{ltxtable}
\newsavebox\TBox
\begin{document}

\savebox\TBox{%
\begin{tabular}{@{} ccc @{}}\hline
One & Two & Three\\\hline
\end{tabular}}

\begin{center}
\usebox\TBox
\end{center}

\begin{filecontents*}{myLongtab.tex}
\begin{longtable}{@{} ccX @{}}\hline
1 & 2 & 3\\\hline
\end{longtable}
\end{filecontents*}

\LTXtable{\wd\TBox}{myLongtab}

\end{document}


-

This is a solution without getting the width of one of the table but you may combine it with daleif’s answer.

\documentclass{article}
\usepackage{tabu,longtable}
\newlength{\mytablen}
\setlength{\mytablen}{5cm}
\begin{document}
Short Table:

\begin{tabu} to \mytablen {|XX|}
1 & 2\\
3 & 4\\
\end{tabu}

\bigskip
Long Table:

\begin{longtabu} to \mytablen {|XX|}
1 & 2\\
3 & 4\\
\end{longtabu}
\end{document}


Note that the {longtabu} is centered by default an that longtable needs to be loaded manually

-

Similar to daleif's solution, hack into longtable package:

\documentclass{article}

\usepackage{longtable}

\makeatletter
\def\getLTwidth#1{%
\begingroup
#1=0pt%
\LT@save@row
\edef\X{\noexpand#1=\the#1\relax}%
\expandafter\endgroup\X}
\makeatother
\newlength\LTwidth

\begin{document}

\begin{longtable}[l]{|c|c|}
foo & bar \\
1 & 1234567 \\
\end{longtable}

\getLTwidth\LTwidth
\noindent\rule{\LTwidth}{1pt}

\end{document}


\getLTwidth gets the last longtable's width and set the variable locally.

-
you don't need threeparttablex in my solution above –  daleif Apr 20 '11 at 16:31
That's true, I didn't noticed it. The code is still a little different. I use \LT@save@row outside longtable package, and (maybe unnecessary) set the dimension locally. –  Leo Liu Apr 20 '11 at 17:21