java word转pdf、word中关键字位置插入图片 工具类
创始人
2025-01-15 23:05:26
0

java word转pdf、word中关键字位置插入图片 工具类

1.pom依赖

 		 			org.apache.poi 			poi 			3.15 		 		 			org.apache.poi 			poi-ooxml 			3.15 		 		 			org.apache.poi 			poi-scratchpad 			3.15 		 		 			org.apache.poi 			ooxml-schemas 			1.4 		  		 			org.apache.poi 			poi-ooxml-schemas 			3.15 

2.依赖jar包

		 			com.aspose 			aspose-words 			15.8.0 			system 			${pom.basedir}/src/main/webapp/WEB-INF/lib/aspose-words-15.8.0-jdk16.jar 		 

aspose-words是需要在我们项目中引入的,并且使用时要在resouces目录下导入license.xml文件,否则生成的文件抬头会有红色的license信息。

aspose-words-15.8.0-jdk16.jar 与license.xml

3.工具类

import com.aspose.words.*; import com.aspose.words.Document;  import org.apache.poi.xwpf.usermodel.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.util.Iterator; import java.util.List; import java.util.Map;  /**  * @author dume  * @ClassName WordToPdf  * @description: TODO  * @date 2024年07月02日  * @version: 1.0  */  public class WordUtils {     private static Logger logger = LoggerFactory.getLogger(WordUtils.class);     private static final String BASE_PATH = WordUtils.class.getClassLoader().getResource("").getPath();      /**      *  Word转Pdf      * @param sourcePath 原路径      * @param targetPath 转出路径      * @return      */     public static boolean  WordToPdf(String sourcePath,String targetPath){         FileOutputStream os = null;         try{             // 验证License 若不验证则转化出的pdf文档会有水印产生         if (!getLicense()) {             logger.info("license验证失败");             return false;         }          File file = new File(targetPath);          os = new FileOutputStream(file);         FontSettings.setFontsFolder(BASE_PATH, true);         FontSettings.setDefaultFontName("STFANGSO");         Document doc = new Document(sourcePath);         doc.save(os, SaveFormat.PDF);         os.flush();         os.close();         }catch (Exception e){             e.printStackTrace();             logger.error(e.getMessage());             return false;         }finally {             if(os!=null){                try{                    os.close();                }catch (Exception e){                 }             }         }        return true;     }      /**      *  word中插入图片方法      * @param sourcePath  word路径      * @param imgPath     图片路径      * @param keyWords    关键字      * @return   插入是否成功      */     public static boolean InsertImg(String sourcePath,String imgPath,String keyWords){         try{             // 验证License 若不验证则转化出的pdf文档会有水印产生             if (!getLicense()) {                 logger.info("license验证失败");                 return false;             }             Document doc = new Document(sourcePath);             DocumentBuilder builder = new DocumentBuilder(doc);              //插入图片的方法             NodeCollection runs = doc.getChildNodes(NodeType.PARAGRAPH, true);             for (int i = 0; i < runs.getCount(); i++) {                 Node r = runs.get(i);                 String text = r.getText();                 //获取键                 if(text.contains(keyWords)){                     //锁定到当前段落即实现页面变换                     builder.moveTo(r);                     builder.insertImage(imgPath, RelativeHorizontalPosition.PAGE, 205, RelativeVerticalPosition.PAGE, 0, 20, 7, WrapType.INLINE);                     break;                 }             }             doc.save(sourcePath);         }catch (Exception e){             e.printStackTrace();             logger.error(e.getMessage());             return false;         }         return true;     }          public static boolean getLicense() {         boolean result = false;         try {             FileInputStream is = new FileInputStream (BASE_PATH+"license.xml");             License asposeLicense = new License();             asposeLicense.setLicense(is);             result = true;         } catch (Exception e) {             e.printStackTrace();         }         return result;     }       /***      * @Description :替换段落文本      * @param document docx解析对象      * @param textMap  需要替换的信息集合      * @return void      */     public static void changeText(XWPFDocument document, Map textMap) {         // 获取段落集合         Iterator iterator = document.getParagraphsIterator();         XWPFParagraph paragraph = null;         while (iterator.hasNext()) {             paragraph = iterator.next();             // 判断此段落是否需要替换             if (checkText(paragraph.getText())) {                 replaceValue(paragraph, textMap);             }         }     }      /***      * @Description :替换表格内的文字      * @param document      * @param data      * @return void      */     public static void changeTableText(XWPFDocument document, Map data) {         // 获取文件的表格         Iterator tableList = document.getTablesIterator();         XWPFTable table;         List rows;         List cells;         // 循环所有需要进行替换的文本,进行替换         while (tableList.hasNext()) {             table = tableList.next();             if (checkText(table.getText())) {                 rows = table.getRows();                 // 遍历表格,并替换模板                 for (XWPFTableRow row : rows) {                     cells = row.getTableCells();                     for (XWPFTableCell cell : cells) {                         // 判断单元格是否需要替换                         if (checkText(cell.getText())) {                             List paragraphs = cell.getParagraphs();                             for (XWPFParagraph paragraph : paragraphs) {                                 replaceValue(paragraph, data);                             }                         }                     }                 }             }         }     }      /***      * @Description :检查文本中是否包含指定的字符(此处为“$”)      * @param text      * @return boolean      */     public static boolean checkText(String text) {         boolean check = false;         if (text.contains("$")) {             check = true;         }         return check;     }      /***      * @Description :替换内容      * @param paragraph      * @param textMap      * @return void      */     public static void replaceValue(XWPFParagraph paragraph, Map textMap) {         XWPFRun run, nextRun;         String runsText;         List runs = paragraph.getRuns();         for (int i = 0; i < runs.size(); i++) {             run = runs.get(i);             runsText = run.getText(0);             if (runsText.contains("${") || (runsText.contains("$") && runs.get(i + 1).getText(0).substring(0, 1).equals("{"))) {                 while (!runsText.contains("}")) {                     nextRun = runs.get(i + 1);                     runsText = runsText + nextRun.getText(0);                     //删除该节点下的数据                     paragraph.removeRun(i + 1);                 }                 Object value = changeValue(runsText, textMap);                 //判断key在Map中是否存在                 String replaceText = runsText.replace("${", "").replace("}", "");                 if (textMap.containsKey(replaceText)) {                     run.setText(value.toString(), 0);                 } else {                     //如果匹配不到,则不修改                     run.setText(runsText, 0);                 }             }         }     }      /***      * @Description :匹配参数      * @param value      * @param textMap      * @return java.lang.Object      */     public static Object changeValue(String value, Map textMap) {         Object valu = "";         for (Map.Entry textSet : textMap.entrySet()) {             // 匹配模板与替换值 格式${key}             String key = textSet.getKey();             if (value.contains(key)) {                 valu = textSet.getValue();             }         }         return valu;     }  }  

相关内容

热门资讯

专业讨论!德扑之星真破解套路(... 专业讨论!德扑之星真破解套路(辅助挂)软件透明挂(有挂了解)-哔哩哔哩;人气非常高,ai更新快且高清...
每日必看!智星德州菠萝外挂检测... 每日必看!智星德州菠萝外挂检测(辅助挂)软件透明挂(有挂教学)-哔哩哔哩1、玩家可以在智星德州菠萝外...
透视透明挂!轰趴十三水有后台(... 轰趴十三水有后台赢率提升策略‌;透视透明挂!轰趴十三水有后台(辅助挂)软件透明挂(有挂详情)-哔哩哔...
发现玩家!德扑ai助手软件(辅... 发现玩家!德扑ai助手软件(辅助挂)透视辅助(有挂教学)-哔哩哔哩;玩家在德扑ai助手软件中需先进行...
一分钟了解!x-poker辅助... 一分钟了解!x-poker辅助软件(辅助挂)辅助透视(有挂攻略)-哔哩哔哩1、每一步都需要思考,不同...
一分钟揭秘!德州最新辅助器(辅... 一分钟揭秘!德州最新辅助器(辅助挂)透视辅助(有挂攻略)-哔哩哔哩;德州最新辅助器最新版本免费下载安...
玩家攻略推荐!德州辅助(辅助挂... 玩家攻略推荐!德州辅助(辅助挂)辅助透视(有挂了解)-哔哩哔哩是由北京得德州辅助黑科技有限公司精心研...
揭秘真相!pokernow德州... 《揭秘真相!pokernow德州(辅助挂)辅助透视(有挂介绍)-哔哩哔哩》 pokernow德州软件...
五分钟了解!德州之星辅助器(辅... 五分钟了解!德州之星辅助器(辅助挂)辅助透视(有挂透明)-哔哩哔哩1、很好的工具软件,可以解锁游戏的...
推荐一款!pokermaste... 1、推荐一款!pokermaster有外挂(辅助挂)透视辅助(有挂教学)-哔哩哔哩;详细教程。2、p...