Hide or display layers in PDF in Java

This article will demonstrate how to hide and display Layers in a PDF document using Spire.PDF for Java.

Hide all layers:

import com.spire.pdf.*;
import com.spire.pdf.graphics.layer.*;

public class invisibleAllPdfLayers {
    public static void main(String[] args) {
        //Load the sample document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("layerSample.pdf");

        for (int i = 0; i < doc.getLayers().getCount(); i++)
        {
            //Show all the Pdf layers
            //doc.getLayers().get(i).setVisibility(PdfVisibility.On);
            //Set all the Pdf layers invisible
            doc.getLayers().get(i).setVisibility(PdfVisibility.Off);
        }

        //Save to document to file
        doc.saveToFile("output/invisibleAllPdfLayers.pdf", FileFormat.PDF);
    }
}

Hide or display layers in PDF in Java

Hide some of the PDF layers:

import com.spire.pdf.*;
import com.spire.pdf.graphics.layer.*;

public class invisibleParticularPdfLayers {
    public static void main(String[] args) {
        //Load the sample document
        PdfDocument doc = new PdfDocument();
        doc.loadFromFile("layerSample.pdf");

        //Hide the first layer by index
        doc.getLayers().get(0).setVisibility(PdfVisibility.Off);

        //Hide the layer by name with blue line1
        for (int i = 0; i < doc.getLayers().getCount(); i++)
        {
            if("blue line1".equals(doc.getLayers().get(i).getName())){
                doc.getLayers().get(i).setVisibility(PdfVisibility.Off);
            }
        }

        //Save to document to file
        doc.saveToFile("output/invisiblePaticularPdfLayers.pdf", FileFormat.PDF);
    }
}

Hide or display layers in PDF in Java