java word转pdf、word中关键字位置插入图片 工具类
java word转pdf、word中关键字位置插入图片 工具类
1.pom依赖
<dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-scratchpad</artifactId><version>3.15</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.4</version></dependency><dependency><groupId>org.apache.poi</groupId><artifactId>poi-ooxml-schemas</artifactId><version>3.15</version>
2.依赖jar包
<dependency><groupId>com.aspose</groupId><artifactId>aspose-words</artifactId><version>15.8.0</version><scope>system</scope><systemPath>${pom.basedir}/src/main/webapp/WEB-INF/lib/aspose-words-15.8.0-jdk16.jar</systemPath></dependency>
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<String, Object> textMap) {// 获取段落集合Iterator<XWPFParagraph> 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<String, Object> data) {// 获取文件的表格Iterator<XWPFTable> tableList = document.getTablesIterator();XWPFTable table;List<XWPFTableRow> rows;List<XWPFTableCell> 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<XWPFParagraph> 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<String, Object> textMap) {XWPFRun run, nextRun;String runsText;List<XWPFRun> 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<String, Object> textMap) {Object valu = "";for (Map.Entry<String, Object> textSet : textMap.entrySet()) {// 匹配模板与替换值 格式${key}String key = textSet.getKey();if (value.contains(key)) {valu = textSet.getValue();}}return valu;}}相关文章:
java word转pdf、word中关键字位置插入图片 工具类
java word转pdf、word中关键字位置插入图片 工具类 1.pom依赖 <dependency><groupId>org.apache.poi</groupId><artifactId>poi</artifactId><version>3.15</version></dependency><dependency><groupId>org.apa…...
jail内部ubuntu apt升级失败问题解决
在FreeBSD jail 里安装启动Ubuntu jammy系统,每次装好执行jexec ubjammy sh进入Ubuntu系统后,执行apt update报错。 这个问题困惑了好久,突然有一天仔细去看报错信息,查看了(man 5 apt.conf) ,才搞定问题。简单来说就是…...
迎接AI新时代:GPT-5的技术飞跃与未来展望
引言 随着人工智能技术的迅猛发展,大语言模型在过去几年取得了显著进步。OpenAI最新的声明表明,GPT-5将在一年半后发布,并将带来从高中生智力水平到博士生智力水平的飞跃。这一突破引起了科技界和公众的广泛关注。本文将从技术突破预测、智能…...
Snap Video:用于文本到视频合成的扩展时空变换器
图像生成模型的质量和多功能性的显著提升,研究界开始将其应用于视频生成领域。但是视频内容高度冗余,直接将图像模型技术应用于视频生成可能会降低运动的保真度和视觉质量,并影响可扩展性。来自 Snap 的研究团队及其合作者提出了 "Snap …...
实验8 视图创建与管理实验
一、实验目的 理解视图的概念。掌握创建、更改、删除视图的方法。掌握使用视图来访问数据的方法。 二、实验内容 在job数据库中,有聘任人员信息表:Work_lnfo表,其表结构如下表所示: 其中表中练习数据如下: 1.‘张明…...
C++ 开源库
1 PDFium PDFium 是一个开源的 PDF 渲染和处理库,最初由 Foxit Software 开发,并于2014年捐赠给了 Chromium 项目。PDFium 旨在为各种应用程序提供高效、灵活的 PDF 渲染和操作功能。 2 代码地址 https://github.com/chromium/pdfium 主要特性 渲染…...
LabVIEW滤波器性能研究
为了研究滤波器的滤波性能,采用LabVIEW设计了一套滤波器性能研究系统。该系统通过LabVIEW中的波形生成函数,输出幅值及频率可调的正弦波和白噪声两种信号,并将白噪声与正弦波叠加,再通过滤波器输出纯净的正弦波信号。系统通过FFT&…...
『C++成长记』vector模拟实现
🔥博客主页:小王又困了 📚系列专栏:C 🌟人之为学,不日近则日退 ❤️感谢大家点赞👍收藏⭐评论✍️ 目录 一、存储结构 二、默认成员函数 📒2.1构造函数 📒2.2拷贝…...
【Mac】Charles for Mac(HTTP协议抓包工具)及同类型软件介绍
软件介绍 Charles for Mac 是一款功能强大的网络调试工具,主要用于HTTP代理/HTTP监视器。以下是它的一些主要特点和功能: 1.HTTP代理:Charles 可以作为HTTP代理服务器,允许你查看客户端和服务器之间的所有HTTP和SSL/TLS通信。 …...
LVS集群及其它的NAT模式
1.lvs集群作用:是linux的内核层面实现负载均衡的软件;将多个后端服务器组成一个高可用、高性能的服务器的集群,通过负载均衡的算法将客户端的请求分发到后端的服务器上,通过这种方式实现高可用和负载均衡。 2.集群和分布式&#…...
【RNN练习】天气预测
🍨 本文为🔗365天深度学习训练营 中的学习记录博客🍖 原作者:K同学啊 一、环境及数据准备 1. 我的环境 语言环境:Python3.11.9编译器:Jupyter notebook深度学习框架:TensorFlow 2.15.0 2. 导…...
prompt第四讲-fewshot
文章目录 前提回顾FewShotPromptTemplateforamt格式化 前提回顾 前面已经实现了一个翻译助手了[prompt第三讲-PromptTemplate],prompt模板设计中,有说明、案例、和实际的问题 # -*- coding: utf-8 -*- """ Time : 2024/7/8 …...
StarRocks分布式元数据源码解析
1. 支持元数据表 https://github.com/StarRocks/starrocks/pull/44276/files 核心类:LogicalIcebergMetadataTable,Iceberg元数据表,将元数据的各个字段做成表的列,后期可以通过sql操作从元数据获取字段,这个表的组成…...
阅读笔记——《Fuzz4All: Universal Fuzzing with Large Language Models》
【参考文献】Xia C S, Paltenghi M, Le Tian J, et al. Fuzz4all: Universal fuzzing with large language models[C]//Proceedings of the IEEE/ACM 46th International Conference on Software Engineering. 2024: 1-13.【注】本文仅为作者个人学习笔记,如有冒犯&…...
【C++】使用gtest做单元测试框架写单元测试
本文主要介绍在将gtest框架引入到项目里过程中遇到的问题。 我的需求如下: 用CMake构建项目。我要写一些测试程序验证某些功能,但是不想每一个测试都新建一个main函数。 因为新建一个main函数就要在CMakeList.txt里增加一个project,非常不方便。 于是我搜了下,C++里有没…...
Java类与对象
类是对现实世界中实体的抽象,是对一类事物的描述。 类的属性位置在类的内部、方法的外部。 类的属性描述一个类的一些可描述的特性,比如人的姓名、年龄、性别等。 [public] [abstract|final] class 类名 [extends父类] [implements接口列表] { 属性声…...
xlwings 链接到 指定sheet 从别的 excel 复制 sheet 到指定 sheet
重点 可以参考 宏录制 cell sheet.range(G4)cell.api.Hyperlinks.Add(Anchorcell.api, Address"", SubAddress"001-000-02301!A1")def deal_excel(self):with xw.App(visibleTrue) as app:wb app.books.open(self.summary_path, update_linksFalse)sheet…...
风光摄影:相机设置和镜头选择
写在前面 博文内容为《斯科特凯尔比的风光摄影手册》读书笔记整理涉及在风景拍摄中一些相机设置,镜头选择的建议对小白来讲很实用,避免拍摄一些过曝或者过暗的风景照片理解不足小伙伴帮忙指正 😃,生活加油 99%的焦虑都来自于虚度时间和没有好…...
python制作甘特图的基本知识(附Demo)
目录 前言1. matplotlib2. plotly 前言 甘特图是一种常见的项目管理工具,用于表示项目任务的时间进度 直观地看到项目的各个任务在时间上的分布和进度 常用的绘制甘特图的工具是 matplotlib 和 plotly 主要以Demo的形式展示 1. matplotlib 功能强大的绘图库&a…...
javascript设计模式总结
参考 通过设计模式可以增加代码的可重用性、可扩展性、可维护性 设计模式五大设计原则 单一职责:一个程序只需要做好一件事,如果结构过于复杂就拆分开,保证每个部分独立 开放封闭原则:对扩展开放,对修改封闭。增加需…...
Qt/C++开发监控GB28181系统/取流协议/同时支持udp/tcp被动/tcp主动
一、前言说明 在2011版本的gb28181协议中,拉取视频流只要求udp方式,从2016开始要求新增支持tcp被动和tcp主动两种方式,udp理论上会丢包的,所以实际使用过程可能会出现画面花屏的情况,而tcp肯定不丢包,起码…...
黑马Mybatis
Mybatis 表现层:页面展示 业务层:逻辑处理 持久层:持久数据化保存 在这里插入图片描述 Mybatis快速入门 ; List<Integer> evens new ArrayList…...
使用分级同态加密防御梯度泄漏
抽象 联邦学习 (FL) 支持跨分布式客户端进行协作模型训练,而无需共享原始数据,这使其成为在互联和自动驾驶汽车 (CAV) 等领域保护隐私的机器学习的一种很有前途的方法。然而,最近的研究表明&…...
系统设计 --- MongoDB亿级数据查询优化策略
系统设计 --- MongoDB亿级数据查询分表策略 背景Solution --- 分表 背景 使用audit log实现Audi Trail功能 Audit Trail范围: 六个月数据量: 每秒5-7条audi log,共计7千万 – 1亿条数据需要实现全文检索按照时间倒序因为license问题,不能使用ELK只能使用…...
Frozen-Flask :将 Flask 应用“冻结”为静态文件
Frozen-Flask 是一个用于将 Flask 应用“冻结”为静态文件的 Python 扩展。它的核心用途是:将一个 Flask Web 应用生成成纯静态 HTML 文件,从而可以部署到静态网站托管服务上,如 GitHub Pages、Netlify 或任何支持静态文件的网站服务器。 &am…...
【单片机期末】单片机系统设计
主要内容:系统状态机,系统时基,系统需求分析,系统构建,系统状态流图 一、题目要求 二、绘制系统状态流图 题目:根据上述描述绘制系统状态流图,注明状态转移条件及方向。 三、利用定时器产生时…...
mac 安装homebrew (nvm 及git)
mac 安装nvm 及git 万恶之源 mac 安装这些东西离不开Xcode。及homebrew 一、先说安装git步骤 通用: 方法一:使用 Homebrew 安装 Git(推荐) 步骤如下:打开终端(Terminal.app) 1.安装 Homebrew…...
Web后端基础(基础知识)
BS架构:Browser/Server,浏览器/服务器架构模式。客户端只需要浏览器,应用程序的逻辑和数据都存储在服务端。 优点:维护方便缺点:体验一般 CS架构:Client/Server,客户端/服务器架构模式。需要单独…...
【Elasticsearch】Elasticsearch 在大数据生态圈的地位 实践经验
Elasticsearch 在大数据生态圈的地位 & 实践经验 1.Elasticsearch 的优势1.1 Elasticsearch 解决的核心问题1.1.1 传统方案的短板1.1.2 Elasticsearch 的解决方案 1.2 与大数据组件的对比优势1.3 关键优势技术支撑1.4 Elasticsearch 的竞品1.4.1 全文搜索领域1.4.2 日志分析…...
