Layers have been part of the PDF specifications since version 1.5. They are formally known as Optional Content Groups (OCG) and are in the PDF specification described as:

Optional content (PDF 1.5) refers to sections of content in a PDF document that can be selectively viewed or hidden by document authors or consumers. This capability is useful in items such as CAD drawings, layered artwork, maps, and multi-language documents.

Below are two screenshots from a PDF that contains layers. In the first screenshot all layers are visible; in the second two of the layers have been hidden.

(The above example is based on an example contributed by Gloria Faccanoni)

As far as I know, only Acrobat (Reader) fully supports OCG. The latest version of the Foxit reader supports showing and hiding layers using javascript, but currently it does not have a layer panel where you can enable and disable layers manually.

The ocg.sty package

I usually use Beamer and PDFs for presentations. With packages like animate and movie15 I can include animations and interactive content in my presentations. So what about layers? Can we create documents with layers using PDFLaTeX? The answer is yes. You can either use the AcroTeX eDucation Bundle(requires Acrobat Professional), or the ocg.sty package.

In a thread on comp.text.tex Martin Heller made me aware of ocg.sty, a package written by Michael Ritzert. At the moment it is only available in the comp.text.tex archives, but it is a useful package and deserves some attention. To make it more accessible I have made a copy of ocg.sty available from TeXample.net:

The package’s interface is simple. Each OCG layer is wrapped in an ocg environment:

\begin{ocg}{layer name}{layer id}{initial visibility}
...
\end{ocg}

The parameters are:

  • layer name. A descriptive layer name. In Acrobat this name will be used in the layers panel.
  • layer id. A unique id used internally by ocg.sty. You can use numbers and letters. Avoid spaces and other special characters.
  • initial visibility. If set to 1 the layer will be visible when the document is opened. If set to 0 it will be hidden.

A few examples:

\begin{ocg}{Background}{1}{1} ...
\begin{ocg}{Content}{content}{1} ...
\begin{ocg}{Annotations}{2}{1} ...

If two or more layers share the same name and id they will all belong to the same layer.

Note: Two compilations are necessary to insert layers in the final PDF.

Using layers

Now that I have described the package’s interface it is time to show a few examples. The first example is not very exciting:

\documentclass{article}
\usepackage{ocg}
\begin{document}
\begin{ocg}{Para A}{1}{1}
This is paragraph A.
\end{ocg}

\begin{ocg}{Para B}{2}{1}
This is paragraph B with some math in it: $a^2+b^2=c^1$.
\end{ocg}

A third paragraph that is always visible.
\end{document}

ex1.pdf:

Things become more interesting if you use ocg.sty inside a tikzpicture environment. Here is a modified example from the TikZ and PGF manual:

\documentclass{article}
\usepackage{ocg}
\usepackage{tikz}
\usetikzlibrary{arrows,automata}
\begin{document}

\begin{tikzpicture}[shorten >=1pt,node distance=2cm,auto,
                    every state/.style={fill=green!20}]
\begin{ocg}{grid}{grid}{1}
    \draw[black!20] (0,-2) grid (3,2);
\end{ocg}
\begin{ocg}{states}{2}{1}
    \node[state] (q_0) {$q_0$};
    \node[state] (q_1) [above right of=q_0] {$q_1$};
    \node[state] (q_2) [below right of=q_0] {$q_2$};
    \node[state] (q_3) [below right of=q_1] {$q_3$};
\end{ocg}
\begin{ocg}{edges}{3}{1}
    \path[->] (q_0) edge node {0} (q_1)
                    edge node [swap] {1} (q_2)
              (q_1) edge node {1} (q_3)
                    edge [loop above] node {0} ()
              (q_2) edge node [swap] {0} (q_3)
                    edge [loop below] node {1} ();
\end{ocg}
% Add some labels to the grid layer
\begin{ocg}{grid}{grid}{1}
    \path (0,-2) node {(0,-2)}
          (3,2) node {(3,2)};
\end{ocg}
\end{tikzpicture}

\end{document}

ex2.pdf:

The above example is hopefully self-explaining. Note that the content on the grid layer is defined in two separate ocg environments. TikZ also has a layer concept, but TikZ layers have nothing to do with OCG layers. They are, however, a natural place to insert OCG layers.

Interacting with layers

The layer panel is not the only way you can interact with layers. They are also accessible through the javascript API. For background information read these excellent tutorials:

Passing javascript to PdfTeX is possible with some hackery. The example below shows how to insert hyperlinks that toggles layer visibility on and off. The code is based on a snippet written by Alexander Grahn. You can see the final results in the layerlinksbeamer.pdf file.

Update: Added a “call out” layer and changed documentclass to Beamer.

\documentclass{beamer}

\usepackage{tikz}
\usepackage{ocg}
\usetikzlibrary{shadows}
\usepackage{hyperref}

%----------------------------------------------------------------%

% Command to toggle a layer on/off
\newcommand{\ToggleLayer}[2]{%
  % #1: layer name,
  % #2: link text
  \leavevmode%
  \pdfstartlink user {
    /Subtype /Link
    /Border [0 0 0]%
    /A <<
      /S/JavaScript
      /JS (
         var aOCGs = this.getOCGs();
         for(var i=0; aOCGs && i<aOCGs.length;i++)
         {
         if(aOCGs[i].name == "#1")
         aOCGs[i].state = !aOCGs[i].state;
         }
      )
    >>
  }#2%
  \pdfendlink%
}

