How to set the OCG state of an existing PDF?

I need to turn off a specific layer (OCG object) in an exisiting PDF that was created in Autocad and that sets the default value to "on". How can I change this to "off"? Posted on StackOverflow on

I need to turn off a specific layer (OCG object) in an exisiting PDF that was created in Autocad and that sets the default value to "on". How can I change this to "off"?

Posted on StackOverflow on May 1, 2014 by HoustonVBnovice

I've created an example that turns off the visibility of a specific layer. See ChangeOCG.

The concept is really simple. You already have a PdfReader object and you want to apply a change to a file. As documented, you create a PdfStamper object. As you want to change an OCG layer, you use the getPdfLayers() method and you select the layer you want to change by name. (In my example, the layer I want to turn off is named "Nested layer 1"). You use the setOn() method to change its status, and you're done:

PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
Map layers = stamper.getPdfLayers();
PdfLayer layer = layers.get("Nested layer 1");
layer.setOn(false);
stamper.close();
reader.close();

This is Java code. Please read it as if it were pseudo-code and adapt it to your language of choice.


Share this article

Ready to use iText?

Try our iText 7 Library and add-ons FREE for 30 days. Test your proof of concept, and see if our solution is right for you.

Get my FREE trial
Contact

Still have questions? 

We're happy to answer your questions. Reach out to us and we'll get back to you shortly.

Contact us
Stay updated

Join 11,000+ subscribers and become an iText PDF expert by staying up to date with our new products, updates, tips, technical solutions and happenings.

Subscribe Now