TikZ-PGF – How to Calculate Total Width of a Tabularray Table and Integrate with TikZ or Tcolorbox

tablestabularraytcolorboxtikz-pgfwidth

Please consider the following code. It produces a table using tabularray which has fixed width columns, so its total width is smaller than \textwidth. How can find out what the total width of the table is, so I can pass this length to other packages such as tikz or tcolorbox and create a picture or a box with exactly the same width as the table? Please note that the box created, in the exable below, by tcolorbox is slightly at the left, why? Can be fixed? And also is slightly smaller than the rectangle created by tikz although they have virtually the same width, 15cm.

\documentclass[12pt]{article}
\usepackage[a4paper, total={180mm,257mm},left=15mm,top=20mm]{geometry}
\usepackage{tabularray}
\usepackage{tikz,tcolorbox,blindtext}


\begin{document}
    \begin{tblr}{colspec={Q[3.2cm,c]Q[5.2cm,c]Q[5.2cm,c]},rows={0.8cm,m},vlines,hlines}
        Column 1    & Column 2 & Column 3 \\                                                          
        A11         &   A12    &     A13  \\             
        A221        &   A22    &     A23  \\
    \end{tblr}

\vspace{10pt}

    \begin{tikzpicture}
        \draw (0,0) rectangle (15,4);
    \end{tikzpicture}

    \begin{tcolorbox}[width=15cm]
        \blindtext[1]
    \end{tcolorbox}
\end{document}

enter image description here

Best Answer

  • You could use the \settowidth macro to measure the width of your table. To avoid having to code the table twice, you could use a savebox and use it once to typeset your table and another time to measure the width.

  • The tcolorbox is not shifted to the left, instead everything else is shifted to the right from the normal paragraph indent of the class you use. You can avoid it locally by using \noindent or globally by changing the parindent length


\documentclass[12pt]{article}
\usepackage[a4paper, total={180mm,257mm},left=15mm,top=20mm]{geometry}
\usepackage{tabularray}
\usepackage{tikz,tcolorbox,blindtext}

\newlength{\foo}
\newsavebox{\mybox}



\begin{document}

\savebox{\mybox}{\begin{tblr}{colspec={Q[3.2cm,c]Q[5.2cm,c]Q[5.2cm,c]},rows={0.8cm,m},vlines,hlines}
        Column 1    & Column 2 & Column 3 \\                                                          
        A11         &   A12    &     A13  \\             
        A221        &   A22    &     A23  \\
    \end{tblr}}
    
\noindent\usebox{\mybox}

\settowidth{\foo}{\usebox{\mybox}}
    
    \noindent\rule{\foo}{1pt}

\vspace{10pt}

    \noindent\begin{tikzpicture}
        \draw (0,0) rectangle (\foo,4);
    \end{tikzpicture}

    \begin{tcolorbox}[width=\foo]
        \blindtext[1]
    \end{tcolorbox}
\end{document}

enter image description here