1、导入依赖

/ https://mvnrepository.com/artifact/com.documents4j/documents4j-local
implementation group: 'com.documents4j', name: 'documents4j-local', version: '1.1.9'
// https://mvnrepository.com/artifact/com.documents4j/documents4j-transformer-msoffice-word
implementation group: 'com.documents4j', name: 'documents4j-transformer-msoffice-word', version: '1.1.9'

2、word转换pdf实现在线预览

//word文件转pdf
if(name.contains("docx") || name.contains("doc")) {
String uuid = UUIDUtil.getUUID();
FileOutputStream
fos = new FileOutputStream(CacheFileUtil.FILE_PATH + uuid+"."+ StringUtils.substringAfter(name, "."));
fos.write(bytes);
fos.close();
File inputWord = new File(CacheFileUtil.FILE_PATH + uuid+"."+ StringUtils.substringAfter(name, "."));
File outputFile = new File(CacheFileUtil.FILE_PATH + uuid + ".pdf");
InputStream docxInputStream = new FileInputStream(inputWord);
OutputStream outputStream = new FileOutputStream(outputFile);
IConverter converter = LocalConverter.builder().build();
if(name.contains("docx")){
converter.convert(docxInputStream).as(DocumentType.DOCX).to(outputStream).as(DocumentType.PDF).execute();
}else if(name.contains("doc")){
converter.convert(docxInputStream).as(DocumentType.DOC).to(outputStream).as(DocumentType.PDF).execute();
}

outputStream.close();

bytes = Files.readAllBytes(Paths.get(CacheFileUtil.FILE_PATH + uuid + ".pdf"));

//删除缓存在本地的转换文件
inputWord.delete();
outputFile.delete();

}

response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(name, "utf-8"));
response.getOutputStream().write(bytes);

posted on 2022-08-08 09:32  齐天大圣龙卷风  阅读(308)  评论(0编辑  收藏  举报