Skip to main content
Skip table of contents

How to set the OCG state of an existing PDF?

I need to turn off a specific layer (OCG object) in an existing 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 the ChangeOCG example (Java/.NET).

The concept is really simple. If you want to apply a change to a file you create a PdfDocument object in iText 7. As you want to change an OCG layer, you use the getLayers() 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:

JAVA
public void manipulatePdf(String src, String dest) throws IOException {
    PdfDocument pdfDoc = new PdfDocument(new PdfReader(src), new PdfWriter(dest));
    List layers = pdfDoc.getCatalog().getOCProperties(true).getLayers();
    for (PdfLayer layer : layers) {
        if ("Nested layer 1".equals(layer.getPdfObject().get(PdfName.Name).toString())) {
            layer.setOn(false);
            break;
        }
    }
    pdfDoc.close();
}

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

Click How to set the OCG state of an existing PDF? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.