pCOS Cookbook

cookbook

special/layers

Create a list of all layers contained in a PDF document and show their names.

Download Java Code  Show Output  Show Input (layernames.pdf) 

/*
 * Create a list of all layers contained in a PDF document and show their names.
 * <p>
 * This topic will catch all layers (even those which are not presented in
 * Acrobat's user interface), but it will not reflect the default layer
 * hierarchy, and will not show text labels which can separate layer names.
 * <p>
 * Required software: pCOS interface 3 (PDFlib+PDI/PPS 7.x, TET 2.2,
 * PLOP 3.x) <br>
 * Required data: PDF document
 */
package com.pdflib.cookbook.pcos.special;

import com.pdflib.IpCOS;
import com.pdflib.cookbook.pcos.pcos_cookbook_example;

public class layers extends pcos_cookbook_example {

    /* This is where the data files are. Adjust as necessary. */
    private final static String SEARCH_PATH = "../input";

    private final static String KEY = "/Root/OCProperties";

    public void example_code(IpCOS p, int doc) throws Exception {

        System.out.println("File name: " + p.pcos_get_string(doc, "filename"));

        String objtype = p.pcos_get_string(doc, "type:" + KEY);
        if (!objtype.equals("dict")) {
            System.out.println("No layers found\n");
            return;
        }

        objtype = p.pcos_get_string(doc, "type:" + KEY + "/OCGs");
        if (!objtype.equals("array")) {
            System.out.println("PDF error in OCProperties dict");
            return;
        }

        int numentries = (int) p
            .pcos_get_number(doc, "length:" + KEY + "/OCGs");

        for (int i = 0; i < numentries; i++) {
            String key = KEY + "/OCGs[" + i + "]/Name";

            objtype = p.pcos_get_string(doc, "type:" + key);

            if (!objtype.equals("null")) {
                System.out.println(p.pcos_get_string(doc, key));
            }
        }
    }

    public layers(String[] argv, String readable_name, String search_path) {
        super(argv, readable_name, search_path);
    }

    public static void main(String argv[]) {
        layers example = new layers(argv, "Layer names", SEARCH_PATH);
        example.execute();
    }
}