依赖:
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.office.free</artifactId>
<version>5.3.1</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.3</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
</dependencies>
<repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.com/nexus/content/groups/public/</url>
</repository>
</repositories>
工具方法:
import com.spire.doc.*;
import com.spire.doc.FileFormat;
import com.spire.pdf.*;
import com.spire.pdf.PdfPageBase;
import com.spire.presentation.Presentation;
import com.spire.presentation.SlideBackground;
import com.spire.presentation.collections.SlideCollection;
import com.spire.presentation.drawing.BackgroundType;
import com.spire.presentation.drawing.FillFormatType;
import com.spire.presentation.drawing.IImageData;
import com.spire.presentation.drawing.PictureFillType;
import com.spire.xls.Workbook;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.Dimension2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.List;
@Slf4j
@Component
public class WaterMarkUtils {
private static final List<String> FILE_TYPE_LIST = Arrays.asList(".jpg", ".jpeg", ".png", ".bmp", ".JPG", ".PNG", ".JPEG", ".BMP", ".docx", ".xlsx", ".pptx", ".doc", ".xls", ".ppt", ".pdf");
private static final String PDF = ".pdf";
private static final String DOC = ".doc.docx";
private static final String XLS = ".xls.xlsx";
private static final String PPT = ".ppt.pptx";
private static final String IMG = ".jpg.JPG.png.PNG.jpeg.JPEG.bmp.BMP";
public static InputStream addWaterMark(InputStream inputStream, String fileName, String waterMark) throws Exception {
log.info("添加水印文件:{}", fileName);
log.info("水印内容:{}", waterMark);
String suffix = fileName.substring((fileName.lastIndexOf(".") + 1));
if (!FILE_TYPE_LIST.contains("." + suffix)) {
return inputStream;
}
if (PDF.contains(suffix)) {
return pdfAddWaterMark(inputStream, waterMark, fileName);
}
if (DOC.contains(suffix)) {
return wordAddWaterMark(inputStream, waterMark, fileName);
}
if (XLS.contains(suffix)) {
return xlsAddWaterMark(inputStream, waterMark, fileName);
}
if (PPT.contains(suffix)) {
return pptAddWaterMark(inputStream, waterMark, fileName);
}
if (IMG.contains(suffix)) {
return imageAddWaterMark(inputStream, waterMark, suffix, fileName);
}
return null;
}
public static InputStream pdfAddWaterMark(InputStream inputStream, String waterMark, String fileName) throws Exception {
PdfDocument pdf = new PdfDocument();
pdf.loadFromStream(inputStream);
double height = pdf.getPages().get(0).getActualSize().getHeight();
double width = pdf.getPages().get(0).getActualSize().getWidth();
BufferedImage bufferedImage = ImageIO.read(new ByteArrayInputStream(createWaterMark(waterMark, (int) width, (int) height).toByteArray()));
for (int i = 0; i < pdf.getPages().getCount(); i++) {
PdfPageBase page = pdf.getPages().get(i);
page.setBackgroundImage(bufferedImage);
}
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
pdf.saveToStream(dstStream, com.spire.pdf.FileFormat.PDF);
byte[] bytes = dstStream.toByteArray();
InputStream byteStream = new ByteArrayInputStream(bytes);
dstStream.close();
System.out.println("PDF水印添加完成!");
return byteStream;
}
public static InputStream wordAddWaterMark(InputStream inputStream, String waterMark, String fileName) throws IOException, FontFormatException {
Document document = new Document();
document.loadFromStream(inputStream, FileFormat.Auto);
double height = document.getSections().get(0).getPageSetup().getPageSize().getHeight();
double width = document.getSections().get(0).getPageSetup().getPageSize().getWidth();
PictureWatermark picture = new PictureWatermark();
picture.setPicture(new ByteArrayInputStream(createWaterMark(waterMark, (int) width, (int) height).toByteArray()));
picture.isWashout(false);
document.setWatermark(picture);
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
document.saveToStream(dstStream, FileFormat.Auto);
byte[] bytes = dstStream.toByteArray();
InputStream byteStream = new ByteArrayInputStream(bytes);
dstStream.close();
System.out.println("WORD水印添加完成!");
return byteStream;
}
public static InputStream pptAddWaterMark(InputStream inputStream, String waterMark, String fileName) throws Exception {
Presentation presentation = new Presentation();
presentation.loadFromStream(inputStream, com.spire.presentation.FileFormat.AUTO);
Dimension2D size = presentation.getSlideSize().getSize();
int height = (int) size.getHeight();
int width = (int) size.getWidth();
IImageData image = presentation.getImages().append(ImageIO.read(new ByteArrayInputStream(createWaterMark(waterMark, width, height).toByteArray())));
SlideCollection slides = presentation.getSlides();
for (int i = 0; i < slides.getCount(); i++) {
SlideBackground background = presentation.getSlides().get(i).getSlideBackground();
background.setType(BackgroundType.CUSTOM);
background.getFill().setFillType(FillFormatType.PICTURE);
background.getFill().getPictureFill().setFillType(PictureFillType.TILE);
background.getFill().getPictureFill().getPicture().setEmbedImage(image);
}
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
presentation.saveToFile(dstStream, com.spire.presentation.FileFormat.AUTO);
byte[] bytes = dstStream.toByteArray();
InputStream byteStream = new ByteArrayInputStream(bytes);
dstStream.close();
System.out.println("PPT水印添加完成!");
return byteStream;
}
public static InputStream xlsAddWaterMark(InputStream inputStream, String waterMark, String fileName) throws Exception {
Workbook workbook = new Workbook();
workbook.loadFromStream(inputStream);
int count = workbook.getWorksheets().getCount();
int width = 180;
int height = 90;
for (int i = 0; i < count; i++) {
width = (int) workbook.getWorksheets().get(i).getPageSetup().getPageWidth();
height = (int) workbook.getWorksheets().get(i).getPageSetup().getPageHeight();
workbook.getWorksheets().get(i).getPageSetup().setBackgoundImage(ImageIO.read(new ByteArrayInputStream(createWaterMark(waterMark, width, height).toByteArray())));
workbook.getWorksheets().get(i).getPageSetup().setLeftHeader("&G");
}
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
workbook.saveToStream(dstStream);
byte[] bytes = dstStream.toByteArray();
InputStream byteStream = new ByteArrayInputStream(bytes);
dstStream.close();
System.out.println("EXCEL水印添加完成!");
return byteStream;
}
public static InputStream imageAddWaterMark(InputStream inputStream, String waterMark, String suffix, String fileName) throws Exception {
String[] contents = waterMark.split(",");
Image image = ImageIO.read(inputStream);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
String fontType = "FangSong";
int fontStyle = Font.BOLD;
int fontSize = 11;
Font font = new Font(fontType, fontStyle, fontSize);
font = font.deriveFont(15f);
log.info("============================font:" + font.toString() + "=================================");
Graphics2D g2d = bufImg.createGraphics();
g2d.drawImage(image, 0, 0, width, height, null);
g2d.setColor(new Color(65, 177, 221, 147));
g2d.setFont(font);
g2d.rotate(-0.5, (double) bufImg.getWidth() / 2, (double) bufImg.getHeight() / 2);
int maxLen = 0;
int maxHigh = 0;
for (int i = 0; i < contents.length; i++) {
waterMark = contents[i];
int fontlen = getWatermarkLength(waterMark, g2d);
if (fontlen >= maxLen) {
maxLen = fontlen;
}
maxHigh = maxHigh + (i + 1) * fontSize + 10;
}
int line = width * 2 / maxLen;
int co = height * 2 / maxHigh;
int yz = 0;
for (int a = 0; a < co; a++) {
int t = 0;
for (int j = 0; j < contents.length; j++) {
waterMark = contents[j];
int y = (j + 1) * fontSize + 10 + t;
int tempX = -width / 2;
int tempY = -height / 2 + y + yz;
int tempCharLen = 0;
int tempLineLen = 0;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < waterMark.length(); i++) {
char tempChar = waterMark.charAt(i);
tempCharLen = getCharLen(tempChar, g2d);
tempLineLen += tempCharLen;
if (tempLineLen >= width) {
g2d.drawString(sb.toString(), tempX, tempY);
t = t + fontSize;
sb.delete(0, sb.length());
tempY += fontSize;
tempLineLen = 0;
}
sb.append(tempChar);
}
for (int z = 0; z < line; z++) {
g2d.drawString(sb.toString(), tempX, tempY);
tempX = tempX + maxLen + XMOVE;
}
}
yz = yz + maxHigh + YMOVE;
}
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g2d.dispose();
ByteArrayOutputStream dstStream = new ByteArrayOutputStream();
ImageIO.write(bufImg, suffix, dstStream);
byte[] bytes = dstStream.toByteArray();
InputStream byteStream = new ByteArrayInputStream(bytes);
dstStream.close();
System.out.println("IMG水印添加完成!");
return byteStream;
}
private static final int XMOVE = 80;
private static final int YMOVE = 80;
public static ByteArrayOutputStream createWaterMark(String content, int width, int height) throws IOException, FontFormatException {
String[] contents = content.split(",");
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
String fontType = "FangSong";
int fontStyle = Font.BOLD;
int fontSize = 11;
Font font = new Font(fontType, fontStyle, fontSize);
font = font.deriveFont(15f);
log.info("============================font:" + font.toString() + "=================================");
Graphics2D g2d = image.createGraphics();
image = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g2d.dispose();
g2d = image.createGraphics();
g2d.setColor(new Color(65, 177, 221, 147));
g2d.setStroke(new BasicStroke(1));
g2d.setFont(font);
g2d.rotate(-0.5, (double) image.getWidth() / 2, (double) image.getHeight() / 2);
int maxLen = 0;
int maxHigh = 0;
for (int i = 0; i < contents.length; i++) {
content = contents[i];
int fontlen = getWatermarkLength(content, g2d);
if (fontlen >= maxLen) {
maxLen = fontlen;
}
maxHigh = maxHigh + (i + 1) * fontSize + 10;
}
int line = width * 2 / maxLen;
int co = height * 2 / maxHigh;
int yz = 0;
for (int a = 0; a < co; a++) {
int t = 0;
for (int j = 0; j < contents.length; j++) {
content = contents[j];
int y = (j + 1) * fontSize + 10 + t;
int tempX = -width / 2;
int tempY = -height / 2 + y + yz;
int tempCharLen = 0;
int tempLineLen = 0;
StringBuffer sb = new StringBuffer();
for (int i = 0; i < content.length(); i++) {
char tempChar = content.charAt(i);
tempCharLen = getCharLen(tempChar, g2d);
tempLineLen += tempCharLen;
if (tempLineLen >= width) {
g2d.drawString(sb.toString(), tempX, tempY);
t = t + fontSize;
sb.delete(0, sb.length());
tempY += fontSize;
tempLineLen = 0;
}
sb.append(tempChar);
}
for (int z = 0; z < line; z++) {
g2d.drawString(sb.toString(), tempX, tempY);
tempX = tempX + maxLen + XMOVE;
}
}
yz = yz + maxHigh + YMOVE;
}
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER));
g2d.dispose();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
return os;
}
public static int getCharLen(char c, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charWidth(c);
}
public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {
return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());
}
}