% Show all layers on the current page
\newcommand{\ShowAllLayers}[1]{%
  % #1: layer name,
  % #2: link text
  \leavevmode%
  \pdfstartlink user {
    /Subtype /Link
    /Border [0 0 0]%
    /A <<
      /S/JavaScript
      /JS (
         var aOCGs = this.getOCGs();
         for(var i=0; aOCGs && i<aOCGs.length;i++)
         {
         aOCGs[i].state = true;
         }
      )
    >>
  }#1%
  \pdfendlink%
}

% Hide all layers on the current page
\newcommand{\HideAllLayers}[1]{%
  % #1: link text,
  \leavevmode%
  \pdfstartlink user {
    /Subtype /Link
    /Border [0 0 0]%
    /A <<
      /S/JavaScript
      /JS (
         var aOCGs = this.getOCGs();
         for(var i=0; aOCGs && i<aOCGs.length;i++)
         {
         aOCGs[i].state = false;
         }
      )
    >>
  }#1%
  \pdfendlink%
}

\begin{document}
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
\begin{frame}
\centering

% Example by Dominique W├╝rtz
% http://www.texample.net/tikz/examples/intersecting-rings/

% Define the rings. Store them in macros to make things
% more flexible.
\def\ringa{(-1,0) circle (2) (-1,0) circle (3)}
\def\ringb{(1,0) circle (2) (1,0) circle (3)}

\begin{tikzpicture}[note/.style={draw,fill=yellow, drop shadow}]
    % First we fill the intersecting area
    % The \clip command does not allow options, therefore
    % we have to use a scope to set the even odd rule.
    \begin{scope}[even odd rule]
        \begin{ocg}{Intersection}{intersection}{1}
        % Define a clipping path. All paths outside ringa will
        % be cut because the even odd rule is set.
        \clip \ringa;
        % Fill ringb. Since the even odd rule is set, only the
        % ring will be filled, not the hole in the middle.
        \fill[fill=orange] \ringb;
        \end{ocg}
    \end{scope}
    % Then we draw the rings
    \begin{ocg}{Ring A}{ringa}{1}
    \draw \ringa;
    \end{ocg}
    \begin{ocg}{Ring B}{ringb}{1}
    \draw \ringb;
    \end{ocg}
    \begin{ocg}{callout}{callout}{0}
        \draw (0,2) -- ++(-20:3)
            node[note,text width=3cm] {{This is a call out box.
               Click the call out link to close}};
    \end{ocg}
    % Insert a link to toggle the call out.
    \node[blue] {\ToggleLayer{callout}{Toggle call out}};
\end{tikzpicture}

% Insert links to toggle layer visibility
Toggle: \ToggleLayer{Ring A}{ring A} |
\ToggleLayer{Ring B}{ring B} |
\ToggleLayer{Intersection}{Intersection} |
\ShowAllLayers{Show all layers} |
\HideAllLayers{Hide all layers}
\end{frame}
\end{document}

Summary

So why should we use layers? If you use Beamer you can usually achieve similar results using overlays. Two disadvantages of overlays is that they increase the size of PDF, and sometimes care must be taken to ensure that the content does not “jump around” from frame to frame. Layers do not have these problems. However, the limited support for layers in many PDF viewers may be a problem for some users.

For presentations it is most common to use the PDF viewer’s full screen mode. Acrobat’s layer panel will in that case not be visible. It may therefore be necessary to insert javascript snippets to control the layer visibility. Nevertheless, layers are a useful tool to have in your presentation toolbox. They are also useful for traditional documents, especially when it comes to presenting complex diagrams and plots. Many times I have wished that I could hide elements like grids and annotations in a figure because they obscure the real data.

Have fun experimenting with ocg.sty. I hope that it will find its way to CTAN some time.

Comments

  • #1 Kjell Magne Fauske, November 5, 2008 at 9:35 a.m.

    Updated the layerlinks example with a call out layer.

  • #2 luoyi, February 5, 2009 at 4:20 p.m.

    can we use keyboard instead of mouse click to control the layer's visible ?

  • #3 Kjell Magne Fauske, February 5, 2009 at 8:46 p.m.

    @luoyi. You probably can, but unfortunately I'm not familiar enough with Acrobat JavaScript to know how. You can probably find the necessary information at Acrobat Developer Center.

  • #4 Manuel, September 15, 2009 at 9:22 a.m.

    Is there any way to do this with \includegraphics imported pictures? Like put several on top of each other?

  • #5 Martin Heller, September 15, 2009 at 11:10 p.m.

    Alexander Grahn has provided a very nice example on how the animate.sty package can be used to create layers at the pdfTeX mailinglist: http://tug.org/pipermail/pdftex/2009-September/008092.html

  • #6 Chris Wilson, May 7, 2013 at 12:21 p.m.

    Hi Kjell,

    I tried to use OCG with Pandoc, xetex and Beamer to put speakers' notes on a switchable layer. I tried to load the ocg.sty file like this in my Pandoc template:

    \RequirePackage{templates/ocg}
    \usepackage{templates/ocg}
    

    That works (and fails if the file doesn't exist at that path) but I still can't use OCG in my slides. I tried this:

    \begin{document}
    \begin{frame}{test}
    \begin{ocg}{Speaker Notes}{notes}{1}
    Say "hello" now.
    \end{ocg}
    hello
    \note{say "hello" now}
    \end{frame}
    \end{document}
    

    And I get this error from pandoc (from Xetex I think):

    pandoc: Error producing PDF from TeX source.
    ! LaTeX Error: Environment ocg undefined.
    

    Any ideas?

    Cheers, Chris.

Adding comments is currently not enabled.