Java office在线预览实现--openoffice

Java office在线预览实现–openoffice

本篇主要介绍用openoffice来实现office文档转换为pdf,从而方便在线预览。
首先去下载安装openoffice;
然后启动服务,这是启动命令:

cd C:\Program Files (x86)\OpenOffice 4\program 
soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;"

如果项目和该服务不在同一台机器上,ip地址设为该服务启动机器的地址
需要用到的jar包:

 <dependency>
     <groupId>com.artofsolving</groupId>
     <artifactId>jodconverter</artifactId>
     <version>2.2.1</version>
 </dependency>

代码:

/**  
 * 方法示例:
 * String sourcePath = "F:\\office\\source.doc";
 * String destFile = "F:\\pdf\\target.pdf";
 * office2PDF(sourcePath, destFile);
*/
    public static void office2PDF(String infile, String targetfile)throws Exception {
        // 获得文件格式
        DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
        DocumentFormat pdfFormat = formatReg.getFormatByFileExtension("pdf");//目标文件格式
        DocumentFormat Format;
        String[] p = infile.split("\\.");
        String postfix = p[p.length-1].substring(0,3);
        //原文件格式包括doc,docx,xls,xlsx,ppt,pptx
        Format = formatReg.getFormatByFileExtension(postfix);
        InputStream inputStream = new FileInputStream(infile);
        OutputStream outputStream = new FileOutputStream(targetfile);
        OpenOfficeConnection connection = new SocketOpenOfficeConnection("127.0.0.1", 8100);//如果项目不在该服务所在机器,将ip改为openoffice安装的机器地址
        try {
            connection.connect();
            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
            converter.convert(inputStream,Format, outputStream, pdfFormat);
            outputStream.flush();
            outputStream.close();
            inputStream.close();
        } catch (ConnectException e) {
            e.printStackTrace();
        }finally {
            if(connection!=null){
                connection.disconnect();
                connection = null;
            }
        }
    }

在转换成功后,有可能生成的pdf文件会出现字体不一致的问题,主要是office 文档所用字体,本机系统中没有,所以需要下载新的字体到本机,window是在c盘window下的font文件夹。目前存在的一个问题是转换速度较慢。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值