在工作中遇到一个问题,实现word文档的在线预览,网上有很多种方法,我选择的是使用openOffice下载,分享一下我在实现功能中遇到的问题,用于记录也希望帮到别人。

OpenOffice下载

官网下载链接:http://www.openoffice.org/download/

opennlp 下载模型 opendocument下载_servlet

 由于官网是外网下载的比较慢,我这里分享出来我的网盘下载地址,需要的朋友可以下载使用。

百度网盘下载地址:https://pan.baidu.com/s/1Ko-DGEvH2mKET8p4S4xd4Q

提取码:byan

OpenOffice安装

无脑下一步就行了。下载完以后会在桌面有个快捷方式,右击属性查看路径

默认路径为"C:\Program Files (x86)\OpenOffice 4\"

opennlp 下载模型 opendocument下载_opennlp 下载模型_02

 进入到目录里启动打开cmd命令行启动openoffice服务

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

openOffice使用

在pom文件中添加依赖,说一下遇见的问题 jodconverter 这个jar包目前maven仓库里只有2.2.1,2.2.1这个版本的jar包在转换docx,pptx,xlsx三种拓展名文件时,不支持会报错。具体原因和解决方法我会在下面说明。

<!--openoffice-->
        <dependency>
            <groupId>com.artofsolving</groupId>
            <artifactId>jodconverter</artifactId>
            <version>2.2.1</version>
        </dependency>
        <!-- jxls poi -->
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-ooxml</artifactId>
            <version>3.17</version>
        </dependency>
        <dependency>
            <groupId>org.apache.poi</groupId>
            <artifactId>poi-scratchpad</artifactId>
            <version>3.17</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/net.sf.jxls/jxls-core -->
        <dependency>
            <groupId>net.sf.jxls</groupId>
            <artifactId>jxls-core</artifactId>
            <version>1.0.6</version>
        </dependency>

创建工具类FileConvertUtil 

public class FileConvertUtil {

    //    @Value("${baseplatform.file.preview-max-size}")
    private static int previewMaxSize = 100;

    /**
     * 默认转换后文件后缀
     */
    private static final String DEFAULT_SUFFIX = "pdf";
    /**
     * openoffice_port
     */
    private static final Integer OPENOFFICE_PORT = 8100;

    /**
     * 【office文档转换为PDF(处理本地文件) 】
     *
     * @param sourcePath: 源文件路径
     * @param suffix:     源文件后缀
     * @return java.io.InputStream 转换后文件输入流
     */
    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(处理网络文件)】
     *
     * @param netFileUrl: 网络文件路径
     * @param suffix:     文件后缀
     * @return java.io.InputStream 转换后文件输入流
     */
    public static InputStream convertNetFile(String netFileUrl, String suffix) throws Exception {
        // 创建URL
        netFileUrl = getEncodeUrl(netFileUrl).replaceAll("\\+", "%20");
        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();
            //根据响应获取文件大小(M)
            int size = urlconn.getContentLength() / 1024 / 1024;
            if (size > previewMaxSize) {
                throw new HguException(20001,"文件太大,请下载查看");
            }
            return covertCommonByStream(inputStream, suffix);
        }
        return null;
    }


    /**
     * 【将文件以流的形式转换】
     *
     * @param inputStream: 源文件输入流
     * @param suffix:      源文件后缀
     * @return java.io.InputStream 转换后文件输入流
     */
    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】
     *
     * @param out:
     * @return java.io.ByteArrayInputStream
     */
    public static ByteArrayInputStream outputStreamConvertInputStream(final OutputStream out) {
        ByteArrayOutputStream baos = (ByteArrayOutputStream) out;
        return new ByteArrayInputStream(baos.toByteArray());
    }

    /**
     * 【文件压缩】网络文件
     *
     * @param filePath:
     * @param zipOut:
     * @return void
     */
    public static void fileToZip(String filePath, ZipOutputStream zipOut) throws IOException {
        filePath = getEncodeUrl(filePath).replaceAll("\\+", "%20");
        // 需要压缩的文件
        File file = new File(filePath);
        // 获取文件名称,为解决压缩时重复名称问题,对文件名加时间戳处理
        String fileName = FilenameUtils.getBaseName(URLDecoder.decode(file.getName(), "UTF-8")) + "-"
                + String.valueOf(new Date().getTime()) + "."
                + FilenameUtils.getExtension(file.getName());
        InputStream fileInput = getInputStream(filePath);
        // 缓冲
        byte[] bufferArea = new byte[1024 * 10];
        BufferedInputStream bufferStream = new BufferedInputStream(fileInput, 1024 * 10);
        // 将当前文件作为一个zip实体写入压缩流,fileName代表压缩文件中的文件名称
        zipOut.putNextEntry(new ZipEntry(fileName));
        int length = 0;
        // 最常规IO操作,不必紧张
        while ((length = bufferStream.read(bufferArea, 0, 1024 * 10)) != -1) {
            zipOut.write(bufferArea, 0, length);
        }
        //关闭流
        fileInput.close();
        // 需要注意的是缓冲流必须要关闭流,否则输出无效
        bufferStream.close();
        // 压缩流不必关闭,使用完后再关
    }

    /**
     * 【获取网络文件的输入流】
     *
     * @param filePath: 网络文件路径
     * @return java.io.InputStream
     */
    public static InputStream getInputStream(String filePath) throws IOException {
        InputStream inputStream = null;
        // 创建URL
        URL url = new URL(filePath);
        // 试图连接并取得返回状态码
        URLConnection urlconn = url.openConnection();
        urlconn.connect();
        HttpURLConnection httpconn = (HttpURLConnection) urlconn;
        int httpResult = httpconn.getResponseCode();
        if (httpResult == HttpURLConnection.HTTP_OK) {
            inputStream = urlconn.getInputStream();
        }
        return inputStream;
    }

    /**
     * 判断汉字的方法,只要编码在\u4e00到\u9fa5之间的都是汉字,中文符号,空格,+
     *
     * @param c:
     * @return boolean
     */
    public static boolean isChineseChar(char c) {
        return String.valueOf(c).matches("[\u4e00-\u9fa5\u3002\uff1b\uff0c\uff1a\u201c\u201d\uff08\uff09\u3001\uff1f\u300a\u300b\\s\\+]");
    }

    /**
     * 得到中文转码后的 url,只转换 url 中的中文字符
     *
     * @param url:
     * @return java.lang.String
     */
    public static String getEncodeUrl(String url) throws UnsupportedEncodingException {
        String resultURL = StringUtils.EMPTY;
        for (int i = 0; i < url.length(); i++) {
            char charAt = url.charAt(i);
            //只对汉字处理
            if (isChineseChar(charAt)) {
                String encode = URLEncoder.encode(charAt + "", "UTF-8");
                resultURL += encode;
            } else {
                resultURL += charAt;
            }
        }
        return resultURL;
    }

controller层

opennlp 下载模型 opendocument下载_html_03

红框这里的参数根据功能需求自己修改就可以了,因为我是要根据从数据表里查出来的数据填充到word模板中下载下来,然后再转成pdf。 所以我的参数里带了我要从前端获取的id和request。如果有现成的word直接转的话,这里给上url(word的本地路径或者网络路径)也是能用的。response是必带的。

service层

service层里的重要代码就是这些,执行完这些就已经实现功能了。

//word文档路径
            String url = tempDir+filename;
            //获取文件类型
            String[] str = url.split( "\\.");

            if (str.length == 0) {
                throw new Exception("文件格式不正确");
            }
            String suffix = str[str.length - 1];
            if (!suffix.equals("txt") && !suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls")
                    && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("pptx")) {
                throw new Exception("文件格式不支持预览");
            }

            //处理本地文件
            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();

上面提到的问题

关于我在上面提到的问题,jodconverter 2.2.1 这个jar包由于不兼容上面提到的三种文件格式,我从网上搜索了好几种解决方案。

1.使用jodconverter-core 这个jar包 网上可以搜到很多相关的文章,想用这种的小伙伴可以去再找找。

2.重写BasicDocumentFormatRegistry类或者DefaultDocumentFormatRegistry类,我们顺着jar包打开找DefaultDocumentFormatRegistry这个类可以发现里面的21种文件格式当中没有我们需要的docx。我这里截出来一部分这个类中的内容。

opennlp 下载模型 opendocument下载_java_04

 下面标红的两个类重写一个就可以了,路径我放到了我的utils里面,建了两个包。

opennlp 下载模型 opendocument下载_jar包_05

 

BasicDocumentFormatRegistry

opennlp 下载模型 opendocument下载_opennlp 下载模型_06

 下面我把第一种的源码贴过来,第二种的源码我觉得就不用贴了

package com.hgu.utils.artofsolving.jodconverter;

import com.artofsolving.jodconverter.DocumentFormat;
import com.artofsolving.jodconverter.DocumentFormatRegistry;

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

/**
 * @description: 重写 BasicDocumentFormatRegistry 文档格式
 * @Author: wbw
 * @Data: 2022-10-15
 **/
public class BasicDocumentFormatRegistry implements DocumentFormatRegistry {

    private List/* <DocumentFormat> */ documentFormats = new ArrayList();

    public void addDocumentFormat(DocumentFormat documentFormat) {
        documentFormats.add(documentFormat);
    }

    protected List/* <DocumentFormat> */ getDocumentFormats() {
        return documentFormats;
    }

    /**
     * @param extension the file extension
     * @return the DocumentFormat for this extension, or null if the extension
     * is not mapped
     */
    @Override
    public DocumentFormat getFormatByFileExtension(String extension) {
        if (extension == null) {
            return null;
        }

        //将文件名后缀统一转化
        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();
        for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
            DocumentFormat format = (DocumentFormat) it.next();
            if (format.getFileExtension().equals(lowerExtension)) {
                return format;
            }
        }
        return null;
    }

    @Override
    public DocumentFormat getFormatByMimeType(String mimeType) {
        for (Iterator it = documentFormats.iterator(); it.hasNext(); ) {
            DocumentFormat format = (DocumentFormat) it.next();
            if (format.getMimeType().equals(mimeType)) {
                return format;
            }
        }
        return null;
    }
}

DefaultDocumentFormatRegistry

opennlp 下载模型 opendocument下载_java_07

注意!!!,虽然上面上面两个任选一个改动就行,但是另外的一个也要从jar包复制处理到你的目录下。

opennlp 下载模型 opendocument下载_servlet_08

 3.还有一种更简单的方式,但是我目前没在用,测试的时候试了一下,是可以实现功能的,也是最简便的。让我感觉上面的第二种方式基本没有用,只能说在用第二种方法的时候加深了对这几个类的理解。也是有好处的。

直接说第三种方法:

opennlp 下载模型 opendocument下载_java_09

 看图片就懂了,直接if判断了一下,是docx就把它变成doc,这种方法我试了是可以实现功能的,感兴趣的小伙伴可以试一下!