前提
安装openOfiice,直接下载安装没啥好说的
引入相关pom
修改配置文件
- 相关pom
<!--jodconverter 核心包 -->
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-core -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.2.4</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.4</version>
</dependency>
<!--jodconverter 本地支持包 -->
<!-- https://mvnrepository.com/artifact/org.jodconverter/jodconverter-local -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.2.4</version>
</dependency>
<!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.6</version>
</dependency>
2.配置文件
jodconverter:
local:
enabled: true
office-home: C:\Program Files (x86)\OpenOffice 4\
max-tasks-per-process: 10
port-numbers: 8100
3.controller
@Controller
public class ToPdfController {
// 第一步:转换器直接注入
@Resource
private DocumentConverter converter;
@Resource
private HttpServletResponse response;
@RequestMapping("toPdfFile")
public String toPdfFile() {
File file = new File("D:/a.docx");//需要转换的文件
try {
File newFile = new File("D:/obj-pdf");//转换之后文件生成的地址
if (!newFile.exists()) {
newFile.mkdirs();
}
//文件转化
converter.convert(file).to(new File("D:/obj-pdf/hello.pdf")).execute();
//使用response,将pdf文件以流的方式发送的前段
ServletOutputStream outputStream = response.getOutputStream();
InputStream in = new FileInputStream(new File("D:/obj-pdf/hello.pdf"));// 读取文件
// copy文件
int i = IOUtils.copy(in,outputStream);
System.out.println(i);
in.close();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
return "This is to pdf";
}
}