qiangzaiBlog

1、简介

有时候我们需要在程序中使用到office的转换和预览功能,本文就针对这个需求记录了较为简单的office转换和功能:jodconverter。当然也有aspose和其他开源第三方(kkfileview),jodconverter是免费的,aspose需要付费。

2、SpringBoot集成jodconverter实战

2.1、首先下载好OpenOffice或LibreOffice,并在pom.xml引入相关依赖

<!--转换工具-->

<dependency>

  <groupId>org.jodconverter</groupId>

  <artifactId>jodconverter-spring-boot-starter</artifactId>

  <version>4.4.2</version>

</dependency>

<dependency>

  <groupId>org.jodconverter</groupId>

  <artifactId>jodconverter-local</artifactId>

  <version>4.4.2</version>

</dependency>

<dependency>

  <groupId>org.jodconverter</groupId>

  <artifactId>jodconverter-core</artifactId>

  <version>4.4.2</version>

</dependency>

2.2、application.yml设置相关参数

jodconverter:

  local:

     enabled: true

     # libreOffice根目录

     officeHome: E:\soft\libreoffice

     # 任务执行的超时时间

     taskExecutionTimeout: 86400000

     # 任务队列的超时时间

     taskQueueTimeout: 86400000

     # 端口(线程)

     portNumbers: [2001,2002,2003]

     # 一个进程的超时时间

    processTimeout: 86400000

2.3、代码

@RequestMapping(value = "/preview")

@ResponseBody

public void preview(MultipartFile file, HttpServletResponse response) {

  if (file == null) {

    return;

  }

  InputStream inputStream = null;

  OutputStream outputStream = null;

  try {

    inputStream = file.getInputStream();

    outputStream = response.getOutputStream();

    String fileName = file.getOriginalFilename();

    if (StrUtil.endWithAnyIgnoreCase(fileName, ".doc", ".docx", ".xls", ".xlsx", ".csv", ".ppt", ".pptx")) {

      //转为PDF

      documentConverter.convert(inputStream).to(outputStream)

        .as(documentConverter.getFormatRegistry().getFormatByExtension("pdf")).execute();

    } else if (StrUtil.endWithAnyIgnoreCase(fileName, ".pdf", ".txt", ".xml", ".md", ".json", ".html", ".htm",

      ".gif", ".jpg", ".jpeg", ".png", ".ico", ".bmp")) {

      IoUtil.copy(inputStream, outputStream);

    } else {

      outputStream.write("暂不支持预览此类型附件".getBytes());

    }

  } catch (IORuntimeException e) {

    log.error("附件预览IO运行异常:{}", e.getMessage());

  } catch (IOException e) {

    log.error("附件预览IO异常:{}", e.getMessage());

  } catch (OfficeException e) {

    log.error("附件预览Office异常:{}", e.getMessage());

  } finally {

    IOUtils.closeQuietly(inputStream);

  }

  IoUtil.writeUtf8(outputStream, true);

}

2.4、效果演示

  2.4.1、在浏览器输入http://ip地址:端口号/file/index。

  2.4.2、上传附件,点击“选择文件”上传需要转换文件。

  2.4.3、点击“预览”,效果如下

分类:

技术点:

相关文章: