OpenOffice在线预览(安装与代码实现)

1、Windows安装


双击安装包 打开运行程序 ----> 点击下一步按钮 ----> 点击浏览按钮 选择安装目录路径 -----> 会自动检测系统中的插件 如果需要会自动安装 -----> 输入使用的用户 以及选择用户权限 点击下一步按钮 -----> 勾选通常安装 点击下一步 ----> 点击完成 即安装结束

接下来以命令方式启动OpenOffice服务

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

服务打开成功之后在任务管理器可以看见soffice.bin的进程。


2、Linux安装

2.1、OpenOffice安装及部署

将 Apache_OpenOffice_4.1.5_Linux_x86-64_install-rpm_zh-CN.tar.gz 安装包上传

解压安装包: tar -zxvf Apache_OpenOffice_4.1.5_Linux_x86-64_install-rpm_zh-CN.tar.gz

安装OpenOffice服务

cd zh-CN/RPMS

rpm -ivh *.rpm --force --nodeps

cd desktop-integration

rpm -ivh *.rpm --force --nodeps

2.2、启动OpenOffice服务

放入后台永久运行OpenOffice服务

nohup /opt/openoffice4/program/soffice -headless -accept="socket,host=127.0.0.1,port=8100;urp;" -nofirststartwizard &

查看OpenOffice服务是否已启动

netstat -lnp | grep 8100

netstat -tln

如8100端口未启动(上步操作启动成功则忽略下续操作)

查看OpenOffice错误信息: openoffice4

出现: /opt/openoffice4/program/soffice.bin: error while loading shared libraries: libXext.so.6: cannot open shared object file: No such file or directory

执行: yum install libXext.x86_64

出现: /opt/openoffice4/program/soffice.bin: error while loading shared libraries: libfreetype.so.6: cannot open shared object file: No such file or directory

执行: yum install freetype

出现: no suitable windowing system found, exiting.

执行: yum groupinstall "X Window System"

直至输入openoffice4没有错误提示为止

2.3、OpenOffice格式转换中文乱码(如果预览文件无法识别中文,执行该步骤)

查看jdk安装路径: ls -lrt /etc/alternatives/java

进入jdk安装路径: cd usr/lib/jvm/java-1.8.0-openjdk-1.8.0.212.b04-0.el7_6.x86_64/jre/bin/java

再进入jre/lib目录: cd jre/lib/

创建fonts目录: mkdir fonts

进入该路径: cd fonts

创建fallback目录: mkdir fallback

进入该路径: cd fallback

