DEV Community 👩‍💻👨‍💻

Alexis
Alexis

Posted on

Java - Add, Hide, or Delete Layers in PDF

PDF layer is an interactive feature for PDF documents. You can consider a layer as a separate overlaid page on which text, images or other elements can be added. A layer can have a name and the user can alter whether this layer is visible or not. This article demonstrates how to add, hide or delete layers in a PDF document by using Spire.PDF for Java.

Add Spire.Pdf.jar as dependency

If you are working on a maven project, you can include the dependency in pom.xml file using this:

<repositories>
    <repository>
        <id>com.e-iceblue</id>
        <name>e-iceblue</name>
        <url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
    </repository>
</repositories>
<dependencies>
    <dependency>
        <groupId>e-iceblue</groupId>
        <artifactId>spire.pdf</artifactId>
        <version>8.7.0</version>
    </dependency>
</dependencies>
Enter fullscreen mode Exit fullscreen mode

If you are not using maven, then you can find the required jar files from the zip file available in this location. Include all the jar files into the application lib folder to run the sample code given in this tutorial.

Add Layers to PDF

The following are the steps to create layers in a PDF document using Spire.PDF for Java.

  • Create a PdfDocument object and load an existing PDF file.
  • Create a PdfLayer object using Document.getLayers().addLayer(string layerName) method.
  • Create a canvas for the layer using PdfLayer.createGraphics() method.
  • Draw text, image or other elements on the canvas.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.graphics.*;
import com.spire.pdf.graphics.layer.PdfLayer;

import java.awt.*;
import java.awt.geom.Dimension2D;
import java.io.IOException;

public class AddLayersToPdf {

    public static void main(String[] args) throws IOException {

        //Create a PdfDocument object and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf");
        //Invoke AddLayerWatermark method to add a watermark layer
        AddLayerWatermark(pdf);
        //Invoke AddLayerHeader method to add a header layer
        AddLayerHeader(pdf);
        //Save to file
        pdf.saveToFile("output/AddLayers.pdf");
        pdf.close();
    }

    private static void AddLayerWatermark(PdfDocument doc) throws IOException {

        //Create a layer named "watermark"
        PdfLayer layer = doc.getLayers().addLayer("watermark");
        //Create a font
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", Font.PLAIN,48),true);
        //Specify watermark text
        String watermarkText = "CONFIDENTIAL";
        //Get text size
        Dimension2D fontSize = font.measureString(watermarkText);
        //Calculate two offsets
        float offset1 = (float)(fontSize.getWidth() * Math.sqrt(2) / 4);
        float offset2 = (float)(fontSize.getHeight() * Math.sqrt(2) / 4);
        //Get page count
        int pageCount = doc.getPages().getCount();
        //Declare two variables
        PdfPageBase page;
        PdfCanvas canvas;
        //Loop through the pages
        for (int i = 0; i < pageCount; i++) {

            page = doc.getPages().get(i);
            //Create a canvas from layer
            canvas = layer.createGraphics(page.getCanvas());
            canvas.translateTransform(canvas.getSize().getWidth() / 2 - offset1 - offset2, canvas.getSize().getHeight() / 2 + offset1 - offset2);
            canvas.setTransparency(0.4f);
            canvas.rotateTransform(-45);
            //Draw sting on the canvas of layer
            canvas.drawString(watermarkText, font, PdfBrushes.getDarkBlue(), 0, 0);
        }
    }

    private static void AddLayerHeader(PdfDocument doc) {

        //Create a layer named "header"
        PdfLayer layer = doc.getLayers().addLayer("header");
        //Get page size
        Dimension2D size = doc.getPages().get(0).getSize();
        //Specify the initial values of X and y
        float x = 70;
        float y = 15;
        //Get page count
        int pageCount = doc.getPages().getCount();
        //Declare two variables
        PdfPageBase page;
        PdfCanvas canvas;
        //Loop through the pages
        for (int i = 0; i < pageCount; i++) {

            //Draw an image on the layer
            PdfImage pdfImage = PdfImage.fromFile("C:\\Users\\Administrator\\Desktop\\terms.png");
            float width = pdfImage.getWidth();
            float height = pdfImage.getHeight();
            page = doc.getPages().get(i);
            canvas = layer.createGraphics(page.getCanvas());
            canvas.drawImage(pdfImage, x, y, width, height);
            //Draw a line on the layer
            PdfPen pen = new PdfPen(PdfBrushes.getDarkGray(), 2f);
            canvas.drawLine(pen, x, y + height + 5, size.getWidth() - x, y + height + 2);
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

addlayers

Set Visibility of Layers in PDF

The following are the steps to set visibility of layers in PDF using Spire.PDF for Java.

  • Create a PdfDocument object and load an existing PDF file containing laypers.
  • Get a specific layer in the PDF using PdfDocument.getLayers().get(int index) method.
  • Set the visibility of the layer using **PdfLayer.setVisibility() **method.
  • Save the document to another PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.FileFormat;
import com.spire.pdf.PdfDocument;
import com.spire.pdf.graphics.layer.PdfVisibility;

public class SetLayerVisibility {
    public static void main(String[] args) {

        //Create a PdfDocument object and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\AddLayers.pdf");

        //Set the visibility of the first layer to off
        pdf.getLayers().get(0).setVisibility(PdfVisibility.Off);

        //Save to file
        pdf.saveToFile("output/HideLayer.pdf", FileFormat.PDF);
        pdf.dispose();
    }
}
Enter fullscreen mode Exit fullscreen mode

hidelayers

Delete Layers from PDF

The following are the steps to delete a specific layer in PDF using Spire.PDF for Java.

  • Create a PdfDocument object.
  • Load a PDF file containing layers using PdfDocument.loadFromFile() method.
  • Get the layer collection from the document using PdfDocument.getLayers() method.
  • Remove a specific layer using PdfLayerCollection.removeLayer() method.
  • Save the document to another file using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;

public class DeleteLayers {

    public static void main(String[] args) {

        //Create a PdfDocument object and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\AddLayers.pdf");

        //Delete the specific layer by its name
        pdf.getLayers().removeLayer("watermark");

        //Save to file
        pdf.saveToFile("output/DeleteLayer.pdf");
        pdf.close();
    }
}
Enter fullscreen mode Exit fullscreen mode

deletelayers

Oldest comments (0)

Take a look at this:

Settings

Go to your customization settings to nudge your home feed to show content more relevant to your developer experience level. 🛠