1、使用的依赖
com.aspose
aspose-words
14.9.0
com.e-iceblue
https://repo.e-iceblue.cn/repository/maven-public/
aspose-maven-repository
http://artifact.aspose.com/repo/
2、编写aspose.word 工具类
public class AsposeWordUtils {
private static final Logger log = LoggerFactory.getLogger(AsposeWordUtils.class);
static {
String fileName = "license.xml";
try (InputStream license = AsposeWordUtils.class.getClassLoader().getResource(fileName).openStream()) {
License asposeLicense = new License();
asposeLicense.setLicense(license);
} catch (Exception e) {
log.error("引入license文件失败!", e);
}
}
public static byte[] byteToPdf(byte[] content) {
try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream inputStream = new ByteArrayInputStream(content)) {
document document = new document(inputStream);
document.save(bos, SaveFormat.PDF);
return bos.toByteArray();
} catch (Exception e) {
log.error("字节数组转pdf字节数组失败!", e);
return null;
}
}
public static byte[] docToDocx(byte[] content) {
try(ByteArrayOutputStream bos = new ByteArrayOutputStream();
InputStream inputStream = new ByteArrayInputStream(content)) {
document document = new document(inputStream);
document.save(bos, SaveFormat.DOCX);
return bos.toByteArray();
} catch (Exception e) {
log.error("doc字节数组转docx字节数组失败!", e);
return null;
}
}
}
3、测试代码
@Test
public void wordToPdf(){
String filePath = "C:\Users\desktop\docx文件的.docx";
byte[] content = new byte[0];
try {
content = Files.readAllBytes(Paths.get(filePath));
} catch (IOException e) {
e.printStackTrace();
}
// 如果doc文件转成的pdf打不开的话,可先将doc字节流转成docx字节流,再转成pdf
// content = AsposeWordUtils.docToDocx(content);
// word字节数组转pdf字节数组
byte[] result = AsposeWordUtils.byteToPdf(content);
InputStream inputStream = new ByteArrayInputStream(result);
FileOutputStream fos = new FileOutputStream("C:\Users\desktop\导出的pdf文件.pdf");
byte[] buffer = new byte[1024];
int r = 0;
while ((r = inputStream.read(buffer)) != -1) {
fos.write(buffer, 0, r);
}
inputStream.close();
}
4、写一个license.xml文件,SpringBoot项目放resource目录下
Aspose.Total for Java
Aspose.Words for Java
Enterprise
20991231
20991231
8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7
sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=