Layers ​
PDF layers, also called Optional Content Groups (OCGs), control whether parts of page content are visible when viewing, printing, or exporting. Foxit PDF SDK for Web can read the document layer tree and control layer node visibility.
With the full UI (UIExtension), a layers panel usually displays the layer tree and toggles layer visibility. To build a custom layers panel or control layer visibility from application code, use the public layer APIs on PDFDoc.
Related APIs include:
PDFDoc.getLayerNodesJson(): Reads the document layer tree.PDFDoc.setLayerNodeVisible(): Sets whether a layer node is visible.
Read the Layer Tree ​
const pdfDoc = pdfViewer.getCurrentPDFDoc();
const layerTree = await pdfDoc.getLayerNodesJson();
console.log(layerTree);getLayerNodesJson() returns a layer tree structure. Nodes typically include id, name, visible, and children. Use this to render a custom layers panel.
Traverse Layer Nodes ​
Obtain node count and specific nodes by traversing the tree returned from getLayerNodesJson(); no separate count or lookup APIs are required.
function walkLayerNodes(node, visit) {
visit(node);
(node.children || []).forEach(child => walkLayerNodes(child, visit));
}
const layerTree = await pdfDoc.getLayerNodesJson();
walkLayerNodes(layerTree, (node) => {
console.log(node.id, node.name, node.visible);
});When a document has many layer nodes, avoid rendering an overly deep tree at once; expand nodes on demand.
Set Layer Visibility ​
PDFDoc.setLayerNodeVisible(layerId, visible) toggles layer node display state.
await pdfDoc.getLayerNodesJson();
await pdfDoc.setLayerNodeVisible(layerId, false);
await pdfViewer.redraw(true);If the page does not update immediately after a successful change, call PDFViewer.redraw(true) to re-render.
Preserve Layers When Importing Pages ​
Some page import APIs support layer-related parameters. For example, PDFDoc.insertPages() can use flags and layerName to control whether source document layers are added to the current document as non-optional tags when importing pages. See Page organizer for details.
Notes ​
- Layer visibility is document display state; whether changes are written to the file depends on the API used and your save workflow.
- Call
getLayerNodesJson()before setting layer visibility to obtain the latest layer tree. - Layer node IDs come from the layer tree; do not construct them in application code.
- With many layers, reading and rendering a custom layers panel may affect performance; show layers on demand.