踩坑日记 - word转pdf

说明

最近这几天研究了下word转pdf的功能实现,特别记录下,方便以后查看。
搜索了网上大部分的资料,总的来说,不外乎以下几种:
1. openoffice,支持windows和linux环境,亲测,word转成pdf后,windows环境下格式没问题,但是linux环境下格式有些出入,且不好跟踪定位;
2. word转html,再通过itext转成pdf,实现最方便,效果最差,跨平台,未测试
3. libreoffice,支持跨平台,和openoffice的实现类似,亲测,实现效果比openoffice好;
4. jacob + msOfficeWord + SaveAsPDFandXPS,保持原doc格式,效率最慢,只能在windows环境下进行,未测试;

最终,我选择使用libreoffice来实现word转pdf的功能。

openoffice实现

1、安装openoffice服务
http://www.openoffice.org/download/index.html
2、功能实现

/**
 * 若OFICCE转换PDF不经常调用,则调用时启动openoffice server 将Office文档转换为PDF.
 * 运行该函数需要用到OpenOffice
 * 
 * @description
 * @param sourceFile
 *      源文件, 绝对路径. 可以是Office2003-2007全部格式的文档, Office2010的没测试. 包括.doc, .docx, .xls, .xlsx, .ppt, .pptx等. 
 *      示例: D:/111/淮安药监_数据交换问题201404.doc
 * @param destFile
 *      目标文件. 绝对路径. 示例: D:/111/淮安药监_数据交换问题201404.pdf
 * @return 操作成功与否的提示信息. 
 *      如果返回 -1, 表示找不到源文件, 或OpenOffice 安装目录路径配置错误; 
 *      如果返回 0, 则表示操作成功; 返回1, 则表示转换失败
 * @2014-6-18 上午10:55:01
 */
public int office2PDF(String sourceFile, String destFile) {
    initParameters();
    // connect to an OpenOffice.org instance running on port 8100
    OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
    try {
        File inputFile = new File(sourceFile);
        if (!inputFile.exists()) {
            return -1;// 找不到源文件, 则返回-1
        }
        // 如果目标路径不存在, 则新建该路径
        File outputFile = new File(destFile);
        if (!outputFile.getParentFile().exists()) {
            boolean mkdirs = outputFile.getParentFile().mkdirs();
            if (mkdirs == false) {
                throw new RuntimeExceptionOwn("目录" + outputFile.getParentFile().getPath() + "创建失败");
            }
        }

        connection.connect();
        // convert
        DocumentConverter converter = new OpenOfficeDocumentConverter(
                connection);
        converter.convert(inputFile, outputFile);
        // close the connection
        return 0;
    } catch (ConnectException e) {
        log.error("error:" + e);
    } finally {
        connection.disconnect();// 如果发生异常,系统也会切断连接
    }
    return 1;
}


private void initParameters() {
    Properties pro
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值