Skip to main content
Participant
April 11, 2018
Answered

Control Layers with Javascript

  • April 11, 2018
  • 2 replies
  • 6841 views

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 has been closed for replies.
Correct answer Thom Parker

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.

2 replies

Thom Parker
Community Expert
Community Expert
April 11, 2018

Here's an article on scripting OCG layers

It includes a sample file

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
Participant
April 12, 2018

can you reattach the link. 

Thom Parker
Community Expert
Community Expert
April 12, 2018

Opps, must have missed that.

Here it is:

https://acrobatusers.com/tutorials/create_use_layers

Thom Parker - Software Developer at PDFScriptingUse the Acrobat JavaScript Reference early and often
try67
Community Expert
Community Expert
April 11, 2018

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.