java为word、excel、pdf、ppt、图片添加图片水印(文字水印同理)

您所在的位置:网站首页 ppt加水印转pdf java为word、excel、pdf、ppt、图片添加图片水印(文字水印同理)

java为word、excel、pdf、ppt、图片添加图片水印(文字水印同理)

2024-06-02 08:15| 来源: 网络整理| 查看: 265

使用idea开发,所需依赖如下:

 spire的下载、使用,代码中会给出网址。idea中选中右键,添加为库即可使用

e-iceblue spire.office.free 5.3.1 system ${project.basedir}/lib/spire.office.free-5.3.1.jar org.apache.pdfbox pdfbox 2.0.25 com.itextpdf itextpdf 5.5.13 org.imgscalr imgscalr-lib 4.2

还需要一张白色图片,作用在于可以设置水印图片的透明度(spire没有提供方法)

 

 

具体代码如下:

 

import cn.hutool.core.io.FileUtil; import cn.hutool.core.lang.UUID; import cn.hutool.core.util.StrUtil; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfGState; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import com.spire.doc.*; import com.spire.doc.FileFormat; import com.spire.pdf.PdfDocument; import com.spire.pdf.PdfPageBase; import com.spire.pdf.PdfPageSize; import com.spire.pdf.graphics.PdfMargins; import com.spire.presentation.Presentation; 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.ExcelVersion; import com.spire.xls.ViewMode; import com.spire.xls.Workbook; import com.spire.xls.Worksheet; import com.spire.xls.collections.WorksheetsCollection; import com.wuwei.common.config.WuWeiConfig; import java.awt.*; import java.awt.geom.Rectangle2D; import java.awt.image.BufferedImage; import java.io.*; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import lombok.extern.slf4j.Slf4j; import org.apache.pdfbox.cos.COSName; import org.apache.pdfbox.io.MemoryUsageSetting; import org.apache.pdfbox.multipdf.PDFMergerUtility; import org.apache.pdfbox.pdmodel.PDDocument; import org.apache.pdfbox.pdmodel.PDPage; import org.apache.pdfbox.pdmodel.PDPageContentStream; import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject; import org.apache.pdfbox.pdmodel.graphics.state.PDExtendedGraphicsState; import org.imgscalr.Scalr; import org.springframework.core.io.ClassPathResource; import javax.imageio.ImageIO; import static java.awt.image.BufferedImage.TYPE_INT_ARGB; /** * jar下载地址:https://repo.e-iceblue.cn/#browse/browse:maven-public:e-iceblue,下载free的; *

* 使用文档:https://www.e-iceblue.cn/tutorials.html,查看...for java的文档 *

* 为下列文件添加图片水印: *

* word; *

* excel:本质上是添加图片页眉,且在正常模式下不可见,仅在页面布局模式或打印预览模式可见;也可添加背景图片; *

* ppt:本质是添加背景图片; *

* pdf; */ @Slf4j public class WaterMarkUtils { /** * 100为原大小; * word水印缩放大小; */ public static final int SIZE = 100; /** * 当前模块resource下的静态图片->设置透明度的背景图片 */ public static final String BACKGROUND_PATH = "static/" + "white.png"; /** * 仅针对excel文件: * 水印图片透明度设置:0->1.0f,逐渐不透明; */ public static final Float ALPHA_EXCEL = 0.2f; /** * 仅针对ppt文件: * 水印图片透明度设置:0->1.0f,逐渐不透明; */ public static final Float ALPHA_PPT = 0.2f; /** * 仅针对pdf文件: * 水印图片透明度设置:0->1.0f,逐渐不透明; */ public static final Float ALPHA_PDF = 0.2f; /** * 仅针对图片: * 水印图片透明度设置:0->1.0f,逐渐不透明; */ public static final Float ALPHA_IMG = 0.4f; /** * 对水印图片进行缩放的大小设置: * 大于370->等比缩小到370; * 小于370->等比放大到370; */ public static final int TARGETWIDTH = 370; /** * 对水印图片进行缩放的大小设置: * 大于370->等比缩小到370; * 小于370->等比放大到370; */ public static final int TARGETHEIGHT = 370; /** * "doc", "docx", "xls", "xlsx", "ppt", "pptx", "pdf" */ public static final String WORD_TYPE = "word"; public static final String DOC = "doc"; public static final String DOCX = "docx"; public static final String EXCEL_TYPE = "excel"; public static final String XLS = "xls"; public static final String XLSX = "xlsx"; public static final String PPT_TYPE = "ppt"; public static final String PPT = "ppt"; public static final String PPTX = "pptx"; public static final String PDF_TYPE = "pdf"; public static final String PDF = "pdf"; public static final String IMG_TYPE = "img"; public static final String[] IMG = {"bmp", "gif", "jpg", "jpeg", "png"}; /** * 复制文件并添加水印 * * @param filePath 下载文件的绝对路径; * @param waterMarkFilePath 水印图片的路径,直接redisCache.getCacheObject(WATER_MARK_FILE_PATH))获取; * @return 1.已添加水印文件的绝对路径,再行下载,下载后需自行删除该水印文件; *

* 2.为空,代表不是添加水印的文件,按原路径下载; */ public static String addWaterMark(String filePath, String waterMarkFilePath) { String path = ""; //判断是否有水印图片 if (!new File(waterMarkFilePath).exists()) { log.info("abc-" + "水印图片不存在"); return path; } String fileType = getFileType(filePath); try { if (fileType.equals(WORD_TYPE)) { //word文件 path = wordAddWaterMark(filePath, waterMarkFilePath); } else if (fileType.equals(EXCEL_TYPE)) { //excel文件 path = excelAddWaterMark1(filePath, waterMarkFilePath); } else if (fileType.equals(PPT_TYPE)) { //PPT文件 path = pptAddWaterMark(filePath, waterMarkFilePath); } else if (fileType.equals(PDF_TYPE)) { //PDF文件 path = pdfAddWaterMark2(filePath, waterMarkFilePath); } else if (fileType.equals(IMG_TYPE)) { //图片 path = imgAddWaterMark(filePath, waterMarkFilePath); } } catch (Exception e) { log.error("文件添加水印失败" + e.getMessage()); e.printStackTrace(); } return path; } /** * 为图片添加水印 * * @param filePath * @param waterMarkFilePath * @return */ private static String imgAddWaterMark(String filePath, String waterMarkFilePath) throws IOException { //获取画布 BufferedImage read = ImageIO.read(new File(filePath)); Graphics2D graphics = read.createGraphics(); //缩放水印图片 BufferedImage image = ImageIO.read(new File(waterMarkFilePath)); int width = image.getWidth(); int height = image.getHeight(); //设置比例 float f = getScale(width, height, 0.5f); //获取缩放后的宽高 int w = (int) (width * f); int h = (int) (height * f); //缩放图片 Image i = image.getScaledInstance(w, h, Image.SCALE_SMOOTH); //设置透明度,0->1,逐渐不透明 graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, ALPHA_IMG)); //添加水印并设置在图片的右下角 graphics.drawImage(i, read.getWidth() - w, read.getHeight() - h, null); //释放资源 graphics.dispose(); //保存图片 String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) + System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true); ImageIO.write(read, filePath.substring(filePath.lastIndexOf(".") + 1), new File(downloadPath)); return downloadPath; } public static float getScale(int width, int height, float f) { if (width > 3000) { f = 0.06f; } if (width > 1000 && width < 3000) { f = 0.1f; } if (width > 300 && width < 1000) { f = 0.3f; } return f; } /** * pdf文件添加水印,使用itextpdf,速度最快 * * @param filePath * @param waterMarkFilePath * @return */ public static String pdfAddWaterMark2(String filePath, String waterMarkFilePath) throws Exception { PdfReader reader = new PdfReader(filePath); String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) + System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(downloadPath)); PdfGState gs1 = new PdfGState(); // 设置透明度 gs1.setFillOpacity(ALPHA_PDF); //得到缩放后的图片 String resizePath = resizeImage(waterMarkFilePath, TARGETWIDTH, TARGETHEIGHT); com.itextpdf.text.Image image = com.itextpdf.text.Image.getInstance(resizePath); // 获取PDF页数 int num = reader.getNumberOfPages(); com.itextpdf.text.Rectangle pagesize; float width = 0f; float height = 0f; //设置缩放后的宽高 /*float scale = 0.5f; if (image.getWidth() < 200 && image.getHeight() < 200) { scale = 2f; } float w = image.getWidth() * scale; float h = image.getHeight() * scale;*/ int x = 0; for (int i = 1; i 0) { // 判断需要生成几个pdf文件 int n = (int) Math.ceil((double) pageCount / 10); int x = 0; // 每十页生成一个pdf文件 for (int i = 1; i 图片色彩变淡,false->原色彩 picture.isWashout(true); document.setWatermark(picture); //保存文档 String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) + System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true); document.saveToFile(downloadPath, FileFormat.Docx); //删除缩放后的图片 FileUtil.del(resizePath); return downloadPath; } /** * excel文件添加水印; *

* 本质上是添加背景图片 * * @param filePath * @param waterMarkFilePath * @return */ private static String excelAddWaterMark1(String filePath, String waterMarkFilePath) throws IOException { //创建Workbook实例 Workbook workbook = new Workbook(); //加载Excel文档 workbook.loadFromFile(filePath); //得到设置了透明度的水印图片 String path = drawTransparent(waterMarkFilePath, ALPHA_EXCEL); File file = new File(path); BufferedImage bufferedImage = ImageIO.read(file); //获取工作表 WorksheetsCollection worksheets = workbook.getWorksheets(); for (int i = 0; i < worksheets.size(); i++) { //将图片设置为工作表的背景图 worksheets.get(i).getPageSetup().setBackgoundImage(bufferedImage); } //保存文档 String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) + System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true); workbook.saveToFile(downloadPath, ExcelVersion.Version2013); //删除设置了透明度的水印图片 file.delete(); return downloadPath; } /** * 绘制透明度图片 * * @param waterMarkFilePath 水印图片 * @param alpha 透明度 * @return * @throws IOException */ public static String drawTransparent(String waterMarkFilePath, float alpha) throws IOException { //读取背景图片 ClassPathResource resource = new ClassPathResource(BACKGROUND_PATH); //使用resource.getFile();会报错,打成jar后,没办法通过File的形式访问jar包里面的文件,用流读取文件可以 InputStream stream = resource.getInputStream(); // 读取背景图片 BufferedImage read = ImageIO.read(stream); Graphics2D graphics = read.createGraphics(); //读取水印图片 BufferedImage image = ImageIO.read(new File(waterMarkFilePath)); //设置透明度,0->1,逐渐不透明 graphics.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_ATOP, alpha)); //添加水印并设置居中位置 graphics.drawImage(image, (read.getWidth() - image.getWidth()) / 2, (read.getHeight() - image.getHeight()) / 2, null); //释放资源 graphics.dispose(); //保存图片 String downloadPath = WuWeiConfig.getProfile() + "/" + System.currentTimeMillis() + "_" + StrUtil.subAfter(waterMarkFilePath, "/", true); ImageIO.write(read, waterMarkFilePath.substring(waterMarkFilePath.lastIndexOf(".") + 1), new File(downloadPath)); return downloadPath; } /** * excel文件添加水印; *

* 本质上是添加图片页眉,并且水印在正常模式下不可见,仅在页面布局模式或打印预览模式可见。 * * @param filePath * @param waterMarkFilePath * @return */ private static String excelAddWaterMark(String filePath, String waterMarkFilePath) throws IOException { Workbook workbook = new Workbook(); workbook.loadFromFile(filePath); for (Worksheet sheet : (Iterable) workbook.getWorksheets()) { //添加水印 BufferedImage img = drawText(waterMarkFilePath, sheet.getPageSetup().getPageHeight(), sheet.getPageSetup().getPageWidth()); //设置页眉 sheet.getPageSetup().setCenterHeaderImage(img); sheet.getPageSetup().setCenterHeader("&G"); //设置边距 sheet.getPageSetup().setTopMargin(0); sheet.getPageSetup().setLeftMargin(0); sheet.getPageSetup().setRightMargin(0); sheet.getPageSetup().setBottomMargin(0); //将显示模式设置为页面布局模式 sheet.setViewMode(ViewMode.Layout); } //保存文档 String downloadPath = filePath.substring(0, filePath.lastIndexOf("/") + 1) + System.currentTimeMillis() + "_" + StrUtil.subAfter(filePath, "/", true); workbook.saveToFile(downloadPath, ExcelVersion.Version2010); return downloadPath; } private static BufferedImage drawText(String waterMarkFilePath, double height, double width) throws IOException { //创建画布 BufferedImage img = new BufferedImage((int) width, (int) height, TYPE_INT_ARGB); Graphics2D loGraphic = img.createGraphics(); //使用ImageIO的read方法读取图片 BufferedImage read = ImageIO.read(new File(waterMarkFilePath)); //获取缩放后的宽高 int w = (int) (read.getWidth() * 0.5); int h = (int) (read.getHeight() * 0.5); //调用缩放方法获取缩放后的图片 Image i = read.getScaledInstance(w, h, Image.SCALE_DEFAULT); //画布上添加水印图片及设置水印位置 loGraphic.drawImage(i, ((int) width - w) / 2 - 10, ((int) height - h) / 2, null); //释放资源 loGraphic.dispose(); return img; } private static String getFileType(String filePath) { int i = filePath.lastIndexOf("."); String str = filePath.substring(i + 1); switch (str) { case DOC: case DOCX: return WORD_TYPE; case XLS: case XLSX: return EXCEL_TYPE; case PPT: case PPTX: return PPT_TYPE; case PDF: return PDF_TYPE; } if (Arrays.asList(IMG).contains(str.toLowerCase())) { return IMG_TYPE; } return ""; } /** * 画透明字符串图片 * * @param width 图片宽度 * @param height 图片高度 * @param fontHeight 字体大小 * @param drawStr 文字 * @return */ public static BufferedImage drawTransparentStringPic(int width, int height, Integer fontHeight, String drawStr) { try { BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D gd = buffImg.createGraphics(); //设置透明 buffImg = gd.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); gd = buffImg.createGraphics(); //设置对线段的锯齿状边缘处理 gd.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); //设置旋转(旋转角度,旋转x轴定点,y轴定点),右斜对角 gd.rotate(Math.toRadians(-47), (width - fontHeight) / 2, height / 2); //设置字体 gd.setFont(new Font("宋体", Font.BOLD, fontHeight)); //设置颜色 gd.setColor(Color.RED); //画边框 //gd.drawRect(0, 0, width - 1, height - 1); //绘制文字 gd.drawString(drawStr, (width - fontHeight * drawStr.length()) / 2, height / 2); gd.dispose(); return buffImg; } catch (Exception e) { return null; } } /* public static void main(String[] args) { BufferedImage imgMap = drawTransparentStringPic(700, 700, 39, "奥术是否阿萨德"); File imgFile = new File("D:\\hams\\asd789888.png"); try { ImageIO.write(imgMap, "PNG", imgFile); } catch (IOException e) { e.printStackTrace(); } System.out.println("生成完成"); }*/ /** * https://www.baeldung.com/java-resize-image * 对水印图片进行缩放的大小设置: * 大于370->等比缩小到370; * 小于370->等比放大到370; * * @param waterMarkFilePath 水印图片路径 * @param targetWidth 缩放设置的宽 * @param targetHeight 缩放设置的高 * @return * @throws Exception */ public static String resizeImage(String waterMarkFilePath, int targetWidth, int targetHeight) throws Exception { BufferedImage originalImage = ImageIO.read(new File(waterMarkFilePath)); BufferedImage resize = Scalr.resize(originalImage, Scalr.Method.AUTOMATIC, Scalr.Mode.AUTOMATIC, targetWidth, targetHeight, Scalr.OP_ANTIALIAS); //保存图片 String downloadPath = WuWeiConfig.getProfile() + "/" + System.currentTimeMillis() + "_" + StrUtil.subAfter(waterMarkFilePath, "/", true); //String downloadPath = "D:\\hams\\r4.png"; ImageIO.write(resize, "png", new File(downloadPath)); return downloadPath; } }

实测可用。



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3