Real PDF layers (optional content groups) for Typst, with the interactive features you know from LaTeX’s ocgx2 or ocg-p: clickable answers, show/hide buttons, step-by-step
reveals, radio groups, conditional content, hover hints, print/screen-only content (like with hyperref), and student / answer-key versions of the same document. This package has been made with a lot of help from AI (mostly Claude and Gemini).
Live demos & Ready-to-open PDFs
- Interactive Web Playground (html imitation) : Test every function (
gap,ocg-stepper,ocg-cycle,ocg-when,ocg-hover,ocg-canvas,ocg-switch,ocg-sort-table…) directly in your browser alongside a simulated Acrobat Layers panel and Print Preview mode (source file:index.html). - Interactive PDF Demo (
demo.pdf) : A compiled and post-processed PDF showcasing a few possibilities (open in Acrobat Reader, Foxit, or Firefox). - Examples in English (
examples.pdf) & Exemples en français (exemples.pdf) : Complete ready-to-test PDF compilations covering all features and layouts in both languages.
Typst cannot write layers on its own, so the system works in two stages:
- Typst — the functions of this package mark the content that goes into a layer and the zones that act as buttons (invisible markers made with
pdf.artifactand special links). - Post-processing — a small Python script,
ocgpp.py(French messages) orocgpp_en.py(English messages) (built on PyMuPDF), turns every marker into a real layer and every link into a PDF action. A small windows application can also be used without installing Python : OCGStudio (with english, french, german or spanish interface).
Warning : The script may break some accessibility artifacts not made by the package (kind: “watermark” or “page”) but should leave the rest unchanged (unless you use the --untag option for a lighter/non accessible pdf). Be sure to verify it if your document need to meet accessibility requirements! The central function ocg-layer also allows to change kind: “watermark” by something else but I chose “watermark” and “page” to, hopefully, not break them.
typst compile doc.typ doc.pdf
python ocgpp_en.py doc.pdf doc-ocg.pdf // ou avec ocgpp.py pour de messages en français
Open doc-ocg.pdf in Acrobat Reader (or Foxit / Firefox for most features): the buttons work and the Layers panel lists your layers.
Note. The Typst package alone only produces the markers. The interactive PDF is the output of the post-processing step. The script is available in the repository.
Requirements
- Typst ≥ 0.15.0 (
pdf.artifactwithkind: "watermark"). - Python 3 and PyMuPDF for post-processing:
pip install pymupdforOCGStudio.exe. - CeTZ and fletcher are only needed for
ocg-canvasandocg-fletcher.
Quick start
#import "@preview/millefeuille:0.1.0": ocgen
#import ocgen: *
Calculation: $12 + 7 =$ #gap[$19$]
#box(width: 8cm, height: 1.2em, ocg-layer("note", text(red)[A hidden remark.]))
#ocg-zone("note", box(inset: 4pt, stroke: 0.5pt)[Show / hide])
The dots after the = are clickable and reveal the answer; the button toggles the layer note.
Three ideas are enough to start:
- A layer is content that can be shown or hidden. It has a name; all the content with the same name is the same layer, wherever it is in the document.
- A zone is ordinary Typst content wrapped by a button function (
ocg-zone,ocg-cycle,ocg-stepper…). A click acts on one or several layers. - A layer reserves its space: when hidden, it leaves a blank (with most functions). Put it in a
boxor ablockof the size you want.
Languages
The package exposes its functions through two modules with identical contents: ocgen (English comments, error messages and default button labels) and ocgfr (the same in French). The PDF annotations (annot-note, annot-highlight, annot-attach) have the same two versions, in the annoten and annotfr modules.
#import "@preview/millefeuille:0.1.0": ocgfr, annotfr
#import ocgfr: * // or keep a namespace: #ocgfr.gap[42]
#import annotfr: *
Examples
All the examples assume the import below (see Languages) and a small helper for buttons:
#import "@preview/millefeuille:0.1.0": ocgen
#import ocgen: *
#let btn(x) = box(inset: 4pt, stroke: 0.5pt, x)
1. A worksheet with hidden answers (and overlay solutions)
gap reserves the space of a short answer (clickable dots), gapinline writes a longer answer in the flow of the line (it can wrap onto the next line), and correction-ocg / correction-flow hide a whole block (correction-flow can be split by a page break).
= Worksheet
+ $12 + 7 =$ #gap[$19$]
+ The derivative of $x^2$ is #gapinline[$2x$].
+ In a triangle, the sum of the angles is #gapinline[$180°$, whatever the shape of the triangle, provided we work in a Euclidean plane].
+ Solve $3x - 5 = 2x + 4$.
#correction-flow[
*Solution.* $3x - 2x = 4 + 5$, so $x = 9$.
Check: $3 times 9 - 5 = 22$ and $2 times 9 + 4 = 22$.
]
// The animated preview below only show the results of the first 2 lines.
Style the cue that remains (with c) when an answer is hidden with any Typst stroke, you can also change the text color (with color) and, if necessary the fill (with fill-color):
#gapinline(c: blue, stroke: (paint: red, thickness: 1pt, dash: "dashed"))[the answer]
#gapinline(stroke: none)[no line at all]
#gap(c: green, color: blue)[$x = 3$]
With overlay: true, correction-ocg renders on top of the following content in the document flow when active (without shifting the layout). Register render-correction-overlays() in page(foreground: ...):
#set page(foreground: render-correction-overlays())
Compute $integral_0^1 x^2 dif x$.
#correction-ocg(overlay: true)[
*Overlay Solution.* $integral_0^1 x^2 dif x = [x^3 / 3]_0^1 = 1/3$.
]
2. One button for the whole page/document
#ocg-zone-all(mode: "off", btn[Hide all answers])
#ocg-zone-all(mode: "on", btn[Show all answers])
#ocg-zone-all(mode: "toggle", btn[Invert])
Without names, the action targets every layer of the document (or of the current scope). Pass names: ("a", "b") to target only some of them.
3. A worked solution revealed step by step
Numbered steps, Beamer / Touying style: attach content to step numbers, without naming layers.
#ocg-steps("sol", 4)
#ocg-uncover("sol", 1)[*Factor $x^2 - 5x + 6$.*] \
#ocg-uncover("sol", 2)[1. Find two numbers with sum $-5$ and product $6$.] \
#ocg-uncover("sol", 3)[2. They are $-2$ and $-3$.] \
#ocg-uncover("sol", 4)[3. Hence $x^2 - 5x + 6 = (x - 2)(x - 3)$.]
#ocg-steps-nav("sol", prev: true)
// Animated svg in the next part
ocg-uncover shows content from a step on; ocg-only shows it at that step only; ranges such as "2-3", "2-" or ("1-1", "4-") are accepted.
4. Your own layers and a stepper
When you want to name layers yourself:
#let oline(name, body) = box(width: 12cm, height: 0.6cm, ocg-layer(name, body))
#oline("a", [① Draw the triangle.])
#oline("b", [② Draw the altitude from $C$.])
#oline("c", [③ Mark the right angle.])
#ocg-stepper(("a", "b", "c"), prev: true)
ocg-stepper provides Reset, Previous and Next step buttons. Use mode: "replace" so that each step replaces the previous one, and loop: false to stop at the last step. You can also jump directly to a given step with ocg-goto(("a", "b", "c"), 2, btn[First 2]) or build custom trigger areas with ocg-step-zone.
5. Radio groups & cycling switch (ocg-cycle, ocg-switch): a multiple-choice question
*Which of these numbers is prime?*
#ocg-cycle("q1", "q1-a", btn[A. 21]) #ocg-cycle("q1", "q1-b", btn[B. 27])
#ocg-cycle("q1", "q1-c", btn[C. 29]) #ocg-cycle("q1", "q1-d", btn[D. 33])
#let feedback(name, body) = box(width: 12cm, height: 0.6cm, ocg-layer(name, body))
#feedback("q1-a", text(red)[No: $21 = 3 times 7$.])
#feedback("q1-b", text(red)[No: $27 = 3^3$.])
#feedback("q1-c", text(green.darken(30%))[Yes! 29 is prime.])
#feedback("q1-d", text(red)[No: $33 = 3 times 11$.])
ocg-cycle shows the layer it names and explicitly hides the other members of the group; the group is created on the fly. ocg-radio(…, group: …) declares a group in advance.
When you want to cycle through several alternative contents by clicking directly on the block itself (reserving the maximum bounding box of all variants), use ocg-switch — for example for bilingual blocks or external packages like lilaq that do not yet have a dedicated wrapper:
// Bilingual EN / FR switch
#ocg-switch(
[English: Click to switch to French.],
[Français : Cliquez pour passer à l'anglais.],
)
// External package (e.g. lilaq diagram)
#import "@preview/lilaq:0.2.0" as lq
#ocg-switch(
lq.diagram(lq.plot(xs, ys-curve)),
lq.diagram(lq.plot(xs, ys-curve), lq.vlines(0)), // vertical asymptote x = 0
)
6. Conditional content
ocg-when shows content depending on the state of other layers:
#box(width: 4cm, height: 0.6cm, ocg-layer("A", text(red)[A is shown]))
#box(width: 4cm, height: 0.6cm, ocg-layer("B", text(blue)[B is shown]))
#ocg-zone("A", btn[A]) #ocg-zone("B", btn[B])
#ocg-when(ocg-all("A", ocg-not("B")))[visible if A and not B] \
#ocg-when(ocg-any("A", "B"))[visible if A or B] \
#ocg-when(ocg-not(ocg-any("A", "B")))[visible if neither]
7. Hover hints (ocg-hover, hover-word, hover-phrase)
#box(width: 12cm, height: 0.6cm, ocg-layer("hint", text(red)[Hint: think about the altitude.]))
#ocg-hover("hint", btn[Hover to see the hint])
// Reveal each word individually as the mouse hovers over it:
#hover-word[This] #hover-word[text] #hover-word[is] #hover-word[not] #hover-word[visible.]
// Or split a whole phrase automatically (mode: "hide" hides each word on hover):
#hover-phrase(mode: "hide")[Hover over each word to hide it.]
The hint is shown as long as the mouse is over the zone (mode: "hide" does the opposite). Hover only works in Acrobat and Foxit from my tests.
8. Figures with layers (CeTZ)
Elements marked with ocg-group become layers; everything else is always visible.
#import "@preview/cetz:0.5.2"
// Exemple without the marks of the animated svg
#ocg-canvas(cetz, length: 0.8cm, on: ("altitude",), {
import cetz.draw: *
line((0, 0), (5, 0), (1.5, 3), close: true, stroke: 1.2pt)
ocg-group("altitude", line((1.5, 0), (1.5, 3), stroke: (paint: blue, thickness: 1.5pt)))
ocg-group("median", line((2.5, 0), (1.5, 3), stroke: (paint: red, thickness: 1.5pt)))
ocg-group("bisector", line((2.5, -0.3), (2.5, 3), stroke: (paint: green, dash: "dashed")))
})
#ocg-cycle("lines", "altitude", btn[Altitude])
#ocg-cycle("lines", "median", btn[Median])
#ocg-cycle("lines", "bisector", btn[Bisector])
9. Figures with layers (fletcher)
#import "@preview/fletcher:0.5.8" as fletcher: node, edge
#ocg-fletcher(fletcher, spacing: (3cm, 1.4cm), node-stroke: 0.6pt,
node((0, 0), [Start], name: <a>),
node((1, 0), [Step 1], name: <b>),
edge(<a>, <b>, "->"),
..ocg-group("step2", node((2, 0), [Step 2], name: <c>), edge(<b>, <c>, "->")),
..ocg-group("bonus", node((1, 1), [Bonus], name: <d>), edge(<b>, <d>, "->", bend: 20deg)),
)
#ocg-zone("step2", btn[Step 2]) #ocg-zone("bonus", btn[Bonus])
For any other kind of figure that can be “hidden” without changing its size, use ocg-passes.
10. “Child” layers
Typst cannot write a layer inside another one, so layers are written side by side and parent: declares that a layer only appears if its parent does too. In the Layers panel they are filed under the parent.
#box(width: 100%, height: 2.3cm, {
place(top + left, ocg-layer("frame", on: true, rect(width: 7cm, height: 2.1cm, stroke: 1pt)))
place(top + left, dx: 0.5cm, dy: 0.4cm,
ocg-layer("details", parent: "frame", on: true, circle(radius: 0.6cm, fill: aqua)))
place(top + left, dx: 2.2cm, dy: 0.7cm,
ocg-layer("caption", parent: "details", on: true)[A detail of the frame])
})
#ocg-zone("frame", btn[frame]) #ocg-zone("details", btn[details])
Hide “frame” and both “details” and “caption” disappear. In figures (ocg-canvas or ocg-fletcher), use parents: (area: "altitude", formula: "area").
11. Gaps in code blocks
Inside a code block, mark the parts to hide with @@…@@ (settable):
#code-gap(```python
def square(x):
return @@x * x@@
for n in range(@@1, 6@@):
print(n, square(n))
```)
or process every code block of a section automatically, with one shared layer:
#[
#show: code-gaps.with(name: "tp1", c: blue)
```latex
\int_0^1 @@x^2@@ \, dx = @@\frac{1}{3}@@
```
]
#ocg-zone-all(mode: "toggle", names: "tp1", btn[Show / hide the gaps])
12. Printing, display and export
Three parameters, available on every layer function, control what happens when the PDF is printed, displayed or exported (values: "ifvisible" by default, "always", "never"):
// An answer that must never end up on paper
#gap(printocg: "never")[$x = 3$]
// A mark that only appears on the printed copy
#box(width: 9cm, height: 1.2em,
ocg-layer("print-mark", [Printed copy — do not write below this line], printocg: "always"))
// Visible in the interface, excluded from text/image export
#ocg-layer("logo", image("logo.png", width: 3cm), on: true, exportocg: "never")
13. Links that stand out on screen only
Like ocgcolorlinks in LaTeX: coloured and framed on screen, plain when printed.
#show: ocg-colorlinks.with(color: blue, stroke: 0.6pt + blue, radius: 2pt,
url-color: red, url-stroke: 0.6pt + red)
See #link("https://typst.app/docs")[the documentation] and #link(<conclusion>)[the conclusion].
Individual links: ocg-link("https://typst.app", stroke: 0.5pt + eastern)[typst.app]. For links that can wrap across lines, use ocg-link-inline (or inline: true in ocg-colorlinks).
14. Reusable macros with namespaces
A macro that uses the same layer names every time can be reused safely with ocg-scope:
#let exercise(title) = [
*#title*: #gap[$a + b$]
#box(width: 4cm, height: 0.6cm, ocg-layer("sol", text(red)[solution]))
#ocg-zone("sol", btn[solution])
#ocg-zone-all(mode: "on", btn[Show all (this exercise)])
]
#ocg-scope("ex1", exercise("Exercise 1"))
#ocg-scope("ex2", exercise("Exercise 2"))
Post-process with --scope explicit (or --scope page, where every page is a scope of its own) and each exercise is independent. Without the option, scopes are ignored.
15. Student and answer-key versions from one source
Layer names are what you point to on the command line:
# interactive version
python ocgpp_en.py doc.pdf doc-ocg.pdf
# student version: the answers are really removed from the file
python ocgpp_en.py doc.pdf student.pdf --strip "gap-*,correction-*,sol"
# answer-key version: the answers become normal, permanently visible content
python ocgpp_en.py doc.pdf answers.pdf --reveal "gap-*,correction-*,sol"
# fully static PDF that works in every reader
python ocgpp_en.py doc.pdf static.pdf --reveal all
# interactive, but answers never printed
python ocgpp_en.py doc.pdf print-safe.pdf --print-off "gap-*,correction-*,sol"
Only --strip guarantees that the answers are not in the file.
16. Touying slides
Content inside hide (which Touying uses for #pause, #uncover and #alternatives) loses its links and markers, but not its counter updates, so every layer after it would be shifted. One show rule fixes it:
#import "@preview/touying:0.8.1": *
#import themes.simple: *
#import "@preview/millefeuille:0.1.0": ocgen
#import ocgen: *
#show: ocg-hide-aware // before the theme
#show: simple-theme.with(aspect-ratio: "16-9")
== Exercise
$12 + 7 =$ #gap[$19$] \
#pause
$5 times 6 =$ #gap[$30$]
Each subslide is a separate page: unnamed gaps become one layer per page, named layers (name: "sol") are shared across pages.
17. Interactive sortable tables (ocg-sort-table)
Create tables whose rows can be sorted ascending (▲) or descending (▼) by clicking column headers (similar to ocgtabular in LaTeX’s ocg-p):
#ocg-sort-table(
([Function], [Category], [Layers]),
(
("gap", "Inline", "1"),
("ocg-steps", "Sequence", "N"),
("ocg-canvas", "Vector", "K"),
),
toggle-order: true,
)
Function reference (summary)
| Function | Purpose |
|---|---|
ocg-layer(name, body, on:, parent:, printocg:, viewocg:, exportocg:) |
content in the layer name |
gap(body) / gapinline(body) |
hideable answer (fixed box / flowing text) |
correction-ocg(body, overlay:) / correction-flow(body) |
hideable block (fixed / overlay foreground / breakable) |
render-correction-overlays() |
renders overlay: true corrections in page(foreground: ...) |
ocg-zone(name, body) / ocg-zone-cue(name, body) |
button toggling a layer (the latter with a line when hidden) |
ocg-zone-all(body, mode:, names:) |
button acting on several layers |
ocg-radio(..names, group:) / ocg-cycle(group, name, body) |
radio groups |
ocg-switch(..bodies) |
click directly on the block to cycle through multiple contents |
ocg-goto(names, k, body) / ocg-step-zone(names, body) / ocg-stepper(names) |
step through layers |
ocg-steps(id, n), ocg-uncover, ocg-only, ocg-steps-nav, ocg-steps-zone, ocg-steps-goto |
numbered steps |
ocg-when(expr, body), ocg-all, ocg-any, ocg-not |
conditional content |
ocg-hover(names, body) |
show layers while the mouse is over the zone |
hover-word(body) / hover-phrase(text) |
a word (or a whole sentence, word by word) revealed or hidden by hovering |
ocg-group, ocg-canvas, ocg-fletcher, ocg-passes |
layers inside figures |
ocg-link, ocg-colorlinks |
links highlighted on screen only |
ocg-link-inline(dest, body) |
the same, for links that wrap onto several lines (needs the post-processor) |
ocg-sort-table(headers, rows, toggle-order:) |
table with clickable ascending/descending column sort headers |
annot-note, annot-highlight, annot-attach |
PDF annotations: notes, text markup, attached file with a button |
ocg-scope(name, body) |
namespace for layer names |
code-gap, code-gaps |
gaps in code blocks |
ocg-hide-aware(doc) |
show rule: layers written in hidden content (hide, Touying’s #pause) are not registered |
The manual covers every parameter, the post-processor options, and the troubleshooting guide.
Reader support
| Feature | Acrobat Reader | Foxit | Firefox | Chrome, Edge, Sumatra |
|---|---|---|---|---|
| Layers, initial states | yes | yes | yes | yes |
| Buttons (click, steps, radio) | yes | yes | yes | no |
| Conditional content | yes | yes | yes | initial states only |
| Hover | yes | yes | no | no |
| Layers panel | yes | with --layers-panel |
yes | no (pdf24, Evince: yes) |
Chrome and Edge ignore buttons, so for an audience that may use them, distribute a static version (--strip all or --reveal all). When printing from Chrome or Edge, hidden layers are printed too unless they carry printocg: "never" (or the file was post-processed with --print-off). Use --strip for a guarantee. The repository contains ocg_compat_test_en.py (and ocg_compat_test.py, with French texts), which generates a test PDF to check your own readers.
Limitations
- Annotations (
annot-*) and breakable links (ocg-link-inline) are not covered yet by the compatibility test PDF: check them in your own readers. - A layer cannot contain another layer (use
parent:); layers must not be placed inpage(background: …);pdf.artifact(kind: "page")must not be used elsewhere in the document. gap,correction-ocgandocg-linkare not split across lines or pages; usegapinlineandcorrection-flowandocg-link-inlinefor text that has to flow.- The compiled PDF must carry accessibility tags (this is what makes
pdf.artifactmarkers appear). The post-processor option--untagcan remove the tags afterwards to make the file lighter (but not accessible anymore). - Usage states (
printocg,viewocg,exportocg) are applied differently by each reader;"never"is the most widely respected.
License
MIT