4

I would like to determine the size of a TikZ picture programmatically somehow. Is there a way to do that? Here's a simple MWE where I can estimate the size to be around 8cm x 11cm by knowing the block sizes and counting the node distances between them. But a more complex TikZ picture would make estimating the finished size more difficult.

MWE

\documentclass{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}

\begin{document}

\begin{tikzpicture} [bigblock/.style={draw, rectangle, minimum size=5cm}, smallblock/.style={draw, rectangle, minimum size=2cm} ]

\node [bigblock]                    (box1)  {};
\node [bigblock, above=of box1]     (box2)  {};
\node [smallblock, right=of box2]   (box3)  {};

\end{tikzpicture}

\end{document}

  • Yes, that worked. Had to remove the \show\pgfextractx command and combined it with the answer here https://tex.stackexchange.com/questions/8260/what-are-the-various-units-ex-em-in-pt-bp-dd-pc-expressed-in-mm to convert pts to mm – EarthIsHome Sep 22 '21 at 16:30
  • 1
    If you want, you could change the title to ask for cm (to avoid closure of question as duplicate). A title asking about "size" is easier found by others than asking about "bounding box", so I think it would be nice. Then also post your solution. – hpekristiansen Sep 22 '21 at 16:37

1 Answers1

3

Thanks to @hpekristiansen in the comments for pointing out this answer that prints the size of the TikZ picture in pt units: https://tex.stackexchange.com/a/137367/33388

I also combined it with the answer here to convert from pts to cm: https://tex.stackexchange.com/a/137367/33388

MWE

\documentclass[varwidth]{standalone}
\usepackage{tikz}
\usetikzlibrary{positioning}
%\show\pgfextractx

\newlength{\mywidth} \newlength{\myheight}

\makeatletter \newcommand{\pgfsize}[2]{ % #1 = width, #2 = height \pgfextractx{@tempdima}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}} {\pgfpointanchor{current bounding box}{north east}}} \global#1=@tempdima \pgfextracty{@tempdima}{\pgfpointdiff{\pgfpointanchor{current bounding box}{south west}} {\pgfpointanchor{current bounding box}{north east}}} \global#2=@tempdima } \def\convertto#1#2{\strip@pt\dimexpr #2*65536/\number\dimexpr 1#1} \makeatother

\begin{document}

\begin{tikzpicture} [bigblock/.style={draw, rectangle, minimum size=5cm, align=center}, smallblock/.style={draw, rectangle, minimum size=2cm, align=center} ]

\node [bigblock]            (box1)  {};
\node [bigblock, above=of box1]     (box2)  {};
\node [smallblock, right=of box2]   (box3)  {};

\pgfsize{\mywidth}{\myheight} \end{tikzpicture}

% varwidth option was added to the standalone class options to allow for line breaks Width = \convertto{cm}{\the\mywidth} cm\ Height = \convertto{cm}{\the\myheight} cm

\end{document}

Width and height of TikZ picture in cm