1.word模板制作
- 在word文档光标位置,插入 -》文档部件 -》域,弹框如下:

最终生成的模板文档如下:

注:图片域和单个变量域是同一个,定义图片域时,同一个图片需要定义不同的域名。
2.工具类准备
- 使用Aspose进行文档转换,首先引入相应的jar包到系统环境
- 项目resource下导入license.xml文件
- 使用Aspose时,需要调用设置License方法,设置完成第一次替换比较慢,再次就不需要设置License方法,效率会更高。
注意:使用Aspose时,每一个模块(words,pdf,cells)都有相同的类,如License类,SaveOptions类,SaveFormat类,功能各不相同。
获取license示例代码:
package com.sinoif.common.utils;
import com.aspose.words.License;
import lombok.extern.slf4j.Slf4j;
import java.io.InputStream;
/**
* @description:
* @author: guanlj
* @date: 2020/7/24 11:10
*/
@Slf4j
public class AsposeLicenseUtil {
private static License aposeLic = new License();
/**
* 获取License的输入流
*
* @return
*/
private static InputStream getLicenseInput() {
InputStream inputStream = null;
ClassLoader contextClassLoader = Thread.currentThread().getContextClassLoader();
try {
//获取项目resource下的文件流
inputStream = contextClassLoader.getResourceAsStream("license.xml");
} catch (Exception e) {
log.error("license not found!"+ e);
}
return inputStream;
}
/**
* 设置License
*
* @return true表示已成功设置License, false表示失败
*/
public static boolean setWordsLicense() {
if (!aposeLic.getIsLicensed()) {
try {
aposeLic.setLicense(getLicenseInput());
return aposeLic.getIsLicensed();
} catch (Exception e) {
log.error("set words license error!", e);
}
}
return aposeLic.getIsLicensed();
}
}
3.模板填充
代码示例:
package com.sinoif.common.utils;
import com.aspose.words.*;
im

本文详细介绍如何使用Aspose库在Java环境下实现Word文档模板的自动化填充,包括文本、图片及表格数据的替换,以及如何避免水印和提高转换效率。

948

被折叠的 条评论
为什么被折叠?



