PDF Layers (OCG) using xelatex

I am switching from pdflatex to xelatex and have trouble finding an alternative on how to do layers in the pdf. So far I have been using ocg.sty to separate relevant content from eye-candy content (background images, illustrations), so the reader can hide the latter for printing.

However, ocg.sty does not work with xelatex due lack of pdfobj support. The newer CTAN ocgtools package also has this issue and will work with pdflatex, but not xelatex.

Is there currently any way to produce ocg layers using xelatex? Or is there another approach for hiding/disabling some parts (not necessarily only images) in a PDF before printing?

-

In principle, it is possible. However, someone has to add the support for xetex into the packages. You may try to compile the following text with xetex. The second line is in optional OCG and can be switched off. Stolen from here.

%create new OCG
\special{pdf:obj @ocg <</Type/OCG /Name (myocg)>>}

%register it and configure its default behaviour
\special{pdf:put @catalog <<
/OCProperties <<
/OCGs [@ocg]
/D <</BaseState/ON /Order [@ocg]>>
>>
>>}

This is a minimal OCG example.

%add the OCG to the resources of the current page object
\special{pdf: put @resources <<
/Properties <<
%this maps the name oc1'' to the OCG object
/oc1 @ocg
>>
>>}

%mark someting of the page content as optional
\special{pdf: content /OC /oc1 BDC} %optional content follows

This text is optional.

\special{pdf: content EMC} %end of optional content

\bye

-
There is a new package ocg-p.sty on CTAN, which supports xelatex. – robert.marik.cz Aug 6 '13 at 9:39

I've extended robert.marik.cz's great answer so that I have a setup command that creates multiple layers and a simple macro to use within the document.

In my style file, I do:

\newcommand{\setupOCG}{
\special{pdf:obj @ocg1 <</Type/OCG /Name (My first layer)>>}
\special{pdf:obj @ocg2 <</Type/OCG /Name (My second layer)>>}
%register it and configure its default behaviour
\special{pdf:put @catalog <<
/OCProperties <<
/OCGs [@ocg1 @ocg2]
/D <</BaseState/ON /Order [@ocg1 @ocg2]>>
>>
>>}
%add the OCG to the resources of the current page object
\makeatletter%
\special{pdf: put @resources <<
/Properties <<
%this maps the name to the OCG object
/oc1 @ocg1
/oc2 @ocg2
>>
>>}
\makeatother%
}
}

\newcommand{\myocg}[2]{%
\special{pdf: content /OC #1 BDC}#2\special{pdf: content EMC}%
}


This requires the eso-pic package. My first layer and My second layer will become the visibile names of the in the PDF reader. It's easy to add even more layers by adding @ocg3 and /oc3 etc.

In my document, I then do:

...

\setupOCG

\begin{document}

\myocg{/oc1}{I am visible on the first layer.}
\myocg{/oc2}{I am visible on the second layer.}

...


Works like a charm.

-
Thanks I extended your solution into an interface common with ocg.sty. See user.mendelu.cz/marik/latex/ocg-xetex – robert.marik.cz Jun 23 '12 at 20:51

Fortunately ocgx2 also works with XeLaTeX.

-