【spire-free添加水印】
使用spire-free添加各类文件类型水印
- 依赖:
- 工具方法:
依赖:
<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;/*** @author shorey* @date 2022年4月14日*/
@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;}/*** @param inputStream* @throws Exception*/public static InputStream pdfAddWaterMark(InputStream inputStream, String waterMark, String fileName) throws Exception {//创建PdfDocument对象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.setScaling(20);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(); // 获取Graphics2d对象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;// 填充Y轴方向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);}// 填充X轴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对象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(); // 获取Graphics2d对象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;// 填充Y轴方向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);}// 填充X轴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);}/*** 获取水印文字总长度** @paramwaterMarkContent水印的文字* @paramg* @return水印文字总长度*/public static int getWatermarkLength(String waterMarkContent, Graphics2D g) {return g.getFontMetrics(g.getFont()).charsWidth(waterMarkContent.toCharArray(), 0, waterMarkContent.length());}
}
【spire-free添加水印】相关推荐
- Java-PDF添加水印【文字或图片】,使用Spire.PDF for Java
Spire.PDF for Java 有免费版与收费版,单纯使用添加水印的功能的话,测试下来 免费版就够了,以下是相关代码与官网教程 1.官网:JAVA 添加 PDF 文本水印 (e-iceblue. ...
- Java在PDF中添加水印(文本/图片水印)效果import com.spire.pdf.*; import com.spire.pdf.graphics.*; import java.awt.*;
水印是一种十分常用的防伪手段,常用于各种文档.资料等.常见的水印,包括文字类型的水印.图片或logo类型的水印.以下Java示例,将分别使用insertTextWatermark(PdfPageBas ...
- java使用spire.office.free给office添加水印
Spire.Office for Java 是一套企业级的涵盖 E-iceblue 所有 Java组件的集合,它包括以下产品的最新版本:Spire.Doc for Java, Spire.XL ...
- 用Spire.XLS给Excel添加水印,打印水印
我的需求:给已存在的Excel添加水印,打印的时候有水印.并且可以传多组水印,可以设置水印位置,水印颜色,水印文本,水印字符大小,水印位置等等 效果图 需要引用Spire.XLS.dll插件,NPOI ...
- C# 给word文档添加水印
C# 给word文档添加水印 和PDF一样,在word中,水印也分为图片水印和文本水印,给文档添加图片水印可以使文档变得更为美观,更具有吸引力.文本水印则可以保护文档,提醒别人该文档是受版权保护的,不 ...
- 在Java生成的html页面加水印,Java在Excel中添加水印的实现(单一水印、平铺水印)...
在Excel中没有直接添加水印的功能,但依旧可以通过一定方式来实现类似水印效果.本文通过Java程序代码介绍具体实现方法.可添加单一水印效果,即水印是以单个文本字样来呈现:也可添加多个平铺水印效果,即 ...
- java ppt控件_Java版PPT操作控件Spire.Presentation v3.3.5新版来袭!支持转换GroupShape到图片...
Spire.Presentation for Java是专业的 PowerPoint API,它允许开发人员在 Java 应用程序中创建.读取.写入.转换和保存 PowerPoint 文档.作为一款独 ...
- C# Word文档添加水印
在工作中遇到个需求,需要给Word文档添加水印搞了一天才搞出来,所以在此记录一下: 重点用到了E-iceblue官网下载到的:Spire.dll using Spire.Doc; using Spir ...
- java为word添加水印,图片水印和文字水印
java为word添加水印,图片水印和文字水印 jdk1.5及以上 所需jar包:Spire.Office.jar 或 Spire.Doc.jar jar包下载:https://www.e-icebl ...
- pdf和word等文档添加水印
前言 本文介绍了java为pdf, word, excel, ppt等文档添加水印的方法, 详见官方文档 目录 前言 正文 效果图 maven依赖 java代码 总结 正文 效果图 pdf word ...
最新文章
- 在MacBook Pro 2015上安装iTerm2笔记
- linux 开机自动启动脚本方法
- 处理2D图像和纹理——显示文字
- oracle 5632,17、oracle 性能管理
- 服务器如何修复dll,Windows10系统修复KernelBase.dll错误的解决方法
- Linux环境下如何计算CPU占用率
- java web批量下载_JAVAWEB批量文件下载器
- bluetooth射频已关闭请打开bluetooth射频_【05/25 - 公告】微软已推送 Build 18362.145 (KB4497935) 版本...
- oracle+rownum(),Oracle rownum和row_number()
- oracle完全卸载重装历程
- 学习Linux第一天
- Oracle Licensing
- c++实现超声回波包络检测_学术简报新型电磁超声换能器,小尺寸板材缺陷检测效率高...
- VTK:图形基本操作进阶——表面重建技术(等值面提取)
- 如何冻结excel指定行和列
- 百度云智峰会 百度天像打造多媒体新生态
- C语言代码简化技巧(一)
- requests---timeout请求超时
- 抖音四面被拒,再战头条终获offer,在线面试指南
- 清新小学生文明礼仪PPT模板
热门文章
- 安卓手机自建 KMS 服务器
- [日文]中国語のコンピュータ用語を紹介する記事
- python写酒店管理系统_基于C# Winform的酒店管理系统
- chrome 插件清单
- 统计图表这么多?这个可视化工具太赞了~~
- 卅年史诗!地球上出现过的CPU完全收藏 - (6-9) 确立x86地位创造商业奇迹的CPU系列——80x86系列
- 常见Linux服务的默认端口整理
- 噪声:Practical Poissonian-Gaussian noise modeling and fitting for single-image raw-data
- 深度盘点:这20套可视化炫酷大屏真香啊(附源码)
- leetcode55java_Leetcode-957 N 天后的牢房 Java 详细注释