DEV Community

E-iceblue Product Family
E-iceblue Product Family

Posted on

Add and Delete Layers in PDF in Java

PDF layers allow users to selectively hide or show the content appearing on them in PDF documents. In this article, we will introduce how to add layers to a PDF document, draw content to the layers and delete a specific layer in Java using Free Spire.PDF for Java library.

Before getting started, please download Free Spire.PDF for Java package through this link, unzip the package and then import Spire.Pdf.jar from lib folder into our application.

Add layers to a PDF

In the below example, we will learn how to add two layers to a PDF document and draw the content of a PDF page and an image to the layers.

import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.graphics.layer.PdfLayer;

import java.awt.*;
import java.awt.geom.Point2D;

public class AddLayers {
    public static void main(String[] args) throws Exception {

       //Create a new PDF document
        PdfDocument target = new PdfDocument();
        //Add a page
        PdfPageBase page = target.getPages().add();

        //Load an existing PDF document
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("Instruction.pdf");
        //Create a template of the first page in the PDF
        PdfTemplate template = pdf.getPages().get(0).createTemplate();

        //Add a layer to the new created PDF
        PdfLayer layer1 = target.getLayers().addLayer("Layer 1");
        PdfCanvas canvas1 = layer1.createGraphics(page.getCanvas());
        //Draw the template to the layer
        canvas1.drawTemplate(template, new Point2D.Float(20,50), PdfPageSize.A4);

        //Add a layer to the new created PDF
        PdfLayer layer2 = target.getLayers().addLayer("Layer 2");
        PdfCanvas canvas2 = layer2.createGraphics(page.getCanvas());
        //Draw an image to the layer
        canvas2.drawImage(PdfImage.fromFile("Hydrangeas.jpg"), new Point2D.Float(330,125), new Dimension(200, 130));

        //Save the resultant document
        target.saveToFile("result.pdf");
    }
}

Delete a specific layer

The below example shows how to remove a specific layer along with its content from a PDF document.

import com.spire.pdf.PdfDocument;

public class DeleteLayer {
    public static void main(String[] args){
        //Load the PDF
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("result.pdf");

        //Remove the layer named "Layer 1" and its content from the PDF
        pdf.getLayers().removeLayer("Layer 1", true);

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

Top comments (0)