700字范文,内容丰富有趣,生活中的好帮手!
700字范文 > 【spire-free添加水印】

【spire-free添加水印】

时间:2023-09-29 00:55:47

相关推荐

【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-/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.ponent;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 4月14日*/@Slf4j@Componentpublic 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());}}

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。