Java使用XWPFTemplate将word填充数据,并转pdf

poi-tl

poi-tl(poi template language)是基于Apache POI的Word模板引擎。纯Java组件,跨平台,代码短小精悍,通过插件机制使其具有高度扩展性。

主要处理区域有这么几个模块:

依赖

<dependency><groupId>com.deepoove</groupId><artifactId>poi-tl</artifactId><version>1.0.0</version><exclusions><exclusion><artifactId>slf4j-log4j12</artifactId><groupId>org.slf4j</groupId></exclusion></exclusions></dependency>

1、基本介绍

1.1、 根据文件路径、文件、文件流几种方式获取XWPFTemplate

//文件路径
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);//文件
File wordtemplate = new File(inDocxFilePath);
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);//文件流
InputStream wordtemplate = new FileInputStream(inDocxFilePath);
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);

1.2、生成到文件路径或者是流

//生成到文件路径
template.writeToFile(outFilePath);
template.close();//生成到流
FileOutputStream out = new FileOutputStream(wordoutprint);
template.write(out);
out.flush();//关闭资源
out.close();
template.close();

修改变量 为 ${var}

File inDocxFile = new File(inDocxFilePath);
Configure configure = Configure.newBuilder().buildGramer("${", "}").build();
XWPFTemplate template = XWPFTemplate.compile(inDocxFile, configure).render(map);

2、模板

2.1、文本、对象

TextRenderData、HyperLinkTextRenderData

Map<String, Object> map = new HashMap<>();// 1、普通字符map.put("word", "helloWord");//2、配置格式Style style = StyleBuilder.newBuilder().buildColor("00FF00").buildBold().build();map.put("author", new TextRenderData("HealerJean", style));//3、超链接map.put("website", new HyperLinkTextRenderData("website.", "http://www.baidu.com"));//制作模板XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(map);//开始生成新的wordFileOutputStream outputStream = new FileOutputStream(outDocxFilePath);template.write(outputStream);outputStream.flush();//关闭资源outputStream.close();template.close();

2.2、图片

PictureRenderData

String imagePath = "D:/pdf/image.png";Map<String, Object> map = new HashMap<>();// 本地图片map.put("localPicture", new PictureRenderData(120, 120, imagePath));// 图片流文件InputStream inputStream = new FileInputStream(imagePath);map.put("localBytePicture", new PictureRenderData(100, 120, ".png", inputStream));// 网络图片map.put("urlPicture", new PictureRenderData(100, 100, ".png", BytePictureUtils.getUrlBufferedImage("https://raw.githubusercontent.com/HealerJean/HealerJean.github.io/master/assets/img/tctip/weixin.j跑pg")));// java 图片BufferedImage bufferImage = ImageIO.read(new FileInputStream(imagePath));map.put("bufferImagePicture", new PictureRenderData(100, 120, ".png", bufferImage));//如果希望更改语言前后缀为 ${var}Configure builder = Configure.newBuilder().buildGramer("${", "}").build();XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, builder).render(map);//开始生成新的wordtemplate.writeToFile(outDocxFilePath);template.close();

2.3、表格

MiniTableRenderData

Map<String, Object> map = new HashMap<>();Table table1 = new Table("11", "12", "13");Table table2 = new Table("21", "22", "23");List<Table> table = new ArrayList<>();table.add(table1);table.add(table2);// RowRenderData header = RowRenderData.build("one", "two", "three");//使用样式Style style = StyleBuilder.newBuilder().buildColor("00FF00").buildBold().build();RowRenderData header = RowRenderData.build(new TextRenderData("one", style), new TextRenderData("two"), new TextRenderData("three"));List<RowRenderData> tableBody = new ArrayList<>();for (Table item : table) {RowRenderData row = RowRenderData.build(item.getOne(), item.getTwo(), item.getThree());tableBody.add(row);}map.put("table", new MiniTableRenderData(header, tableBody));Configure builder = Configure.newBuilder().buildGramer("${", "}").build();XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, builder).render(map);template.writeToFile(outDocxFilePath);template.close();

2.4、列表模板

NumbericRenderData

Map<String, Object> map = new HashMap<>();map.put("unorderlist", new NumbericRenderData(new ArrayList<TextRenderData>()));map.put("orderlist", new NumbericRenderData(NumbericRenderData.FMT_DECIMAL, new ArrayList<TextRenderData>()));//如果希望更改语言前后缀为 ${var}Configure builder = Configure.newBuilder().buildGramer("${", "}").build();XWPFTemplate template = XWPFTemplate.compile(inDocxFilePath, builder).render(map);template.writeToFile(outDocxFilePath);template.close();

3、配置

ConfigureBuilder builder = Configure.newBuilder();
XWPFTemplate.compile("~/template.docx", builder.buid());

3.1、图片语法@修改为%

builder.addPlugin('%', new PictureRenderPolicy());

