TikZ-PGF – Fitting Page Size to a TikZ Figure

geometrypaper-sizetikz-pgf

Sometimes I'm using tikz as a plotting tool, without embedding the figure in a document. In this case, I normally, want to include the resulting PDF in a different TeX file (yes I know I could include the TikZ code directly, but it is not helpful in this case). Therefore, I want the picture to fit exactly to the page, so I won't have white space around it. To this end, I'm using the geometry package and clip of TikZ. For example, here:

\documentclass{minimal}
\usepackage{tikz}
\usepackage[paperwidth=1cm,paperheight=1cm,hmargin=0cm,vmargin=0cm]{geometry}

\begin{document}
\begin{center}
\begin{tikzpicture}
\clip (0,0) rectangle (1,1);
\draw[red] (0,0) -- (1,1);
\draw[red] (1,0) -- (0,1);
\draw[blue] (0,0) rectangle (1,1);
\end{tikzpicture}
\end{center}
\end{document}

Is there a better/nicer/more elegant way to do it?

EDIT 1:
For the sake of clarifying, I used clip because I thought it will make things simpler. Without it, things are actually more straightforward.

EDIT 2:

Unfortunately one can only accept one answer. In this case I could accept all. For me, I got to know three new tools, all are slightly different, to accomplish my goal. I choose the Martin's answer due to its standalone nature; no need of neither external tools nor post-proccessing. The other two options yielded more or less the same result.

Best Answer

Use the preview package with tightpage,active options to only display elements you want as single pages. You need to wrap the tikzpicture in preview environments or declare it as \PreviewEnvironment{tikzpicture}.

The standalone class gives you exactly this functionality in a very short form:

\documentclass[class=minimal,border=0pt]{standalone}
\usepackage{tikz}
\begin{document}
\begin{tikzpicture}
\clip (0,0) rectangle (1,1);
\draw[red] (0,0) -- (1,1);
\draw[red] (1,0) -- (0,1);
\draw[blue] (0,0) rectangle (1,1);
\end{tikzpicture}
\end{document}

Result

(Dark border is the PDF viewer background and not part of the PDF)

You then can load the standalone package (!) in a document and simply \input this file. The preamble and document environment will be automatically striped.

Note:

You are currently clipping at the center of the blue rectangle and cutting it in half. You need to add half the line with on each side of the clipping path:

\clip (-.5\pgflinewidth,-.5\pgflinewidth) rectangle ([shift={(.5\pgflinewidth,.5\pgflinewidth)}]1,1);