springboot jodconverter openoffice 实现 office 文件 在线预览

这个已是好几个月前做的,好多细节已记得不那边清楚了。今天部署到环境还遇到不少问题。总结下。

1、office 文件实现在线预览的一般思路就是,将文件转pdf,在通过pdf.js 实现在线浏览。这其中转pdf 各个工具转换的效果有些差异,存在走样问题。

2、另一种思路是通过脚本调用office 的转换pdf功能,这种效果最好,高保真。但就是会麻烦些,依赖office 工具。

3、如果还要部署到Linux上使用哪就只能用开源的办公软件 openoffice 了。

4、jodconverter 能很好的调用openoffice 工具转换 配置也相对比较简单。

效果图:

springboot jodconverter openoffice 实现 office 文件 在线预览_第1张图片

 

 

springboot jodconverter openoffice 实现 office 文件 在线预览_第2张图片

 

springboot 默认集成了jodconverter 所有应用起来很方便

yml 中加入如下配置就可以了

jodconverter:
enabled: true #注意这个开关,今天部署时就遇到这个问题,排查好久才发现。
officeHome: C:\Program Files (x86)\OpenOffice 4
portNumbers: 8101,8102,8103,8104,8105
maxTasksPerProcess: 5

 

核心代码:

  public boolean office2pdf(FileEntity fileEntity, String suffix) {
    LOG.info("call office to pdf ,file info:" + fileEntity.toString());
    File file = new File(fileEntity.getAbsolute_path());
    if (file.exists() && file.isFile()) {
      LOG.info("call office to pdf ,find file info:" + fileEntity.toString());
      try {
        File pdfFile = new File(file.getParentFile(), fileEntity.getPrn() + suffix);
        if (!pdfFile.exists()) {
          DocumentConverter documentConverter = szAppConfig.getBeanByClass(DocumentConverter.class);
          documentConverter.convert(file).to(pdfFile).execute();
          if (".html".equalsIgnoreCase(suffix)) {
            try {
              String htmlFormant =
                  "\n" +
                      "    \n" +
                      "\n" +
                      "\n" +
                      "\n" +
                      "";
RandomAccessFile raf = new RandomAccessFile(pdfFile.getAbsolutePath(), "rw");
long lastPoint = 0; //记住上一次的偏移量
String line = null;
while ((line = raf.readLine()) != null) {
final long ponit = raf.getFilePointer();
if (line.toUpperCase().contains("")) {
String str = line.toUpperCase().replace("", htmlFormant);
raf.seek(lastPoint);
raf.write(str.getBytes("gb2312"));
}
lastPoint = ponit;
}
raf.close();
} catch (IOException e) {
e.printStackTrace();
}
}
LOG.info("call office to pdf ,convert over. file info:" + fileEntity.toString());
}
return true;
} catch (OfficeException e) {
e.printStackTrace();
LOG.info(
"call office to pdf ,thrown error info:" + e.toString() + ", file info:" + fileEntity
.toString());
return false;
}
}
return false;
}

 

上面有一个任意读写文件,是为了加入自定已的js 来控制excle 的展示样式。反正当时纠结了好久。

pom:



org.jodconverter
jodconverter-core
4.1.0


org.jodconverter
jodconverter-local
4.1.0


org.jodconverter
jodconverter-spring-boot-starter
4.1.0


org.libreoffice
juh
5.4.2


org.libreoffice
jurt
5.4.2


org.libreoffice
ridl
5.4.2


org.libreoffice
unoil
5.4.2


org.libreoffice
unoloader
5.4.2


代码就这么些着实有些简洁,却实现了一个看着不那么容易的功能。

转载于:https://www.cnblogs.com/kunsyliu/p/11246168.html

你可能感兴趣的:(springboot jodconverter openoffice 实现 office 文件 在线预览)