编程开源技术交流,分享技术与知识

网站首页 > 开源技术 正文

Java实现Office文件预览(java预览word)

wxchong 2024-08-18 00:54:37 开源技术 12 ℃ 0 评论

一、核心技术栈:使用开源技术ONLYOFFICE办公套件,官网地址:【ONLYOFFICE API 文档 - 基本概念

二、环境搭建:

本篇使用docker为例进行ONLYOFFICE环境部署,docker安装可自行学习,本文不做介绍

1、拉取镜像

执行以下命令,可自定义拉取的版本,本文使用7.5.1.23版本,默认拉取当前最新镜像

docker pull onlyoffice/documentserver 

2、创建容器

执行以下命令

docker run -i -t -d -p 8013:80 --name documentserver --restart=always -e JWT_ENABLED=false -v /data/onlyoffice/DocumentServer/logs:/var/log/onlyoffice -v /data/onlyoffice/DocumentServer/data:/var/www/onlyoffice/Data -v /data/onlyoffice/DocumentServer/lib:/var/lib/onlyoffice -v /data/onlyoffice/DocumentServer/db:/var/lib/postgresql onlyoffice/documentserver

3、启动演示项目

sudo docker exec 容器id sudo supervisorctl start ds:example

浏览器访问容器8013端口 http://127.0.0.1:8013 即可看到项目演示用首页,如下图:


4、配置域名

https域名代理onlyoffice时需要在location里加如下配置

proxy_redirect http:// $scheme://;
proxy_set_header X-Forwarded-Proto $scheme;

否则会提示

This request has been blocked; the content must be served over HTTPS.

5、可能会遇到的问题

  • Onlyoffice显示文档安全令牌的格式不正确,解决方法,在重启创建命令加上以下参数
-e JWT_ENABLED=false -e USE_UNAUTHORIZED_STORAGE=true -e ONLYOFFICE_HTTPS_HSTS_ENABLED=false
  • Onlyoffice下载文件失败问题

查看日志:docker中对应位置/var/log/onlyoffice/logs/documentserver/converter/out.log,创建容器的时候,已经将此目录挂在到宿主机/data/onlyoffice/DocumentServer/logs,发现出现以下错误

Error: DNS lookup xxx.xxx.xxx.xx(family:undefined, host:undefined) is not allowed. Because, It is private IP address.

解决方法:编辑Onlyoffice配置文件允许私有IP通过,docker中配置文件路径/etc/onlyoffice/documentserver/default.json,修改以下参数

"request-filtering-agent" : {
        "allowPrivateIPAddress": true,
        "allowMetaIPAddress": true
},

也可以在宿主机上将文件复制出来进行编辑,然后再上传至容器

docker cp onlyoffice:/etc/onlyoffice/documentserver/default.json ./
vim default.json
docker cp ./default.json onlyoffice:/etc/onlyoffice/documentserver/default.json

不管用哪一种方式,修改了容器参数,需要重启容器,才能生效;至此ONLYOFFICE环境已经搭建完成

6、JAVA使用ONLYOFFICE预览office文件

JAVA开发一个Controller控制器,请求视图指向目标页面,html编码示例如下

<!DOCTYPE html>
<html lang="zh">

<head>
    <meta charset="UTF-8">
    <title>${title}预览</title>
    <script type="text/javascript" src="${onlyofficeDomain}/web-apps/apps/api/documents/api.js"></script>
    <style>
        html {
            height: 100%;
            width: 100%;
            padding: 0;
            margin: 0;
        }

        body {
            height: 100%;
            width: 100%;
            padding: 0;
            margin: 0;
        }
    </style>
</head>

<body class="full-screen">
<div id="placeholder"></div>

