java openOffice实现局域网内在线预览(docx转pdf)

前言

当前的主浏览器都支持直接打开pdf文件,从而实现文件预览。如果是其他格式文件则得下载,因此用openOffice实现文件转pdf格式。

一、 openOffice的安装

  1. 下载地址:http://www.openoffice.org/
    安装教程可参考:openOffice下载和安装

  2. 进入安装目录,输入cmd
    安装路径

  3. 命令窗口输入以下命令启动:
    soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" –nofirststartwizard

二、测试

  1. 导包
    <!--openoffice-->
        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.1</version>
        </dependency>
  1. 文件工具类
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.StreamOpenOfficeDocumentConverter;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLConnection;

/**
 * 文件格式转换工具类
 *
 * @author Simon
 * @version 1.0
 * @since JDK1.8
 */
public class FileConvertUtil {
    /** 默认转换后文件后缀 */
    private static final String DEFAULT_SUFFIX = "pdf";
    /** openoffice_port */
    public static final String DEFAULT_HOST = "127.0.0.1";
    private static final Integer OPENOFFICE_PORT = 8100;
 
    /**
     * office文档转换为PDF(处理本地文件)
     */
    public static InputStream convertLocaleFile(String sourcePath, String suffix) throws Exception {
        File inputFile = new File(sourcePath);
        InputStream inputStream = new FileInputStream(inputFile);
        return covertCommonByStream(inputStream, suffix);
    }
 

    /**
     * office文档转换为PDF(处理网络文件)
     */
    public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
        // 创建URL
        URL url = new URL(netFileUrl);
        // 试图连接并取得返回状态码
        URLConnection urlconn = url.openConnection();
        urlconn.connect();
        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
        int httpResult = httpconn.getResponseCode();
        if (httpResult == HttpURLConnection.HTTP_OK) {
            InputStream inputStream = urlconn.getInputStream();
            return covertCommonByStream(inputStream, suffix);
        }
        return null;
    }
 
    /**
     *  将文件以流的形式转换
     */
    public static InputStream covertCommonByStream(InputStream inputStream, String suffix) throws Exception {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        OpenOfficeConnection connection = new SocketOpenOfficeConnection(OPENOFFICE_PORT);
        connection.connect();
        DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
        DefaultDocumentFormatRegistry formatReg = new DefaultDocumentFormatRegistry();
        DocumentFormat targetFormat = formatReg.getFormatByFileExtension(DEFAULT_SUFFIX);
        DocumentFormat sourceFormat = formatReg.getFormatByFileExtension(suffix);
        converter.convert(inputStream, sourceFormat, out, targetFormat);
        connection.disconnect();
        return outputStreamConvertInputStream(out);
    }
 
    /**
     *  outputStream转inputStream
     */
    public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) throws Exception {
        ByteArrayOutputStream baos=(ByteArrayOutputStream) out;
        return new ByteArrayInputStream(baos.toByteArray());
    }
}
  1. controler层代码
 @PostMapping("/onlinePreview")
    public void onlinePreview(@RequestParam("url") String url, HttpServletResponse response) throws Exception {
        //获取文件类型   根据实际的url截断
        String suffix = url.substring(url.lastIndexOf('.') + 1);
        if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
                && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx") && !suffix.equals("sheet") && !suffix.equals("pdf")) {
            throw new Exception("文件格式不支持预览");
        }
        //我的文件是存在本地上的,该url是为了别的电脑能访问到,再传到这的时候就是解析本地文件了,所以找到我的本地文件路径
        //根据具体情况来,否则会报错
        url=url.replace("192.168.1.125:8765/knowledge/","G:/creo/knowledge/");
       //处理本地文件
        InputStream in = FileConvertUtil.convertLocaleFile(url, suffix);
        OutputStream outputStream = response.getOutputStream();
        //创建存放文件内容的数组
        byte[] buff = new byte[1024];
        //所读取的内容使用n来接收
        int n;
        //当没有读取完时,继续读取,循环
        while ((n = in.read(buff)) != -1) {
            //将字节数组的数据全部写入到输出流中
            outputStream.write(buff, 0, n);
        }
        //强制将缓存区的数据进行输出
        outputStream.flush();
        //关流
        outputStream.close();
        in.close();
    }
  1. 常见异常

java.lang.IllegalArgumentException: inputFormat is null at com.artofsolving.jodconverter.openoffice.converter.AbstractOpenOfficeDocumentConverter.ensureNotNull(AbstractOpenOfficeDocumentConverter.java:113)
这是因为转换07版本及高版本(.docx/.xlsx/.pptx)时,这三种格式不在所支持的文件格式中。

** 解决办法: **
重写BasicDocumentFormatRegistry (一定得在com.artofsolving.jodconverter包下)

package com.artofsolving.jodconverter;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {
    private List documentFormats = new ArrayList();
    public BasicDocumentFormatRegistry() {
    }
    public void addDocumentFormat(DocumentFormat documentFormat) {
        this.documentFormats.add(documentFormat);
    }
    protected List getDocumentFormats() {
        return this.documentFormats;
    }
    public DocumentFormat getFormatByFileExtension(String extension) {
        if (extension == null) {
            return null;
        } else {
            if (extension.indexOf("doc") >= 0) {
                extension = "doc";
            }
            if (extension.indexOf("ppt") >= 0) {
                extension = "ppt";
            }
            if (extension.indexOf("xls") >= 0) {
                extension = "xls";
            }
            String lowerExtension = extension.toLowerCase();
            Iterator it = this.documentFormats.iterator();
            DocumentFormat format;
            do {
                if (!it.hasNext()) {
                    return null;
                }
                format = (DocumentFormat)it.next();
            } while(!format.getFileExtension().equals(lowerExtension));
            return format;
        }
    }
    public DocumentFormat getFormatByMimeType(String mimeType) {
        Iterator it = this.documentFormats.iterator();
        DocumentFormat format;
        do {
            if (!it.hasNext()) {
                return null;
            }
            format = (DocumentFormat)it.next();
        } while(!format.getMimeType().equals(mimeType));
        return format;
    }
}

参考:解决jodconverter 2.2.1 版本不支持docx、xlsx、pptx 转换成PDF格式异常

posted @ 2022-05-10 17:25  素衣黛眉  阅读(649)  评论(0编辑  收藏  举报