Add and Delete Layers in PDF in Java

Spire.PDF for Java supports adding many types of layers such as line, image, string, rectangle to PDF document as well as deleting layers from PDF document. In this article, we'll show you how to add and delete Layers in a PDF document using Spire.PDF for Java.

Add layers

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.PdfBrushes;
import com.spire.pdf.graphics.PdfCanvas;
import com.spire.pdf.graphics.PdfPen;
import com.spire.pdf.graphics.layer.PdfLayer;

import java.awt.geom.Point2D;

public class AddLayers {
    public static void main(String[] args){
        //instantiate a PdfDocument object
        PdfDocument pdf = new PdfDocument();
        //add a page
        PdfPageBase page = pdf.getPages().add();
        
        //add 3 layers to the page
        PdfLayer layer = pdf.getLayers().addLayer("red line1");
        PdfCanvas canvas1 = layer.createGraphics(pdf.getPages().get(0).getCanvas());
        canvas1.drawLine(new PdfPen(PdfBrushes.getRed(), 1), new Point2D.Float(50, 350), new Point2D.Float(200, 350));
        layer = pdf.getLayers().addLayer("blue line1");
        PdfCanvas canvas2 = layer.createGraphics(pdf.getPages().get(0).getCanvas());
        canvas2.drawLine(new PdfPen(PdfBrushes.getBlue(), 1), new Point2D.Float(50, 450), new Point2D.Float(200, 450));
        layer = pdf.getLayers().addLayer("green line1");
        PdfCanvas canvas3 = layer.createGraphics(pdf.getPages().get(0).getCanvas());
        canvas3.drawLine(new PdfPen(PdfBrushes.getGreen(), 1), new Point2D.Float(50,550), new Point2D.Float(200, 550));

        //save the resultant document
        pdf.saveToFile("output/addLayers.pdf");
        pdf.close();
    }
}

Add and Delete Layers in PDF in Java

Delete layers

import com.spire.pdf.PdfDocument;

public class DeleteLayers {
    public static void main(String[] args){
        //load a PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("output/addLayers.pdf");

        //remove a layer by name
        pdf.getLayers().removeLayer("red line1");

        //save the resultant document
        pdf.saveToFile("output/deleteLayer.pdf");
        pdf.close();
    }
}

Add and Delete Layers in PDF in Java