Skip to main content
Participant
Apr 11, 2018 8:39 PM UTC
Answered

Control Layers with Javascript

Does anyone know if its possible to control (turn on/off) layers with  java script?

Currently I am using this JS:

var layers = this.getOCGs();

for(var i=0;i<this.layers.length;i++)

{

if(layers.name == "LAYER NAME")

layers.state = !(layers.state);

}

It displays how I want it too, however when I save the PDF and close it. When the PDF is reopened, The layers reset to the original state

Help please

This topic is closed to new replies. Start a new post to keep the conversation going.
Thom Parker
Thom ParkerCorrect answer
Community Expert
Apr 19, 2018 5:34 PM UTC

Hey Thom,

So I read the article but still a little lost on how to build the code.  Sorry, I don't have a strong background in javascripting.

Still looking for a way to reset the layers initial view based on a check boxed in the PDF.  >If check box is on when I save > open the file with that layer and check box on. 


As Try67 explained in the other thread, there are issues with manipulating Layers in Reader. So, if you can't change the OCG state so that it maintains its value, you save the desired state a different way and restore it on Document Open.  One easy way to do this is with "doc.viewState".

So you need hidden text field to save the Layer state, lets call it "LayerState".  Then on document close, or anytime you change Layer visibility, call this code:

this.getField("LayerState").value = eval(viewState.toSource()).ocgStates.toSource();

Next, add this code to a Document Script:

viewState = {ocgStates:eval(this.getField("LayerState").value)};

This is not as good as setting the initialState for the layer, but it works for Acrobat/Reader. Probably won't work for any other viewer.

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often

12 replies

Thom Parker
Community Expert
Community Expert
Apr 11, 2018 10:51 PM UTC

Here's an article on scripting OCG layers

It includes a sample file

Translate
Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Participant
Apr 12, 2018 6:14 PM UTC

can you reattach the link. 

Translate
Thom Parker
Community Expert
Community Expert
Apr 12, 2018 6:44 PM UTC

Opps, must have missed that.

Here it is:

https://acrobatusers.com/tutorials/create_use_layers

Translate
Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
try67
Community Expert
Community Expert
Apr 11, 2018 9:04 PM UTC

You'll need to change the layer's "initialView" property to fix that.

However, this property can't be edited in Reader, so you'll need to use a workaround, like a doc-level script that changes the states of all the layers when the file is opened, based on the value of a (hidden) text field, for example.

Translate