3.2、语法加前缀 为${var}

builder.buildGramer("${", "}");

3.3、模板标签设置正则表达式规则

模板标签支持中文、字母、数字、下划线的组合,比如,我们可以通过正则表达式来配置标签的规则,比如不允许中文:

builder.buildGrammerRegex("[\\w]+(\\.[\\w]+)*");

下面为我在工作中的应用:

生成word:

Map<String, Object> datas = new HashMap<String, Object>() {
{
//时间
put("year", year);
put(pNames[j] + "_" + vNames[j] + "_img_zhpf_4", new PictureRenderData(500, 300, pyhon_img_path + pNames[j] + "_" + vNames[j].replace("_", "-") + "_" + "comprehensive_score_" + element + "_4.png"));
}
};
XWPFTemplate template = XWPFTemplate.compile(wordtemplate).render(datas);
FileOutputStream out = new FileOutputStream(wordoutprint);
template.write(out);
out.flush();
out.close();
template.close();

转pdf:

public static boolean getLicense() {boolean result = false;try {File directory = new File("");// 参数为空String courseFile = directory.getCanonicalPath();//获取项目根目录
//            File file = new File("/temp/qh_assess/java_pro/config/license.xml"); // 新建一个空白pdf文档File file = new File(courseFile + "/config/license.xml"); // 新建一个空白pdf文档InputStream is = new FileInputStream(file); // license.xml找个路径放即可。License aposeLic = new License();aposeLic.setLicense(is);result = true;} catch (Exception e) {e.printStackTrace();}return result;}public static boolean doc2pdf(String inPath, String outPath) {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生return false;}try {long old = System.currentTimeMillis();File file = new File(outPath); // 新建一个空白pdf文档FileOutputStream os = new FileOutputStream(file);Document doc = new Document(inPath); // Address是将要被转化的word文档doc.save(os, SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,// EPUB, XPS, SWF 相互转换long now = System.currentTimeMillis();System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时} catch (Exception e) {e.printStackTrace();}return true;}

license.xml

<?xml version="1.0" encoding="UTF-8" ?>
<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>

这是默认生成的水印

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/pingmian/24305.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

树算法例子

树算法概述 树(Tree)是一种重要的数据结构,在许多算法中都有广泛的应用。 二叉树和红黑树是两种重要的数据结构,广泛应用于提供高效的数据查询和操作。下面,我将给出二叉搜索树(BST)和红黑树(RB Tree)的基本实现: 1. 二叉搜索树 (Binary Search Tree, BST) 二叉搜…

服务器硬件基础知识及运行维护指南

目录 服务器硬件基础知识 1. 中央处理器&#xff08;CPU&#xff09; 2. 内存&#xff08;RAM&#xff09; 3. 存储设备 4. 主板&#xff08;Motherboard&#xff09; 5. 电源供应器&#xff08;PSU&#xff09; 6. 网络接口卡&#xff08;NIC&#xff09; 7. 冷却系统 …

记忆++入门01

1.数字编码 2. 地点桩 1. 卧室 2.婴儿房 3.卫生间 4.次卧 5.书房 6.厨房 7.餐厅 8.客厅 9.阳台左 10.阳台右

Springboot引入redis启动报错问题的解决

在springboot项目pom文件中添加了下面依赖 <dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-data-redis</artifactId> </dependency> 后面老师说spring-boot-starter-data-redis默认使用的let…

深度学习每周学习总结P10(车牌识别)

&#x1f368; 本文为&#x1f517;365天深度学习训练营 中的学习记录博客&#x1f356; 原作者&#xff1a;K同学啊 | 接辅导、项目定制 数据链接 提取码&#xff1a;ppv1 –来自百度网盘超级会员V5的分享 目录 0. 总结1. 数据导入、查看数据分类&#xff0c;自定义transform…

2024全国高考作文题解读(Chat GPT 4.0版本)

新课标I卷 阅读下面的材料&#xff0c;根据要求写作。&#xff08;60分&#xff09; 随着互联网的普及、人工智能的应用&#xff0c;越来越多的问题能很快得到答案。那么&#xff0c;我们的问题是否会越来越少&#xff1f; 以上材料引发了你怎样的联想和思考&#xff1f;请写…

【TB作品】MSP430G2553单片机,MSP430 单片机读取 SHT30 传感器并显示数据

使用 MSP430 单片机读取 SHT30 传感器并显示数据 作品功能 本文介绍了如何使用 MSP430 单片机读取 SHT30 温湿度传感器的数据&#xff0c;并通过 OLED 屏幕显示实时的温度和湿度信息。通过此项目&#xff0c;您将学习如何配置 MSP430 的 I2C 接口、读取 SHT30 传感器的数据以…

高考志愿填报有哪些技巧和方法

一年一度高考季&#xff0c;又高考志愿填报的时侯了。高考志愿填报的时侯&#xff0c;需要考虑的因素比较多&#xff0c;有的同学觉是离家越远越好&#xff0c;要放飞自我&#xff0c;家长再也管不了我了。有的同学觉得专业比学校牌子重要&#xff0c;只要报个好专业&#xff0…

Nvidia/算能 +FPGA+AI大算力边缘计算盒子:大型机械智能预警系统

三一重工股份有限公司&#xff0c;是由三一集团创建于1994年&#xff0c;通过打破国人传统的“技术恐惧症”坚持自主创新迅速崛起。2011年7月&#xff0c;三一重工以215.84亿美元的市值荣登英国《金融时报》全球市值500强&#xff0c;是迄今唯一上榜的中国机械企业。2012年1月&…

centos7如何备份

在CentOS 7中备份数据是一个重要的任务&#xff0c;可以帮助你在数据丢失或系统故障时恢复信息。以下是一些常用的备份方法&#xff1a; 1. 使用​​rsync​​工具备份 ​​rsync​​是Linux系统中常用的备份工具&#xff0c;它可以备份和同步文件到本地目录、外部硬盘或者通…

AI和机器人引领新一轮农业革命

AI和机器人技术在农业领域的应用正在迅速发展&#xff0c;未来它们可能会实现厘米级精度的自主耕作。 精确种植&#xff1a;AI算法可以分析土壤条件、气候数据和作物生长周期&#xff0c;以决定最佳种植地点和时间。 土壤管理&#xff1a;利用传感器和机器学习&#xff0c;机器…

Android Webview 详解

一 简介 一个基于webkit引擎、展现web页面的控件 Android 4.4前&#xff1a;Android Webview在低版本 & 高版本采用了不同的webkit版本的内核Android 4.4后&#xff1a;直接使用了Chrome内核 1.1 作用 在 Android 客户端上加载h5页面在本地 与 h5页面实现交互 & …

Mybatis配置

1. 核心配置文件 mybatis-config.xml 2. 环境配置 Mybatis可以配置适应多种环境 但每个SqlSessionFactory实例只能选择一种环境 Environment <environments default"development"><environment id"development"><transactionManager type&…

为Android组件化项目搭建Maven私服

概览 文章目录 概览前言搭建 maven 私服服务器环境jdk安装配置nexus安装配置管理创建存储点、仓库 项目中使用 maven 私服上传 module 到仓库自动发布 module手动上传单个aar包 引用仓库中的 modulebuild.gradle引入远程module FAQ开发阶段有些module用远程依赖&#xff0c;有些…

20240607在ubuntu下解压缩7z的压缩包文件

20240607在ubuntu下解压缩7z的压缩包文件 2024/6/7 10:26 百度&#xff1a;ubuntu 7z解压缩 在Ubuntu中&#xff0c;可以使用7z命令来解压.7z文件。首先&#xff0c;确保你已经安装了p7zip-full包&#xff0c;如果没有安装&#xff0c;可以使用以下命令安装&#xff1a; sudo …

input输入框设置样式

input清除自带样式 input, textarea,label, button,select,img,form,table,a{-webkit-tap-highlight-color: rgba(255,255,255,0);-webkit-tap-highlight-color: transparent;margin: 0;padding: 0;border: none; } /*去除iPhone中默认的input样式*/ input, button, select, t…

pytorch 使用tensor混合:进行index操作

(Pdb) tmp torch.randn(3,5) (Pdb) indx torch.tensor([1,0]).long() (Pdb) temp(indx) *** NameError: name ‘temp’ is not defined (Pdb) tmp(indx) *** TypeError: ‘Tensor’ object is not callable (Pdb) tmp[indx] tensor([[ 0.1633, 0.9389, 1.2806, -0.2525, 0.28…

【雷达原理】一维CFAR检测算法——对比分析与代码实现

目录 引言一、仿真实例1.1 均匀背景杂波1.2 杂波边缘1.3 多干扰目标杂波 二、MATLAB代码参考文献 引言 推荐博文【目标检测】雷达目标CFAR检测算法 上述文章介绍了四种典型CFAR检测算法的特点及性能对比。本文将利用MATLAB进行仿真&#xff0c;通过实例验证和对比这几种算法的…

力扣1234.替换子串得到平衡字符串

力扣1234.替换子串得到平衡字符串 由题意可知 超过n/4的字母是一定要替换的 所以只要找到一段包含超过n/4个字母的最小区间即可转换为去除这个最小区间后 4种字母的出现频率都<n/4 class Solution {public:int balancedString(string s) {unordered_map<char,int> …

是时候让临床预测模型进入临床实践

是时候让临床预测模型进入临床实践了 临床预测模型发展已经有一段时间&#xff0c;现在感觉是时候让临床预测模型进入临床实践了。 从技术方面考虑&#xff0c;临床预测模型进入临床实践需要的技术都已经具备&#xff0c;从模型开发、验证、阈值确定、部署和临床效应评价的关…