Skip to main content
Skip table of contents

Getting Layers from a PDF Page

Introduction

In PDF documents, layers, known technically as Optional Content Groups (OCGs), enable the separation of content within a page, allowing certain elements to be toggled visible or hidden. This feature is similar to working with layers in graphic design applications, where content can be controlled to enhance user interaction and streamline complex information display. For example, an engineering drawing might have separate layers for electrical, plumbing, and structural details, allowing viewers to isolate or combine these aspects as needed.

New Feature in iText

An enhancement for version 9 of the iText SDK introduces a straightforward method to extract and analyze these layers on a per-page basis using the getPdfLayers() (Java/.NET) function. This function delves into the PDF's annotation and resource structure to compile all associated OCGs, even those listed under the /OCProperties dictionary in the catalog.

The /OCProperties entry itself is an integral part of a PDF's catalog, providing a comprehensive list of defined content groups and their visibility settings.

By accessing both catalog-registered and unique page-specific layers, developers can efficiently manage and manipulate optional content, offering them greater flexibility in creating tailored views or extracting detailed document insights.

Code Example

Java
JAVA
    public void layersExample(String inFilePath){
        // Use PdfDocument to read the input PDF. 
        PdfDocument pdf = new PdfDocument(new PdfReader(inFilePath));
        
        //Get all layers from OCProperties
        List<PdfLayer> layersFromCatalog = pdf.getCatalog().getOCProperties(true).getLayers();
        
        //get layers specifically for page 1
        PdfPage page = pdf.getPage(1);
        Set<PdfLayer> layersFromPage = page.getPdfLayers();
        
        
        pdf.close();
    }
C#
C#
        public void LayersExample(string inFilePath){
            // Use PdfDocument to read the input PDF.
            PdfDocument pdf = new PdfDocument(new PdfReader(inFilePath));

            //Get all layers from OCProperties
           IList<PdfLayer> layersFromCatalog = pdf.GetCatalog().GetOCProperties(true).GetLayers();

            //get set of layers specifically for page 1
            PdfPage page = pdf.GetPage(1);
            var layersFromPage = page.GetPdfLayers();

            pdf.Close();
        }

JavaScript errors detected

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

If this problem persists, please contact our support.