测量表格的列宽

测量表格的列宽

有没有办法确定tabular环境中第一列的宽度?

我曾考虑过使用,savebox但是那样只能给我文本的大小(并且仅在一个单元格中),而不是实际的列宽。

或者我应该使用longtable(或另一个包)来做到这一点?

答案1

这有一些限制tabular:你不能\multicolumn在最后一行有,也不能有可选参数\\(这个可能会被取消)。

\documentclass{article}
\usepackage{environ}

\makeatletter
\NewEnviron{mtabular}[3][c]{%
  \begingroup
  \renewcommand{\multicolumn}[3]{\multispan{##1}##3}%
  \let\\\cr
  \setbox\tw@=\vbox{%
    \ialign{&##\unskip\hfil\cr\BODY\crcr}%
    \get@widths{#3}%
  }%
  \endgroup
  \begin{tabular}[#1]{#2}\BODY\end{tabular}}

\def\get@widths#1{%
  \def\@temp{\else\@latex@warning{No such column}\fi}
  \setbox\z@=\lastbox
  \get@next@width
  \xdef#1##1{%
    \noexpand\ifcase##1\relax\unexpanded\expandafter{\@temp}%
  }%
}
\def\get@next@width{%
  \setbox\z@=\hbox{\unhbox\z@\unskip\global\setbox\@ne=\lastbox}%
  \ifvoid\@ne
  \else
    \edef\@temp{\noexpand\or\the\wd\@ne\unexpanded\expandafter{\@temp}}%
    \expandafter\get@next@width
  \fi
}
\makeatother

\begin{document}

\begin{mtabular}{lcr}{\foo}
abc & def & ghi \\
ABC & \multicolumn{2}{c}{aaa} \\
1 & 12 & 123
\end{mtabular}

The width of the first column was \foo{1}

The width of the second column was \foo{2}

The width of the third column was \foo{3}

\end{document}

它的工作原理是,首先以“缩小”的形式排版表格,然后删除最后一行并一点一点地拆开它。最后一个参数是mtabular一个宏名称,稍后可以与数字参数一起使用以获取相对列宽。

enter image description here

答案2

\documentclass{article}
\usepackage{array}

\makeatletter
\protected\def\z#1{\pdfsavepos\write\@auxout{\gdef\string\tpos#1{\the\pdflastxpos}}}%
\def\foo#1#2{\ifcsname tpos#1\endcsname\the\dimexpr\csname tpos#2\endcsname sp -\dimexpr\csname tpos#1\endcsname sp\relax\fi}
\makeatother

\begin{document}

\begin{tabular}{!{\z{a}}l!{\z{b}}c!{\z{c}}r!{\z{d}}}
abc & def & ghi \\
ABC & \multicolumn{2}{c}{aaa} \\
1 & 12 & 123
\end{tabular}

The width of the first column was \foo{a}{b}

The width of the second column was \foo{b}{c}

The width of the third column was \foo{c}{d}

\end{document}

enter image description here

结果与 egreg 略有不同,因为代码对是否包含 tabcolsep 填充有不同的看法。

相关内容