java使用Openoffice 转存 office 文件格式

本机环境

win7 ,java8 ,openoffice.org4

使用apache开源的openoffice软件, 将word,ppt,转存为pdf

最近寻找将常用的word,ppt转换成pdf,和将excel转换成html的方案,看到一篇文章

Office在线预览及PDF在线预览的实现方式大集:
http://www.officeweb365.com/officetoview.html
尝试过jacob, 但是跨平台性太差劲 ,且换个机器还需要调试, 甚是麻烦
于是决定采用 openoffice 方案

安装openoffice.org

官网地址: http://www.openoffice.org/download/index.html
下载完毕, 一直下一步即可 ,安装完毕后 ,双击打开运行openoffice程序,
然后进入到软件家目录 (C:\Program Files (x86)\OpenOffice 4\program)
打开命令行,运行一下代码 ,开启服务

soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard

运行完毕,可以看到任务管理器>进程>中出现了soffice.bin 和 soffice.exe ,至此,环境安装和准备工作完成, 接下来就是写代码了

pom依赖包

<!-- 两个openoffice 依赖, 必须2.2.2支持07格式-->
        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.2</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.github.livesense/jodconverter-core -->
        <dependency>
            <groupId>com.github.livesense</groupId>
            <artifactId>jodconverter-core</artifactId>
            <version>1.0.5</version>
        </dependency>

com.github.livesense ,使用这个包是可以省去在引入其他依赖包,省事 ,不一定必须非用这个, 但是jodconverter-2.2.2是必须的 ,只有2.2.2版本支持07以上的格式 ,需要去官网https://sourceforge.net/projects/jodconverter/files/下载 ,maven仓库只有2.2.1的版本 ,下载完毕自行处理和引入

核心代码

// 核心代码很简洁,无非就是: 连接 -> 转存为其他格式 -> 断开
OpenOfficeConnection connection = new SocketOpenOfficeConnection(HOST, PORT);
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
// 可以直接输入文件名实现转存 ,converter会自行判断格式
  converter.convert("d://a.docx", "d://aaaaa.pdf");
 connection.disconnect();

封装个工具类代码

import com.artofsolving.jodconverter.BasicDocumentFormatRegistry;
import com.artofsolving.jodconverter.DefaultDocumentFormatRegistry;
import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.sun.istack.Nullable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.validation.constraints.NotNull;
import java.io.File;
import java.net.ConnectException;

public class OpenOfficeUtil {
    private static final String HOST = "127.0.0.1";
    private static final int PORT = 8100;

/**
     * convert("原文件路径","docx", "目标文件路径", "pdf")
     *
     * @param sourceFile
     * @param sourceExtension
     * @param targetFile
     * @param targetExtension
     */
    public static boolean convert(@NotNull String sourceFile, @NotNull String sourceExtension, @NotNull String targetFile, @Nullable String targetExtension) {
        // 源文件是否存在
        File inputFile = new File(sourceFile);
        if (!inputFile.exists()) {
            logger.error("源文件不存在:{} " + sourceFile);
            return false;
        }
        if (!inputFile.canRead()) {
            logger.error("源文件存在, 但是不可读:{} " + sourceFile);
            return false;
        }
        // 输出文件的父目录创建.
        File outputFile = new File(targetFile);
        File targetParentFolders = outputFile.getParentFile();
        if (!targetParentFolders.exists()) {
            //noinspection ResultOfMethodCallIgnored
            targetParentFolders.mkdirs();
        }

        // 连接, 转换, 然后关闭
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(HOST, PORT);
        try {
            if (!connection.isConnected()) {
                connection.connect();
            }
        } catch (ConnectException e) {
            e.printStackTrace();
            logger.error("严重错误: openoffice 服务连接失败." + HOST + ":" + PORT);
            return false;
        }

        boolean isSuccess;
        try {
            //源文件类型  @see document-formats.xml
            DefaultDocumentFormatRegistry ddfr = new DefaultDocumentFormatRegistry();

            DocumentFormat sourceDF = ddfr.getFormatByFileExtension(sourceExtension);
            DocumentFormat targetDF = ddfr.getFormatByFileExtension(targetExtension);

            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(inputFile, sourceDF, outputFile, targetDF);
            isSuccess = true;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("严重错误: 文件转换失败:{}" + e.getMessage());
            isSuccess = false;
        } finally {
            if (connection.isConnected()) {
                connection.disconnect();
            }
        }
        return isSuccess;
    }

    public static void main(String[] args) {

convert("d://a.docx", "docx", "d://aa.pdf", "pdf");
convert("d://a.pptx", "pptx", "d://aa.pdf", "pdf");
convert("d://a.xlsx", "xlsx", "d://aa.html", "html");//巨丑
}
}

完结

java代码部分写的太多了, 其核心部分就几句, 自行体会:

OpenOfficeConnection connection = new SocketOpenOfficeConnection(HOST, PORT);
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert("d://a.docx", "d://aaaaa.pdf");
 connection.disconnect();

其中 ,DefaultDocumentFormatRegistry 是为了应对文件没有后缀(例如d://a), 而指定文件类型而做的操作 ,可以看看 OpenOfficeDocumentConverter 源码 ,里面有多个重载的convert方法

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值