Springboot 实现在线预览,word文档 doc、xlsx、pdf、txt等

一、安装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  # OpenOffice 默认安装位置
    max-tasks-per-process: 10
    port-numbers: 8101

四、代码演示

//用于转换
@Autowired
private DocumentConverter converter;

/**
 * 文件预览
 *
 * @param response
 */
@GetMapping("demo")
public void filePreview(HttpServletResponse response) {
    try {
        String filePath = "D:\\桌面\\技术服务合同范本.docx";                // 源文件地址(pdf,docx,doc都可以)
        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");
            // 文件转换,将源文件转换为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();
    }
}
  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值