package com.casic.missiles.utils; import cn.afterturn.easypoi.word.WordExportUtil; import cn.hutool.core.lang.Assert; import com.baomidou.mybatisplus.core.toolkit.ObjectUtils; import com.spire.doc.*; import com.spire.doc.documents.*; import com.spire.doc.fields.DocPicture; import com.spire.doc.fields.TextRange; import org.apache.commons.lang3.StringUtils; import org.apache.poi.xwpf.usermodel.XWPFDocument; import javax.imageio.ImageIO; import java.awt.*; import java.awt.image.BufferedImage; import java.io.*; import java.util.Map; /** * @Author:zt * @Create:2023/3/7/9:30 * @Description:TODO Word文件操作工具类 * @Version:1.0 */ public class StampUtils { //关键字索引 (-1) private final static Integer keyWordIndex = -1; // 电子印章水平位置 private final static float horizontal = 300f; // 电子印章垂直位置 private final static float vertical = -55f; // 电子印章宽度 private final static float stampWidth = 120; // 电子印章高度 private final static float stampHeight = 120; //照片透明度设置 private final static int alpha = 150; /** * 1、自定义位置添加电子印章 * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 * * @param wordOldUrl word文件路径 * @param wordNewUrl 新word文件路径 * @param stampImgUrl 电子印章图片路径 * @param horizontal 电子印章水平位置 (当前文件推荐260f) * @param vertical 电子印章垂直位置 (当前推荐455f) * @param stampWidth 电子印章宽度(推荐120) * @param stampHeight 电子印章高度(推荐120) * @param bookmarkName 书签名,通过名称寻找书签文本所在位置 * @param newBookmarkText 替换的文本新内容 */ public void addStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, Float horizontal, Float vertical, Float stampWidth, Float stampHeight, String bookmarkName, String newBookmarkText) { // 加载文档 Document document = new Document(); document.loadFromFile(wordOldUrl); // 获取指定段落 Section section = document.getSections().get(0); // 获取段落总数 int count = section.getParagraphs().getCount(); // log.info("获取文档内容段落总数{}",count); Paragraph paragraph = section.getParagraphs().get(0); // 判断是否需要替换书签位置文本内容 if (StringUtils.isNotEmpty(bookmarkName)) { replaceBookmarkContent(document, bookmarkName, newBookmarkText); } // 添加电子印章 DocPicture docPicture = paragraph.appendPicture(stampImgUrl); // 指定电子章位置 // 水平位置 docPicture.setHorizontalPosition(horizontal); // 垂直位置 docPicture.setVerticalPosition(vertical); // 设置电子章大小 docPicture.setWidth(stampWidth); docPicture.setHeight(stampHeight); // 设置图片位于文字顶层 docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); // 保存添加电子章的Word文档 document.saveToFile(wordNewUrl); document.dispose(); // log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl); } /** * 1、根据关键词位置添加电子印章 * 2、替换书签名位置文本内容 bookmarkName传参为null,则不进行书签替换操作 * * @param wordOldUrl word文件路径 * @param wordNewUrl 新word文件路径 * @param stampImgUrl 电子印章图片路径 * @param keyWord 关键字 (自定义) * @param keyWordIndex 关键字索引 (-1) * @param horizontal 电子印章水平位置 (260f) * @param vertical 电子印章垂直位置 (-55f) * @param stampWidth 电子印章宽度 (推荐120) * @param stampHeight 电子印章高度(推荐120) */ public static void addKeyWordStamp(String wordOldUrl, String wordNewUrl, String stampImgUrl, String stampImgUrl1, String keyWord, Integer keyWordIndex, Float horizontal, Float vertical, Float stampWidth, Float stampHeight) { // 加载文档 Document document = new Document(); document.loadFromFile(wordOldUrl); //获取关键字位置 TextSelection[] textSelections = document.findAllString(keyWord, false, false); //加签章照片 if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl)) { Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); //添加公司印章 DocPicture docPicture = paragraph.appendPicture(stampImgUrl); //设置图片位于文字顶层 docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); //指定电子章位置 //水平位置 docPicture.setHorizontalPosition(horizontal); //垂直位置 docPicture.setVerticalPosition(vertical); //设置电子章大小 docPicture.setWidth(stampWidth); docPicture.setHeight(stampHeight); } //加签名照片 if (ObjectUtils.isNotEmpty(textSelections) && StringUtils.isNotEmpty(stampImgUrl1)) { Paragraph paragraph = textSelections[keyWordIndex > -1 ? 0 : textSelections.length - 1].getAsOneRange().getOwnerParagraph(); // 添加电子印章 DocPicture docPicture = paragraph.appendPicture(stampImgUrl1); //设置图片位于文字顶层 docPicture.setTextWrappingStyle(TextWrappingStyle.In_Front_Of_Text); //指定电子章位置 //水平位置 docPicture.setHorizontalPosition(horizontal); //垂直位置 docPicture.setVerticalPosition(vertical); //设置电子章大小 docPicture.setWidth(stampWidth); docPicture.setHeight(stampHeight); } //保存添加电子章的Word文档 document.saveToFile(wordNewUrl); document.dispose(); } /** * 替换书签名位置文本内容 * * @param document word文档对象 * @param bookmarkName 书签名 * @param newBookmarkText 新文本内容 */ public void replaceBookmarkContent(Document document, String bookmarkName, String newBookmarkText) { //定位到指定书签位置 BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); bookmarksNavigator.moveToBookmark(bookmarkName); //用文本内容替换原有书签位置的文本,新替换的内容与原文格式一致 bookmarksNavigator.replaceBookmarkContent(newBookmarkText, true); } /** * 替换书签名位置文本内容为图片 * * @param document word文档对象 * @param bookmarkName 书签名 * @param newImgUrl 图片地址 */ public void replaceBookmarkContentToImg(Document document, String bookmarkName, String newImgUrl) { //定位到指定书签位置 BookmarksNavigator bookmarksNavigator = new BookmarksNavigator(document); bookmarksNavigator.moveToBookmark(bookmarkName); //添加图片,替换原有书签内容 Paragraph para = new Paragraph(document); para.appendPicture(newImgUrl); TextBodyPart bodyPart = new TextBodyPart(document); bodyPart.getBodyItems().add(para); bookmarksNavigator.replaceBookmarkContent(bodyPart); } /** * 替换书签名位置文本内容为表格 * * @param document word文档对象 * @param bookmarkName 书签名 */ public void replaceBookmarkContentToTable(Document document, String bookmarkName) { //声明数组内容 String[][] data = { new String[]{"分类", "等级", "编号"}, new String[]{"A", "一级", "01A"}, new String[]{"B", "二级", "02B"}, new String[]{"C", "三级", "03C"}, }; //创建表格 Table table = new Table(document, true); table.resetCells(4, 3); for (int i = 0; i < data.length; i++) { TableRow dataRow = table.getRows().get(i); for (int j = 0; j < data[i].length; j++) { TextRange range = dataRow.getCells().get(j).addParagraph().appendText(data[i][j]); range.getOwnerParagraph().getFormat().setHorizontalAlignment(HorizontalAlignment.Center); range.getCharacterFormat().setFontName("楷体"); dataRow.getRowFormat().setHorizontalAlignment(RowAlignment.Center); dataRow.getCells().get(j).getCellFormat().setVerticalAlignment(VerticalAlignment.Middle); } } //创建TextBodyPart对象 TextBodyPart bodyPart = new TextBodyPart(document); bodyPart.getBodyItems().add(table); //定位到指定书签位置 BookmarksNavigator bookmarkNavigator = new BookmarksNavigator(document); bookmarkNavigator.moveToBookmark(bookmarkName); //使用表格替换原书签的内容 bookmarkNavigator.replaceBookmarkContent(bodyPart); } /** * 文件转流 * * @param wordNewUrl * @return */ public byte[] getBytesByFile(String wordNewUrl) { try { // byte[] bytes = Files.readAllBytes(Paths.get(wordNewUrl)); File file = new File(wordNewUrl); FileInputStream fis = new FileInputStream(file); ByteArrayOutputStream bos = new ByteArrayOutputStream(); byte[] b = new byte[1024]; int len = -1; while ((len = fis.read(b)) != -1) { bos.write(b, 0, len); } fis.close(); bos.close(); byte[] bytes = bos.toByteArray(); System.out.println("successful..."); return bytes; } catch (Exception e) { e.printStackTrace(); } return null; } /** * 流转文件 * * @param buf 流字节数组 * @param filePath 新文件路径 * @param fileName 新文件名称 */ public void byte2File(byte[] buf, String filePath, String fileName) { BufferedOutputStream bos = null; FileOutputStream fos = null; File file = null; try { File dir = new File(filePath); if (!dir.exists() && dir.isDirectory()) { dir.mkdirs(); } file = new File(filePath + File.separator + fileName); fos = new FileOutputStream(file); bos = new BufferedOutputStream(fos); bos.write(buf); } catch (Exception e) { e.printStackTrace(); } finally { if (bos != null) { try { bos.close(); } catch (IOException e) { e.printStackTrace(); } } if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } /** * word转PDF * * @param wordNewUrl word文件路径 * @param pdfNewUrl 存储新PDF文件路径 */ public static void wordToPdf(String wordNewUrl, String pdfNewUrl) { // 将新Word文档转换为PDF文件 Document document = new Document(); document.loadFromFile(wordNewUrl); document.saveToFile(pdfNewUrl, FileFormat.PDF); document.dispose(); // log.info("文档转换结束,新PDF文档地址:{}",pdfNewUrl); } /** * 图片透明背景转换 * * @param imgsrc * @param alpha * @return */ public static BufferedImage img_alpha(BufferedImage imgsrc, int alpha) { try { //创建一个包含透明度的图片,半透明效果必须要存储为png合适才行,存储为jpg,底色为黑色 BufferedImage back = new BufferedImage(imgsrc.getWidth(), imgsrc.getHeight(), BufferedImage.TYPE_INT_ARGB); int width = imgsrc.getWidth(); int height = imgsrc.getHeight(); for (int j = 0; j < height; j++) { for (int i = 0; i < width; i++) { int rgb = imgsrc.getRGB(i, j); Color color = new Color(rgb); Color newcolor = new Color(color.getRed(), color.getGreen(), color.getBlue(), alpha); back.setRGB(i, j, newcolor.getRGB()); } } return back; } catch (Exception e) { e.printStackTrace(); return null; } } //读取图片 public static BufferedImage file2img(String imgpath) { try { BufferedImage bufferedImage = ImageIO.read(new File(imgpath)); return bufferedImage; } catch (Exception e) { e.printStackTrace(); return null; } } //保存图片,extent为格式,"jpg"、"png"等 public static void img2file(BufferedImage img, String extent, String newfile) { try { ImageIO.write(img, extent, new File(newfile)); } catch (Exception e) { e.printStackTrace(); } } /** * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 * @param temDir 生成文件的目录 * @param fileName 生成文件名 * @param params 参数 */ public static String exportWord(String templatePath, String temDir, String fileName, Map<String, Object> params) { Assert.notNull(templatePath, "模板路径不能为空"); Assert.notNull(temDir, "临时文件路径不能为空"); Assert.notNull(fileName, "导出文件名不能为空"); Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式"); if (!temDir.endsWith("/")) { temDir = temDir + File.separator; } File dir = new File(temDir); if (!dir.getParentFile().exists()) { // 新建文件夹 dir.getParentFile().mkdirs(); } String tmpPath = ""; try { XWPFDocument doc = WordExportUtil.exportWord07(templatePath, params); tmpPath = temDir + fileName; FileOutputStream fos = new FileOutputStream(tmpPath); doc.write(fos); fos.flush(); fos.close(); } catch (Exception e) { e.printStackTrace(); } return tmpPath; } /** * 按照模板 填充数据生成word 只支持docx * * @param templatePath 模板文件路径 * @param temDir 生成文件的目录 * @param fileName 生成文件名 * @param params 填充参数 */ public static void generateReport(String templatePath, String temDir, String fileName, Map<String, Object> params, String stampImgUrl, String stampImgUrl1, String wordNewUrl, String keyWord, Integer keyWordIndex, Float horizontal, Float vertical, Float stampWidth, Float stampHeight, String pdfNewUrl) { //1、按照模板填充数据,并导出word String wordOldUrl = exportWord(templatePath, temDir, fileName, params); //2、照片背景透明设置 //2.1签章背景透明设置 BufferedImage bi = file2img(stampImgUrl); BufferedImage bii = img_alpha(bi, alpha); String newPngPath = stampImgUrl.substring(0, stampImgUrl.length() - 4) + "1.png"; img2file(bii, "PNG", newPngPath); //2.2签名背景透明设置 BufferedImage b = file2img(stampImgUrl1); BufferedImage b0 = img_alpha(b, alpha); String newPngPath1 = stampImgUrl.substring(0, stampImgUrl1.length() - 4) + "1.png"; img2file(b0, "PNG", newPngPath1); //3、添加签章和签名 addKeyWordStamp(wordOldUrl, wordNewUrl, newPngPath, newPngPath1, keyWord, keyWordIndex, horizontal, vertical, stampWidth, stampHeight); // 4、将新word转化为pdf文件 wordToPdf(wordNewUrl, pdfNewUrl); } public static void main(String[] args) { //文件与BufferedImage间的转换 //读取图片 BufferedImage bi = file2img("C:\\upload\\word\\sign.png"); BufferedImage bii = img_alpha(bi, alpha); //生成透明背景图片 img2file(bii, "PNG", "C:\\upload\\word\\sign1.png"); //文件与BufferedImage间的转换 //读取图片 BufferedImage b = file2img("C:\\upload\\word\\name.png"); BufferedImage b0 = img_alpha(b, alpha); //生成透明背景图片 img2file(b0, "PNG", "C:\\upload\\word\\name1.png"); // 目标文件地址 String wordOldUrl = "C:\\upload\\word\\wordExport.docx"; // 添加电子印章后文件存放地址 String wordNewUrl = "C:\\upload\\word\\tem2.docx"; //WORD转PDF存放位置 String pdfNewUrl = "C:\\upload\\word\\tem2.pdf"; //电子印章图片地址 String stampImgUrl = "C:\\upload\\word\\sign1.png"; //电子签名图片地址 String stampImgUrl1 = "C:\\upload\\word\\name1.png"; // word文档内容关键字 String keyWord = "盖章"; StampUtils addStampUtils = new StampUtils(); //获取关键字位置并加盖印章并替换书签名位置文本内容 addStampUtils.addKeyWordStamp(wordOldUrl, wordNewUrl, stampImgUrl, stampImgUrl1, keyWord, keyWordIndex, horizontal, vertical, stampWidth, stampHeight); // 将新word转化为pdf文件 addStampUtils.wordToPdf(wordNewUrl, pdfNewUrl); } }