Word书签替换,加盖电子印章及转换PDF(Java实用版)
一、前言
在项目中有需要对word进行操作的,可以看看哈,本次使用比较强大的spire组件来对word进行操作,免费版支持三页哦,对于不止三页的word文件,可以购买收费版,官网:https://www.e-iceblue.cn/tutorials.html#,也可使用其他组件实现,如poi、docx4j等,我将代码整理成工具类了,大家可以拿下来直接使用哈,一起努力吧。
二、Spire的使用
1、引入pom.xml
<!-- 免费版 .free 只支持前三页转化 -->
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.office.free</artifactId>
<version>5.3.1</version>
</dependency>
2、AddStampUtils
工具类
/**
* @Author:wk
* @Slogan:无论风雨,和自己一决胜负吧
* @Create:2022/7/15/9:30
* @Description:TODO Word文件操作工具类
* @Version:1.0
*/
@Slf4j
public class AddStampUtils {
// 转换目标文件地址
// public static String WORD_OLD_URL = "src/main/resources/word/20200429宋体服务器同步版.doc";
// 转换后文件存放地址
// public static String WORD_NEW_URL = "src/main/resources/word/20200429宋体服务器同步版2.doc";
// WORD转PDF存放位置
// public static String PDF_NEW_URL = "src/main/resources/pdf/20200429宋体服务器同步版2.pdf";
// 电子印章图片地址
// public static String STAMP_IMG_URL = "src/main/resources/word/stamp.png";
/**
* 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)
* @param bookmarkName 书签名,通过名称寻找书签文本所在位置
* @param newBookmarkText 替换的文本新内容
*/
public void addKeyWordStamp(
String wordOldUrl,String wordNewUrl,String stampImgUrl,
String keyWord,Integer keyWordIndex,Float horizontal,
Float vertical,Float stampWidth,Float stampHeight,
String bookmarkName,String newBookmarkText
) {
// 加载文档
Document document = new Document();
document.loadFromFile(wordOldUrl);
// 判断是否需要替换书签位置文本内容
if (StringUtils.isNotEmpty(bookmarkName)) {
replaceBookmarkContent(document,bookmarkName,newBookmarkText);
}
// 获取关键字位置
TextSelection[] textSelections = document.findAllString(keyWord, false, false);
if (ObjectUtils.isNotEmpty(textSelections)) {
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);
}
// 保存添加电子章的Word文档
document.saveToFile(wordNewUrl);
document.dispose();
log.info("文档添加电子印章结束,新WORD文档地址:{}",wordNewUrl);
}
/**
* 替换书签名位置文本内容
* @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 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);
}
}
3、测试
Main主函数测试
public static void main(String[] args) {
// 目标文件地址
String wordOldUrl = "src/main/resources/word/20200429宋体服务器同步版.doc";
// 添加电子印章后文件存放地址
String wordNewUrl = "src/main/resources/word/20200429宋体服务器同步版2.doc";
// WORD转PDF存放位置
String pdfNewUrl = "src/main/resources/pdf/20200429宋体服务器同步版2.pdf";
// 电子印章图片地址
String stampImgUrl = "src/main/resources/word/stamp.png";
// word文档内容关键字
String keyWord = "盖章";
// 索引,默认就填-1即可
Integer keyWordIndex = -1;
// 电子印章水平位置
float horizontal = 260f;
// 电子印章垂直位置
float vertical = -55f;
// 电子印章宽度
float stampWidth = 120;
// 电子印章高度
float stampHeight = 120;
// 书签名
String bookmarkName = "ZWSTTCJKBH";
// 书签位置文本替换新内容
String newBookmarkText = "公开";
AddStampUtils addStampUtils = new AddStampUtils();
// 获取关键字位置并加盖印章并替换书签名位置文本内容
addStampUtils.addKeyWordStamp(wordOldUrl,wordNewUrl,stampImgUrl,keyWord,keyWordIndex,horizontal,vertical,stampWidth,stampHeight,bookmarkName,newBookmarkText);
// 转换为流 字节数组
byte[] bytesByFile = addStampUtils.getBytesByFile(wordNewUrl);
// 流转换为文件
addStampUtils.byte2File(bytesByFile,"src/main/resources/word/","20200429宋体服务器同步版3.doc");
// 将新word转化为pdf文件
addStampUtils.wordToPdf(wordNewUrl,pdfNewUrl);
}
4、效果展示
Before
旧书签位置内容
文档盖章地方:
After
5、注意事项
将word转化为PDF时,打开pdf,发现顶部多了一条横线,如下:
这条横线的由来:传说这条横线是由于word文件的页眉导致的,经过我的证实,发现将鼠标移动至页面顶端,并且双击进入了页眉编辑状态,退出时有时就会在留下一根页眉横线(即使啥都不输入),由此得出传说也可信。哈哈哈,心情愉悦一下
处理方法:
第一种方法:首先将点击页眉,进入页眉编辑状态,并将光标置于页眉处。然后单击“开始”,找到“样式”里面的“正文”样式,轻松删除。
第二种方法(推荐):将光标置于页眉处,同时按住键盘上的:Ctrl+Shift+N,页眉横线立即消失,再按ESC键退出页眉编辑即可。
Word书签替换,加盖电子印章及转换PDF(Java实用版)的更多相关文章
- tp5 使用phpword 替换word模板并利用com组件转换pdf
tp5 使用phpword 替换word模板并利用com组件转换pdf 一.首先composer安装PHPword,就不多说了 二.然后是把模板中要替换的部分用变量代替 三.把原始的模板文件放入项 ...
- javascript下用ActiveXObject控件替换word书签,将内容导出到word后打印第1/2页
由于时间比较紧,没多的时候去学习研究上述工具包,现在用javascript操作ActiveXObject控件,用替换word模板中的书签方式解决. 最近有需求将数据导出到word里,然后编辑打印. 想 ...
- springboot中word转pdf,加盖电子印章
概述 在开发过程中,word转pdf的方式有很多种有jar包的方式,有安装openoffice的方式,但是使用有的jar包有license认证,不然会生成水印,综合几种方法我采用了libreoffic ...
- 【docx4j】docx4j操作docx,实现替换内容、转换pdf、html等操作
主要是想要用此功插件操作docx,主要的操作就是操作段落等信息,另外,也想实现替换docx的内容,实现根据模板动态生成内容的效果,也想用此插件实现docx转换pdf. word的格式其实可以用xml来 ...
- 将页面内容转换Pdf\Word\Excel格式
项目中用到了将邮件内容转换为Pdf.Word.Excel格式,做为邮件附件发送. 查了一些解决方案,走了一些弯路.以此代码记录下. 转换PDF需要下载NReco.PdfGenerator.dll 以下 ...
- Word:转换PDF
本文适用于Word 2007 + Windows 7,造冰箱的大熊猫@cnblogs 2018/8/3 一.Word文档转PDF文档 把Word文档转换为PDF,有两个免费解决方案 1.Microso ...
- SharePoint 2013 Word 转换PDF服务介绍及示例
前言:在SharePoint使用过程中,经常会发现将文档进行格式转换的需求,之前,看到SharePoint 2013有将PPT转换PDF文档的服务,后来,才发现SharePoint 2010开始,就有 ...
- C#关于word文档的书签替换操作
public void Get_Word(string gjbh) { try { DataSet ds = OperaterBase.GetDsBySql("select diffTabl ...
- SharePoint Word 转换PDF服务介绍及示例
前言:在SharePoint使用过程中,经常会发现将文档进行格式转换的需求,之前,看到SharePoint 2013有将PPT转换PDF文档的服务,后来,才发现SharePoint 2010开始,就有 ...
- 在线文档转换API word,excel,ppt等在线文件转pdf、png
在线文档转换API提供word,excel,ppt等在线文件转pdf.png等,文档:https://www.juhe.cn/docs/api/id/259 接口地址:http://v.juhe.cn ...
随机推荐
- Linux:管道命令与文本处理三剑客(grep、sed、awk)
1 管道命令(pipe)介绍 众所周知,bash命令执行的时候会输出信息,但有时这些信息必须要经过几次处理之后才能得到我们想要的格式,此时应该如何处置?这就牵涉到 管道命令(pipe) 了.管道命令使 ...
- SqlServer 添加字段说明、表说明
1.添加表说明 EXECUTE sp_addextendedproperty N'MS_Description','表说明',N'user',N'dbo',N'table',N'表名',NULL,NU ...
- java POI创建HSSFWorkbook工作簿
1. POI Apache POI 是基于 Office Open XML 标准(OOXML)和 Microsoft 的 OLE 2 复合文档格式(OLE2)处理各种文件格式的开源项目. 2. 样式设 ...
- vue3的setup语法糖
https://blog.csdn.net/weixin_44922480/article/details/127337914 https://blog.csdn.net/m0_63108819/ar ...
- 一个好用的java图片缩放及质量压缩方法
本文中代码来自:http://blog.csdn.net/liuhuanchao/article/details/50527856由于网站需要对上传的图片进行宽度判断缩放和质量压缩,以提升整体加载速度 ...
- 2023-04-22:给你两个正整数数组 nums 和 target ,两个数组长度相等。 在一次操作中,你可以选择两个 不同 的下标 i 和 j , 其中 0 <= i, j < nums.leng
2023-04-22:给你两个正整数数组 nums 和 target ,两个数组长度相等. 在一次操作中,你可以选择两个 不同 的下标 i 和 j , 其中 0 <= i, j < num ...
- 2021-12-01:给定一个正数数组arr,代表每个人的体重。给定一个正数limit代表船的载重,所有船都是同样的载重量。 每个人的体重都一定不大于船的载重。 要求: 1, 可以1个人单独一搜船;
2021-12-01:给定一个正数数组arr,代表每个人的体重.给定一个正数limit代表船的载重,所有船都是同样的载重量. 每个人的体重都一定不大于船的载重. 要求: 1, 可以1个人单独一搜船: ...
- vue全家桶进阶之路36:Vue3 全局路由useRouter和本地路由useRoute
在 Vue.js 3.x 中,我们可以使用 useRouter 和 useRoute 来获取当前路由对象和当前路由信息. useRouter useRouter 可以用来获取当前路由对象.我们可以通过 ...
- Django-Virtualenv虚拟环境安装、新建,激活和手动指定Python解释器、虚拟环境安装Django、创建Django项目、运行Django项目
一.安装虚拟环境: 命令:pip3 install virtualenv 二.安装管理工具: 命令:pip3 install virtualenvwrapper 三.新建: 命令:python -m ...
- Kubernetes 证书详解
K8S 证书介绍 在 Kube-apiserver 中提供了很多认证方式,其中最常用的就是 TLS 认证,当然也有 BootstrapToken,BasicAuth 认证等,只要有一个认证通过,那么 ...