一、安装OpenOffice
OpenOffice下载
二、引入依赖
<!--jodconverter 核心包 -->
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.2.2</version>
</dependency>
<!--springboot支持包,里面包括了自动配置类 -->
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-spring-boot-starter -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.2.2</version>
</dependency>
<!--jodconverter 本地支持包 -->
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-local -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.2.2</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
三、配置application.yml文件
jodconverter:
local:
enabled: true
office-home: C:\Program Files (x86)\OpenOffice 4
max-tasks-per-process: 10
port-numbers: 8101
四、代码演示
@Autowired
private DocumentConverter converter;
@GetMapping("demo")
public void filePreview(HttpServletResponse response) {
try {
String filePath = "D:\\桌面\\技术服务合同范本.docx";
File file = new File(filePath);
response.setContentType("application/pdf;charset=UTF-8");
response.setHeader("X-Frame-Options", "SAMEORIGIN");
if (StringUtils.endsWith(filePath, ".doc") || StringUtils.endsWith(filePath, ".docx")) {
UUID uuid = UUID.randomUUID();
File newFile = new File("D:\\桌面\\" + uuid + ".pdf");
converter.convert(file).to(newFile).execute();
ServletOutputStream out = response.getOutputStream();
InputStream in = new FileInputStream(newFile);
int size = IOUtils.copy(in, out);
in.close();
out.close();
System.out.println("该文件大小为:" + size + "字节");
}
} catch (IOException e) {
e.printStackTrace();
} catch (OfficeException e) {
e.printStackTrace();
}
}