---
title: "Java 在PPT中添加水印"
author: "Miaonly"
date: "2021-03-04T15:16:38Z"
tags: []
categories: ["编程语言"]
slug: "java-ppt"
draft: false
lastmod: "2021-03-04T15:16:38Z"
id: 2519479
url: "https://miaonly.iteye.com/blog/2519479"
---

在PPT中没有直接添加水印的功能，要实现水印效果，可以通过以下思路来实现水印效果：添加形状，在形状中添加文本，设置形状置于底层（防止文本遮盖幻灯片内容），下面通过Java程序代码示例来介绍如何实现。

**程序环境：**编译环境为IDEA; 引入free spire.presentation[.jar](https://www.e-iceblue.cn/Downloads/Free-Spire-Presentation-JAVA.html)，jdk版本1.8.0

**详细代码**

 

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

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

public class TextWatermark {
    public  static void main(String[] args) throws Exception {
        //加载示例文档
        Presentation ppt = new Presentation();
        ppt.loadFromFile("sample.pptx");

        //获取指定幻灯片
        ISlide slide = ppt.getSlides().get(0);

        //设置文本水印的宽和高
        int width= 400;
        int height= 300;

        //定义一个长方形区域
        Rectangle2D.Double rect = new Rectangle2D.Double((ppt.getSlideSize().getSize().getWidth() - width) / 2,
                (ppt.getSlideSize().getSize().getHeight() - height) / 2, width, height);

        //添加一个shape到定义区域
        IAutoShape shape = slide.getShapes().appendShape(ShapeType.RECTANGLE, rect);

        //设置shape样式
        shape.getFill().setFillType(FillFormatType.NONE);
        shape.getShapeStyle().getLineColor().setColor(Color.white);
        shape.setRotation(-45);
        shape.getLocking().setSelectionProtection(true);
        shape.getLine().setFillType(FillFormatType.NONE);
        shape.setShapeArrange(ShapeAlignmentEnum.ShapeArrange.SendToBack);

        //添加文本到shape
        shape.getTextFrame().setText("内部使用");
        PortionEx textRange = shape.getTextFrame().getTextRange();

        //设置文本水印样式
        textRange.getFill().setFillType(FillFormatType.SOLID);
        textRange.getFill().getSolidColor().setColor(new Color(211,211,211));
        textRange.setFontHeight(50);

        //保存文档
        ppt.saveToFile("TextWatermark.pptx", FileFormat.PPTX_2013);
        ppt.dispose();
    }
}
```

 

 

 

（完）