I’m new to this package, and I’ve figured out how to toggle layers on/off:
import pymupdfd
doc = pymupdf.open("file.pdf")
ogcs = doc.get_ocgs()
lyr_xref = ogcs[0]
doc.set_layer(-1, on=[lyr_xref], basestate="OFF") # turn off all but the first layer
But how do I delete them, or copy a specific layer to a new file?
I also posted an answer in the repo’s Discussions, so just a few comments here:
What usually is called a “layer” actually refers to the PDF object type OCG - Optional Content Group (not the most fortunate naming in my mind).
These are small objects - in the range of 20 - 30 bytes - that have a handful of attributes, of which one, the “name” is only required.
An OCG is a boolean value really: it can be ON or OFF.
The PDF specification also has the object type OCMD (Optional Content Membership Dictionary). This can define arbitrary boolean expressions of multiple OCGs - in principle supporting the full power of boolean algebra - including “AND”, “OR”, “NOT” and brackets.
Whether or not some PDF object is visible can be made dependent on the value of an OCG or an OCMD.
This dependency is implemented by referring to the XREF of some OCG / OCMD.
For this very reason, an OCG should never be physically deleted as a PDF object: this could make the PDF as a whole unusable.
However: A PDF takes note of an OCG if and only if the OCG’s XREF is present in the catalog’s array /OCProperties/OCGs. Removing an OCG entry from there is the only possible approximation of “deleting a layer”.
So the term “layer” in a PDF is in no way comparable with a layer of a cake: you cannot take it out and get a smaller cake … or reuse it to enrich another cake with a layer of strawberries .
The initial idea of our user @p-vdp was correct - and the only possible one:
If we need a new PDF that shows the page content related to only one of the many “layers” (= OCGs), then setting the wanted OCG to ON and all other OCGs to OFFpermanently is the only viable way.
Deleting / disabling unwanted OCGs does the opposite: PDF objects referring to them would now always be visible!