Alternative text (Alt Text) can help people with vision or cognitive impairments understand shapes, pictures or other graphical content. This article demonstrates how to set and get the alternative text of a shape in a PowerPoint document using Spire.Presentation for Java.

Set alternative text

import com.spire.presentation.*;
import com.spire.presentation.drawing.FillFormatType;

import java.awt.*;
import java.awt.geom.Rectangle2D;

public class SetAltText {
    public static void main(String[] args) throws Exception {
        //instantiate a Presentation object
        Presentation ppt = new Presentation();throws Exception 

        //add a shape to the first slide
        IAutoShape shape = ppt.getSlides().get(0).getShapes().appendShape(ShapeType.TRIANGLE, new Rectangle2D.Double(115, 130, 100, 100));
        shape.getFill().setFillType(FillFormatType.SOLID);
        shape.getFill().getSolidColor().setColor(Color.orange);
        shape.getShapeStyle().getLineColor().setColor(Color.white);

        //set alt text (title and description) for the shape
        shape.setAlternativeTitle("Triangle");
        shape.setAlternativeText("This is a triangle.");

        //save the resultant document
        ppt.saveToFile("Output.pptx", FileFormat.PPTX_2013);
    }
}

Set and Get Alternative Text (Alt Text) of PowerPoint Shapes in Java

Get alternative text

import com.spire.presentation.*;

public class GetAltText {
    public static void main(String[] args) throws Exception {
        //load PowerPoint document
        Presentation ppt = new Presentation();
        ppt.loadFromFile("Output.pptx");

        //get the first shape in the first slide
        IShape shape = ppt.getSlides().get(0).getShapes().get(0);

        //get the alt text (title and description) of the shape
        String altTitle = shape.getAlternativeTitle();
        String altDescription = shape.getAlternativeText();

        System.out.println("Title: " + altTitle);
        System.out.println("Description: " + altDescription);
    }
}

Set and Get Alternative Text (Alt Text) of PowerPoint Shapes in Java

Replace an Image in PowerPoint in Java

2019-09-03 06:59:07 Written by Koohji

This article demonstrates how to replace an existing image in a PowerPoint document with a new image by using Spire.Presentation for Java.

import com.spire.presentation.*;
import com.spire.presentation.drawing.IImageData;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;

public class ReplaceImage {

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

        //create a Presentation object
        Presentation presentation= new Presentation();

        //load the sample PowerPoint file
        presentation.loadFromFile("C:\\Users\\Administrator\\Desktop\\input.pptx");

        //add an image to the image collection
        String imagePath = "C:\\Users\\Administrator\\Desktop\\Microsoft-PowerPoint-logo.jpg";
        BufferedImage bufferedImage = ImageIO.read(new FileInputStream(imagePath));
        IImageData image = presentation.getImages().append(bufferedImage);

        //get the shape collection from the first slide
        ShapeCollection shapes = presentation.getSlides().get(0).getShapes();

        //loop through the shape collection
        for (int i = 0; i < shapes.getCount(); i++) {

            //determine if a shape is a picture
            if (shapes.get(i) instanceof SlidePicture) {

                //fill the shape with a new image
               ((SlidePicture) shapes.get(i)).getPictureFill().getPicture().setEmbedImage(image);
            }
        }
        
        //save to file
        presentation.saveToFile("output/ReplaceImage.pptx", FileFormat.PPTX_2013);
    }
}

Replace an Image in PowerPoint in Java

Java: Add, Hide or Delete Layers in PDF

2023-01-16 08:38:00 Written by Koohji

PDF layers are supported through the usage of Optional Content Group (OCG) objects. As its name implies, optional content refers to the content in a PDF document that can be made visible or invisible dynamically by the user of PDF viewer applications. In this article, you will learn how to programmatically add, hide or delete layers in a PDF file using Spire.PDF for Java.

Install Spire.PDF for Java

First of all, you're required to add the Spire.Pdf.jar file as a dependency in your Java program. The JAR file can be downloaded from this link. If you use Maven, you can easily import the JAR file in your application by adding the following code to your project's pom.xml file.

<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>11.11.11</version>
    </dependency>
</dependencies>

Add Layers to a PDF Document in Java

Spire.PDF for Java provides PdfDocument.getLayers().addLayer() method to add a layer in a PDF document, and you can then draw text, lines, images or shapes on the PDF layer. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF file using PdfDocument.loadFromFile() method.
  • Add a layer with specified name in the PDF using PdfDocument.getLayers().addLayer(java.lang.String name) method. Or you can also set the visibility of the layer while adding it using PdfDocument. getLayers().addLayer(java.lang.String name, PdfVisibility state) method.
  • Create a canvas for the layer using PdfLayer.createGraphics() method.
  • Draw text, image or other elements on the canvas.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
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 instance and load the sample PDF file
        PdfDocument pdf = new PdfDocument();
        pdf.loadFromFile("C:\\Users\\Administrator\\Desktop\\Sample.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("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 = 90;
        float y = 40;

        //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\\img.jpg");
            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);
        }
    }
}

Java: Add, Hide or Delete Layers in PDF

Set Visibility of Layers in a PDF Document in Java

To set the visibility of an existing layer, you'll need to get a specified layer by its index or name using PdfDocument.getLayers().get() method, and then show or hide the layer using PdfLayer.setVisibility(PdfVisibility value) method. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.loadFromFile() method.
  • Set the visibility of a specified layer using PdfDocument.getLayers().get().setVisibility() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
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 instance
        PdfDocument pdf = new PdfDocument();

        //Load a sample PDF file
        pdf.loadFromFile("AddLayers.pdf");

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

        //Save to file
        pdf.saveToFile("HideLayer.pdf", FileFormat.PDF);
        pdf.dispose();
    }
}

Java: Add, Hide or Delete Layers in PDF

Delete Layers in a PDF Document in Java

Spire.PDF for Java also allows you to remove an existing layer by its name using PdfDocument.getLayers().removeLayer(java.lang.String name) method. But kindly note that the names of PDF layers may not be unique and this method will remove all PDF layers with the same name. The detailed steps are as follows.

  • Create a PdfDocument instance.
  • Load a sample PDF document using PdfDocument.LoadFromFile() method.
  • Delete a specified layer by its name using PdfDocument.getLayers().removeLayer() method.
  • Save the result document using PdfDocument.saveToFile() method.
  • Java
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("AddLayers.pdf");

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

        //Save to file
        pdf.saveToFile("DeleteLayer.pdf");
        pdf.close();
    }
}

Java: Add, Hide or Delete Layers in PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

page 61