一、引入aspose库
1、如果是本地引入使用一下maven坐标,jar放在“resources”下
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>20.3</version>
<scope>system</scope>
<systemPath>${project.basedir}/src/main/resources/lib/aspose-words-20.3-jdk17.jar</systemPath>
</dependency>
2、如果需要安装jar到本地maven仓库,使用一下命令
mvn install:install-file -Dfile=F:\aspose-words-20.3-jdk17.jar -DgroupId=com.aspose -DartifactId=aspose-words -Dversion=20.3 -Dpackaging=jar
引入坐标使用
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-words</artifactId>
<version>20.3</version>
</dependency>
二、授权文件
1、把授权文件放在“resources/license”目录下,目录结构如下图
2、在springboot初始化时进行授权验证,新建“AsposeLicenseConfig”如下
import com.aspose.words.License;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.io.InputStream;
@Slf4j
@Component
public class AsposeLicenseConfig implements CommandLineRunner {
public static boolean loadLicense() {
boolean result = false;
try {
InputStream license = AsposeLicenseConfig.class.getClassLoader().getResourceAsStream("license/license.lic");
License asposeLic = new License();
asposeLic.setLicense(license);
result = true;
} catch (Exception e) {
log.error("Aspose license load error:", e);
}
return result;
}
@Override
public void run(String... args) throws Exception {
if (loadLicense()){
log.info("aspose lic import success");
}
}
}
不进行此步骤,生成文档有水印,而且处理页数有限制
三、编辑模板文件
1、把需要替换的模板用自定义字符编辑
2.加载模板文件进行处理
public static byte[] generateContract() throws Exception {
//获取模板文件
ClassPathResource templateResource = new ClassPathResource("template/demo.docx");
Document doc = new Document(templateResource.getStream());
Map<String,String> textMap = new HashMap<>();
textMap.put("${name}","Tom");
textMap.put("${age}","19");
Map<String,byte[]> imgMap = new HashMap<>();
imgMap.put("${img}",getImageBytesFromURL("http://myimg.jpg"));
replaceAll(doc,textMap);
replaceImg(doc,imgMap);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//把生成的文档转换为pdf格式
doc.save(bos, SaveFormat.PDF);
//返回byte[]格式,便于进行oss存储或其他处理
return bos.toByteArray();
其中“getImageBytesFromURL()”用于根据url获取图片的byte[]
public static byte[] getImageBytesFromURL(String url) {
try {
URL imgUrl = new URL(url);
// 打开连接
URLConnection connection = imgUrl.openConnection();
// 获取输入流
InputStream inputStream = connection.getInputStream();
// 读取图片数据到字节数组
byte[] imageBytes = readBytesFromInputStream(inputStream);
// 关闭输入流
inputStream.close();
return imageBytes;
}catch (Exception e){
log.error("获取图片byte[]失败");
}
return null;
}
private static byte[] readBytesFromInputStream(InputStream inputStream) throws Exception {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int bytesRead;
// 从输入流中读取数据到缓冲区
while ((bytesRead = inputStream.read(buffer)) != -1) {
// 将缓冲区的数据写入到ByteArrayOutputStream
byteArrayOutputStream.write(buffer, 0, bytesRead);
}
// 关闭ByteArrayOutputStream,这将刷新缓冲区
byteArrayOutputStream.close();
// 返回字节数组
return byteArrayOutputStream.toByteArray();
}
replaceAll() 具体如下
public static void replaceAll(Document document, Map<String, String> textMap) {
FindReplaceOptions options = new FindReplaceOptions();
options.setMatchCase(false);
textMap.forEach((k, v) -> {
try {
document.getRange().replace(k, v, options);
} catch (Exception e) {
log.error("生成失败!", e);
}
});
}
replaceImg()具体如下
public static void replaceImg(Document document,Map<String,byte[]> imgMap){
ParagraphCollection paragraphs = (ParagraphCollection)document.getChildNodes(NodeType.PARAGRAPH, true);
for (Paragraph paragraph : paragraphs) {
Set<String> keys = imgMap.keySet();
for (String key : keys) {
int index = paragraph.getText().indexOf(key);
if (index>=0){
DocumentBuilder builder = new DocumentBuilder((Document)paragraph.getDocument());
builder.moveTo(paragraph);
builder.write(paragraph.getText().substring(0,index));
try {
builder.insertImage(imgMap.get(key),856F,540F);
} catch (Exception e) {
log.error("图片替换失败");
}
builder.write(paragraph.getText().substring(index + key.length()));
try {
paragraph.getRange().replace(key,"");
} catch (Exception e) {
log.error("模板字符去除失败");
}
}
}
}
}
把生成的pdf转换成 MultipartFile 格式,用于后面处理,兼容springboot文件接口
//生成PDF
byte[] bytes = generateContract();
//存储PDF
MultipartFile multipartFile = new MockMultipartFile(
"test.pdf",
"test.pdf",
"application/pdf",
bytes);