OpenOffice 是 Apache 开源的一个办公组件,可以直接到官网下载使用。适用windows、linux、mac等各大平台,当然对我们程序员来说,肯定不会下载下来用用就完了。我们要在代码中使用她,实现一些 web 项目中的附件预览功能。
一、OpenOffice安装
安装的话就不细说了,直接到官网下载,一路next点下去就行,没啥难度。
二、新建boot项目
这里简单建一个springboot的项目,引入这几个转换包,
<!-- jodconverter -->
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-core</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-local</artifactId>
<version>4.3.0</version>
</dependency>
<dependency>
<groupId>org.jodconverter</groupId>
<artifactId>jodconverter-spring-boot-starter</artifactId>
<version>4.3.0</version>
</dependency>
随后,配置文件 application-dev.yml,
server:
port: 8085
#jodconverter
jodconverter:
local:
enabled: true
office-home: D:/dev/tools/OpenOffice 4
max-tasks-per-process: 10
port-numbers: 8100
三、Controller 调用
package com.my.cloud.previewservice.controller;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.jodconverter.core.DocumentConverter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
/**
* @Author: 技术大咖秀
* @Date: 2020/3/27 11:13
* motto: Saying and doing are two different things.
*/
@Controller
public class PreviewController {
@Autowired
private DocumentConverter converter; // 转换器
@Autowired
private HttpServletResponse response;
@RequestMapping("/home")
public String homePage(){
return "index";
}
@RequestMapping("/test")
public String test(){
return "test";
}
@RequestMapping("/toPdfFile")
public String toPdfFile(){
File file = new File("D:/test/excel.xlsx");//需要转换的文件
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";
}
}
四、测试
新建测试文件,docx、xlsx、pptx 都试一下。
启动项目访问地址: http://localhost:8085/toPdfFile
测试成功。
PS。IE浏览器的话需要pdf.js(可百度下载)。