Search code examples
latexmacrosteximagepgf

The way to find out whole picture width in PGF (Latex)


I've got a latex macro that draws a picture using PGF and Tikz according to given parameters. The width of picture drawn depends on these parameters.

PGF automatically calculates the resulting width of any picture drawn so the user does not have to set it explicitly(like for example when using latex build in picture environment).

However I need to know the width of picture that will be drawn. Of cause I could calculate it as the PGF does but this is going to be quite some work(a lot of if statements...). Is there a way to ask PGF what is the width of picture that is to be drawn (some command I expect)? Either inside tikzpicture environment or just after it? Thanks for help.


Solution

  • What I would probably do is put the tikzpicture environment in a box, and then find the width of the box:

    \setbox0=\vbox{\hbox{%
      \begin{tikzpicture}
        % ...
      \end{tizpicture}%
    }}
    The width of the following picture is {\the\wd0}.
    \box0
    

    Note that after you run \box0, the box will be inserted into the document and its contents will be destroyed; you thus need to query the width of the box before you do that. If you want to save the width, you can store it in a dimension register with \dimen0=\wd0; alternatively, you can use \copybox0, which inserts the box but doesn't destroy it (although this might leak memory).

    Also, having played with some of this before, I found that using just a \vbox caused the box to always be the full width of the page (which, if you think about it, makes sense); however, using just an \hbox caused the unboxing to fail for some reason (it seemed to be a known pug). Using both like this works, however—I'm using something very much like this to render TikZ pictures to PDF files of precisely the right size.