Work with PDF Layers using Java

Aspose.PDF for Java exposes PDF layers through the Layer API on each page. You can create optional content groups, modify their behavior, and export or flatten their content when needed.

Add layers to a PDF page

  1. Create a new PDF Document.
  2. Add a Page to the document.
  3. Create and configure the required Layer objects on the page.
  4. Save the output PDF Document.
public static void addLayers(Path outputFile) {
    try (Document document = new Document()) {
        Page page = document.getPages().add();

        Layer layer = new Layer("oc1", "Red Line");
        layer.getContents().add(new SetRGBColorStroke(1, 0, 0));
        layer.getContents().add(new MoveTo(500, 700));
        layer.getContents().add(new LineTo(400, 700));
        layer.getContents().add(new Stroke());
        page.getLayers().add(layer);

        document.save(outputFile.toString());
    }
}

The full example creates three separate layers with red, green, and blue line content.

Lock a layer

  1. Open the source PDF Document.
  2. Access the target Page and get its Layer collection.
  3. Lock the target Layer.
  4. Save the updated PDF Document.
public static void lockLayer(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        Page page = document.getPages().get_Item(1);
        if (!page.getLayers().isEmpty()) {
            Layer layer = page.getLayers().getFirst();
            layer.lock();
            document.save(outputFile.toString());
        }
    }
}