该路径下上传字体文件simsun.ttc(宋体)、simhei.ttf(黑体)字体文件(如需其他字体支持继续上传

查看系统字体文件路径: cat /etc/fonts/fonts.conf

字体拷贝: 将 usr/lib/jvm/java-1.8.0-openjdk-1.8.0.212.b04-0.el7_6.x86_64/jre/bin/fonts的全部内容,拷贝到系统字体文件路径下(我的字体路径为:/usr/share/fonts)

更新缓存: fc-cache

2.4、重启OpenOffice服务(如果执行了第三步骤,执行该步骤)

 

3、代码实现

/**
     * @param request
     * @param response
     * @param filePath
     * @param fileName
     * @throws IOException
     */
    @Transactional
    @RequestMapping("/preview")
    @ResponseBody
    public AjaxResult preview(HttpServletRequest request, HttpServletResponse response, @RequestParam String filePath, @RequestParam String fileName) throws IOException, InterruptedException {
        // IRequest requestContext = this.createRequestContext(request);
        // ResponseData responseData = new ResponseData();
        response.setContentType("text/html; charset=UTF-8");

        if(!"".equals(filePath)) {
            /* 根据项目所在的服务器环境,确定路径中的 /  和 \ */
            String osName = System.getProperty("os.name");
            if (Pattern.matches("Linux.*", osName)) {
                filePath.replace("\\","/");
            } else if(Pattern.matches("Windows.*", osName)) {
                filePath.replace("/","\\");
            }

            /* 获得文件名后缀 */
            String ext = "";
            if(!"".equals(fileName) && fileName.contains(".")){
                ext = fileName.substring(fileName.lastIndexOf(".") + 1, fileName.length()).toUpperCase();
            }

            /* 根据文件类型不同进行预览 */
            /* 预览图片 */
            if ("PNG".equals(ext) || "JPEG".equals(ext) || "JPG".equals(ext)) {
                response.setContentType("image/jpeg");
            }
            /* 预览BMP格式的文件 */
            if ("BMP".equals(ext)) {
                response.setContentType("image/bmp");
            }
            /* 预览pdf */
            if ("PDF".equals(ext)) {
                response.setContentType("application/pdf");
            }

            /* 利用openOffice将office文件转换为pdf格式, 然后预览doc, docx, xls, xlsx, ppt, pptx */
            if ("DOC".equals(ext) || "DOCX".equals(ext) || "XLS".equals(ext) || "XLSX".equals(ext) || "PPT".equals(ext) || "PPTX".equals(ext)) {
                /* filePath在数据库中是不带文件后缀的, 由于jodConverter必须要识别后缀,所以将服务器中的文件重命名为带后缀的文件 */
                java.io.File docFile = new java.io.File(filePath);
                // File docFileWithExt = new File(filePath + "." + ext.toLowerCase()); //带后缀的文件
                // docFile.renameTo(docFileWithExt);
                /* 转换之后的文件名 */
                java.io.File pdfFile;
                if(filePath.contains(".")){
                    pdfFile = new java.io.File(filePath.substring(0, filePath.lastIndexOf(".")) + ".pdf");
                }else{
                    pdfFile = new java.io.File(filePath + ".pdf");
                }

                /* 判断即将要转换的文件是否真实存在 */
                if (docFile.exists()) {
                    /* 判断该文件是否已经被转换过,若已经转换则直接预览 */
                    if (!pdfFile.exists()) {
                        OpenOfficeConnection connection;

                        /* 打开OpenOffice连接 */
                        try {
                            connection = new SocketOpenOfficeConnection("127.0.0.1",8100);
                            connection.connect();
                        } catch (java.net.ConnectException e) {
                            log.warn("openOffice未连接,正在重新连接...");

                            // 启动OpenOffice的服务
                            String command = openOfficeInstallationPath + "program/soffice -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\" -nofirststartwizard";
                            Runtime.getRuntime().exec(command);

                            Thread.sleep(1000);

                            connection = new SocketOpenOfficeConnection(8100);
                            connection.connect();

                            log.warn("openOffice重新连接成功!!!");
                        }

                        try{
                            // DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
                            DocumentConverter converter = new StreamOpenOfficeDocumentConverter(connection);
                            converter.convert(docFile, pdfFile);
                            connection.disconnect();

                            filePath = pdfFile.getPath(); // 文件转换之后的路径
                            response.setContentType("application/pdf");
                        }catch (com.artofsolving.jodconverter.openoffice.connection.OpenOfficeException e) {
                            e.printStackTrace(); // 读取转换文件失败
                            log.info("读取转换文件失败!!!");
                            return warn("读取转换文件失败!!!");
                        }finally { // 发生exception时, connection不会自动切断, 程序会一直挂着
                            try{
                                if(connection != null){
                                    connection.disconnect();
                                }
                            }catch(Exception e){
                                e.printStackTrace();
                            }
                        }
                    } else {
                        filePath = pdfFile.getPath(); // 文件已经转换过
                        response.setContentType("application/pdf");
                    }
                } else {
                    log.info("需要预览的文档在服务器中不存在!!!");
                    return warn("需要预览的文档在服务器中不存在!!!");
                }
            }

            /* 将文件写入输出流,显示在界面上,实现预览效果 */
            FileInputStream fis = new FileInputStream(filePath);
            OutputStream os = response.getOutputStream();
            try {
                int count;
                byte[] buffer = new byte[1024 * 1024];
                while ((count = fis.read(buffer)) != -1)
                    os.write(buffer, 0, count);
                os.flush();
            } catch (IOException e) {
                e.printStackTrace();
            } finally {
                if (os != null)
                    os.close();
                if (fis != null)
                    fis.close();
            }
        }
        return null;
    }

 

/* 转换文件的核心代码 */
OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(docFile, pdfFile);
connection.disconnect();

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值