java使用BufferedImage给PPT添加背景图片水印代码,水印支持换行
时间: 2023-10-24 09:55:53 浏览: 233
Java 给图片和动图添加水印的方法
要使用Java中的BufferedImage给PPT添加背景图片水印,并支持换行,您可以使用Apache POI库来操作PPT文件。以下是一个示例代码:
```java
import org.apache.poi.sl.usermodel.*;
import org.apache.poi.xslf.usermodel.*;
import org.apache.poi.util.IOUtils;
import java.awt.*;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import javax.imageio.ImageIO;
public class AddBackgroundImageToPPT {
public static void main(String[] args) {
String pptFilePath = "path/to/presentation.pptx";
String backgroundImageFilePath = "path/to/background_image.jpg";
String watermarkText = "Your Watermark Text\nSecond Line";
try (FileInputStream inputStream = new FileInputStream(pptFilePath);
FileOutputStream outputStream = new FileOutputStream("path/to/output.pptx")) {
XMLSlideShow ppt = new XMLSlideShow(inputStream);
XSLFSlideMaster slideMaster = ppt.getSlideMasters().get(0);
// 加载背景图片
BufferedImage backgroundImage = ImageIO.read(new File(backgroundImageFilePath));
int slideWidth = (int) slideMaster.getPageSize().getWidth();
int slideHeight = (int) slideMaster.getPageSize().getHeight();
// 创建一个带有背景图片的PPT背景
XSLFBackground background = slideMaster.getBackground();
background.clear();
background.setFillType(BackgroundFill.FILL_PICTURE);
background.setPictureData(ppt.addPicture(IOUtils.toByteArray(backgroundImage), PictureData.PictureType.JPEG));
background.setAnchor(new Rectangle2D.Double(0, 0, slideWidth, slideHeight));
// 遍历每一页PPT,添加背景图片水印
for (XSLFSlide slide : ppt.getSlides()) {
XSLFSlideLayout slideLayout = slide.getSlideLayout();
XSLFTextBox textBox = slideLayout.createTextBox();
textBox.setText(watermarkText);
textBox.setAnchor(new Rectangle2D.Double(0, 0, slideWidth, slideHeight));
// 设置文本框样式
XSLFTextParagraph paragraph = textBox.getTextParagraphs().get(0);
XSLFTextRun textRun = paragraph.getTextRuns().get(0);
textRun.setFontSize(36);
textRun.setFontColor(Color.GRAY);
textRun.setBold(true);
textRun.setItalic(true);
// 将文本框添加到幻灯片
slide.getShapes().add(textBox);
}
ppt.write(outputStream);
ppt.close();
} catch (IOException | IllegalArgumentException e) {
e.printStackTrace();
}
}
}
```
请确保您已将Apache POI库的依赖项添加到您的项目中。您可以在Maven或Gradle中添加以下依赖项:
```xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.2</version>
</dependency>
```
这是一个简单的示例,通过在文本中使用换行符来支持水印的换行。您可以根据您的需求进行修改和扩展。希望对您有所帮助!
阅读全文