[Tex/LaTex] Transparency in tikz, preview package and xelatex

previewtikz-pgftransparencyxetex

Is it possible to have transparency in a tikz picture while using the preview package and compiling with xelatex?

The following mwe compiles without warnings/errors under both xelatex and pdflatex but with xelatex there is no transparency. Everything is printed opaque. With pdflatex everything works as expected.

\documentclass[a4paper,12pt]{article}

\usepackage{tikz}

\usepackage[xetex,active,tightpage]{preview}
%\usepackage[pdftex,active,tightpage]{preview}

\PreviewEnvironment[]{tikzpicture}

\begin{document}

\begin{tikzpicture}[line width=1ex]
  \draw (0,0) -- (3,1);
  \filldraw [fill=red,draw opacity=0.5] (1,0) rectangle (2,1);
\end{tikzpicture}

\end{document}

Best Answer

You can avoid the issue by selecting the page size to be equal to the picture size. Therefore you don't need preview and it works fine with XeLaTeX. For this you need to save the picture in a box register. Because geometry only allows to select the page size in the preamble you need to move the picture there, which is OK as long it inside a savebox (like inside a lrbox environment).

I'm planning to build a feature like this into standalone as an alternative to preview.

\documentclass[a4paper,12pt]{article}
\usepackage{tikz}
\usepackage{geometry}

%\usepackage[active,tightpage]{preview}
%\usepackage[pdftex,active,tightpage]{preview}
%\PreviewEnvironment[]{tikzpicture}

\pagestyle{empty}
\normalfont% required to select normal font already in the preamble
\begin{lrbox}{0}%
\begin{tikzpicture}[line width=1ex]
  \draw (0,0) -- (3,1);
  \filldraw [fill=red,draw opacity=0.5] (1,0) rectangle (2,1);
\end{tikzpicture}%
\end{lrbox}

\geometry{paperwidth=\wd0,paperheight=\ht0,margin=0cm}
\parindent=0pt
\begin{document}
\usebox{0}%
\end{document}

Result

(The outer dark frame is the background of the PDF viewer)


The upcoming version 1.0 of standalone includes code similar to this and avoids the need of preview. It should work fine for XeLaTeX.