<script language="javascript" type="text/javascript">
    let fileType = '${fileType}';
    let key = '${key}';
    let title = '${title}';
    let url = '${url}';
    let username = '${username}';
    let aliasname = '${aliasname}';
    let type = '${type}';
    /**
     * 预览类型转化
     */
    function getDocumentType(fileType) {
        var ExtsDocument = new Array(".djvu", ".doc", ".docm", ".docx", ".docxf", ".dot", ".dotm", ".dotx", ".epub", ".fb2", ".fodt", ".htm", ".html", ".mht", ".mhtml", ".odt", ".oform", ".ott", ".oxps", ".pdf", ".rtf", ".stw", ".sxw", ".txt", ".wps", ".wpt", ".xml", ".xps");
        var ExtsSpreadsheet = new Array(".csv", ".et", ".ett", ".fods", ".ods", ".ots", ".sxc", ".xls", ".xlsb", ".xlsm", ".xlsx", ".xlt", ".xltm", ".xltx", ".xml");
        var ExtsPresentation = new Array(".dps", ".dpt", ".fodp", ".odp", ".otp", ".pot", ".potm", ".potx", ".pps", ".ppsm", ".ppsx", ".ppt", ".pptm", ".pptx", ".sxi");
        var leixing = "." + fileType;
        if (ExtsDocument.indexOf(leixing.toLowerCase()) > -1) {
            return "word";
        }
        if (ExtsSpreadsheet.indexOf(leixing.toLowerCase()) > -1) {
            return "cell";
        }
        if (ExtsPresentation.indexOf(leixing.toLowerCase()) > -1) {
            return "slide";
        }
    }

    var onDocumentReady = function (event) {
        console.log("onDocumentReady: ", event)
    };

    var onMetaChange = function (event) {
        console.log("onMetaChange: ", event)
        //var title = event.data.title;
        //var favorite = event.data.favorite;
    };
    var onDocumentStateChange = function (event) {
        console.log("onDocumentStateChange: ", event)
        if (event.data) {
            console.log("The document changed");
        } else {
            console.log("Changes are collected on document editing service");
        }
    };
    //alert(getDocumentType(fileType));
    var officeEditor = new DocsAPI.DocEditor("placeholder", {
        "events": {
            "onDocumentReady": onDocumentReady,
            "onMetaChange": onMetaChange,
            "onDocumentStateChange": onDocumentStateChange
        },
        "type": type,
        "document": {
            "fileType": fileType,
            "permissions": {
                "edit": false
            },
            "key": key, //文档的唯一ID
            "title": title+"." + fileType,
            "url": url //地址必须文件服务器能访问到
        },
        "editorConfig": {
            //回调地址,当点击保存时触发,wjbh为数据库的文件标识,可以在回调方法中做业务处理,回调程序的服务器必须能访问到文件服务器
            "callbackUrl": "",
            "lang": "zh-CN", // 中文
            "mode": "view",//查看模式
            //"mode": "edit",//编辑模式
            "customization": { //定制部分允许自定义编辑器界面,使其看起来像您的其他产品,并更改是否存在其他按钮,链接,更改徽标和编辑者所有者详细信息。
                "help": false, //定义是显示还是隐藏“帮助”菜单按钮。默认值为true。
                "hideRightMenu": false, //定义在第一次加载时是显示还是隐藏右侧菜单。默认值为false。
                "autosave": false, //定义是启用还是禁用“自动保存”菜单选项。请注意,如果您在菜单中更改此选项,它将被保存到浏览器的localStorage中。默认值为true。
                "forcesave": true, //定义保存按钮是否显示默认false
                "chat": false, //定义“聊天”菜单按钮是显示还是隐藏;请注意,如果您隐藏“聊天”按钮,则相应的聊天功能也将被禁用。默认值为true。
                "commentAuthorOnly": false, //定义用户是否只能编辑和删除他的评论。默认值为false。
                "comments": true, //定义是显示还是隐藏“注释”菜单按钮;请注意,如果您隐藏“评论”按钮,则相应的评论功能将仅可用于查看,评论的添加和编辑将不可用。默认值为true。
                "compactHeader": false, //定义是否将菜单栏放在在徽标旁边使界面更加紧凑默认false。
                "compactToolbar": false, //定义显示的顶部工具栏类型是完整(false)还是紧凑true。默认值为false 多余菜单将在右侧折叠点击显示。
                "compatibleFeatures": false, //定义仅与OOXML格式兼容的功能的使用。例如,不要在整个文档上使用注释。默认值为false。
                "macros": true, //定义是否将运行文档宏以及可用的宏设置。默认值为true。
                "macrosMode": "warn", //定义是否将运行文档宏。可以采用以下值: disable -根本不运行;enable -自动运行所有宏;warn -警告宏并请求允许运行。默认值为original。
                "plugins": false, //定义是否将启动插件并可用。默认值为true。
                "showReviewChanges": false, //定义在加载编辑器时是否自动显示或隐藏审阅更改面板。默认值为false。
                "spellcheck": true, //定义在加载编辑器时是否自动打开或关闭拼写检查器。拼写检查器仅适用于文档编辑器和演示文稿编辑器。默认值为true。
                "toolbarNoTabs": false, //定义是突出显示顶部工具栏选项卡样式。默认值为false。
                "unit": "cm", //定义在标尺和对话框中使用的度量单位。可以采用以下值:cm -厘米,pt-点,inch -英寸。默认值为厘米(cm)。
                "zoom": 100, //定义以百分比为单位的文档显示缩放值。可以取大于0的值。对于文本文档和演示文稿,可以将此参数设置为-1(使文档适合页面选项)或-2(使文档页面宽度适合编辑器页面)。默认值为100。
                "goback": { //定义“打开文件位置”菜单按钮和右上角按钮的设置。该对象具有以下参数:
                    "blank": true, //在新的浏览器选项卡/窗口(如果值设置为true)或当前选项卡(如果值设置为false)中打开网站。默认值为true,
                    "requestClose": false, //定义如果单击“打开文件位置”按钮,则调用events.onRequestClose事件,而不是打开浏览器选项卡或窗口。默认值为false,
                    "text": "Open file location", //将在“打开文件位置”菜单按钮和右上角按钮(即,而不是“转到文档”)上显示的文本,
                    "url": "" //单击“打开文件位置”菜单按钮时将打开的网站地址的绝对URL ,
                }
                 ,
                "logo": {
                     "image": "http://www.demo.com/logo.png", //可以自定义logo
                     "imageDark": "http://www.demo.com/logo.png", //可以自定义深色logo
                     "url": "https://www.demo.com" //自定义跳转地址,一般可以是官网或者系统地址
                 }
            },
            "user": { //用户信息
                "id": username, //用户ID
                "name": aliasname //用户全名称
            },
            "documentType": getDocumentType(fileType)
            //"documentType": "cell",//表格
            //"documentType": "word",//文档
            // "documentType": "slide",//ppt演示
        }
    });
    //officeEditor.destroyEditor();
</script>
</body>
<style type="text/css">
    .full-screen {
        height: 100%;
        overflow: hidden;
    }
</style>

</html>

预览效果如下




7、注意事项

  • 在配置onlyoffice反向代理时,要用upstream,并且upstream的名字要和server块中的server_name名字保持一致
  • 预览乱码的问题,一般都是缺少字体
  • PDF和图片预览一般建议使用pdf.js

自己使用过程的经验仅供参考,希望可以帮助到大家,谢谢

Tags:

本文暂时没有评论,来添加一个吧(●'◡'●)

欢迎 发表评论:

最近发表
标签列表