使用onlyoffice让你轻松实现word、ppt、excel在线编辑功能

一、了解onlyoffice

ONLYOFFICE Docs是一个开源办公套件,包括文本文档、电子表格和演示文稿的编辑器。它提供以下功能:

1、创建、编辑和查看文本文档、电子表格和演示文稿;

2、与其他队友实时协作处理文件;

3、ONLYOFFICE Docs 还支持用于将您的应用程序与在线办公室集成的WOPI 协议。

二、前提准备

搭建安装onlyoffice,具体参考官网地址:

https://helpcenter.onlyoffice.com/installation/docs-developer-install-ubuntu.aspx?from=api_csharp_example

三、开发进行中

1、准备一个接口返回config配置文件。

@GetMapping("/config/{fileId}")
@ApiOperation("返回配置信息")
public String getConfig(ModelMap map,@PathVariable String fileId){
    //具体业务处理省略
    //主要是获取一些信息,用于设置html中的脚本对象config上。
    //4、设置视图数据:a、文件类型。b、用户信息。c、文件信息。
    map.addAttribute("docType",documentType);
    map.addAttribute("user",user);
    map.addAttribute("fileManager",fileManager);    //将html页面返回回去
    return "onlineEdit";
}

2、准备一个callback接口用于文件保存。

@PostMapping("/saveFile/{fileId}/{fileCode}")
@ApiOperation("在线编辑保存回调接口")
@ResponseBody
public void saveFile(HttpServletRequest request , HttpServletResponse response, @PathVariable String fileId, @PathVariable String fileCode) throws IOException {
    PrintWriter writer = response.getWriter();
    Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
    String body = scanner.hasNext() ? scanner.next() : "";
    JSONObject jsonObject = JSONObject.parseObject(body);
    System.out.println(jsonObject);
    //status等于2时表示已经准备好保存
    if((Integer) jsonObject.get("status") == 2){
      //2、根据返回的Url去下载文件
      URL url = new URL((String) jsonObject.get("url"));
      java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
      InputStream stream = connection.getInputStream();
      //此处获取到的流即是onlyoffice服务下的文件流。
      //3、重新上传业务省略
      connection.disconnect();
    }
    writer.write("{\"error\":0}");

}

3、准备一个html页面。

<!DOCTYPE html>
<html lang="en" style="height: 100%;">
<head>
    <meta charset="UTF-8">
    <script type="text/javascript" src="https://192.168.53.151:9000/web-apps/apps/api/documents/api.js"></script>
    <script type="text/javascript" language="javascript" >
        var  config = {
            "type": "desktop",
            "mode": "review",
            "documentType": "[[${docType}]]",
            "document": {
                "title": "[[${fileManager.fileName}]]",
                "url": "文件下载地址",
                "fileType": "[[${fileManager.fileType}]]",
                "key": "[[${fileManager.fileManagerId}]]",
                "info": {},
                "permissions": {
                    "comment": true,
                    "copy": true,
                    "download": true,
                    "edit": true,
                    "print": true,
                    "fillForms": true,
                    "modifyFilter": true,
                    "modifyContentControl": true,
                    "review": true,
                    "commentGroups": {}
                }
            },
            "editorConfig": {
                "mode": "edit",
                "callbackUrl": 回调接口保存文件的地址,
                "lang": "zh",
                "createUrl": "",
                "templates": [
                    {
                        "icon": "",
                        "name": "Blank",
                        "url": "http://ip地址/OnlineEditorsExampleJava_war_exploded/EditorServlet?fileExt=docx"
                    },
                    {
                        "icon": "http://ip地址/OnlineEditorsExampleJava_war_exploded/css/img/file_docx.svg",
                        "name": "With sample content",
                        "url": "http://ip地址/OnlineEditorsExampleJava_war_exploded/EditorServlet?fileExt=docx&sample=true"
                    }
                ],
                "user": {
                    "id": "[[${user.userId}]]",
                    "name": "[[${user.username}]]"
                },
                "customization": {
                    "goback": {
                        "url": "http://ip地址/OnlineEditorsExampleJava_war_exploded/IndexServlet"
                    },
                    "forcesave": false,
                    "submitForm": false,
                    "about": true,
                    "feedback": false
                },
                "canCoAuthoring": true,
                "canUseHistory": true,
                "canHistoryClose": true,
                "canHistoryRestore": false,
                "canSendEmailAddresses": false,
                "canRequestEditRights": true,
                "canRequestClose": false,
                "canRename": false,
                "canMakeActionLink": true,
                "canRequestUsers": true,
                "canRequestSendNotify": true,
                "canRequestSaveAs": false,
                "canRequestInsertImage": true,
                "canRequestMailMergeRecipients": true
            },
            "width": "100%",
            "height": "100%",
            "events": {},
            "frameEditorId": "iframeEditor"
        }
        var connectEditor = function () {
            new DocsAPI.DocEditor("placeholder", config);
        };
        if (window.addEventListener) {
            window.addEventListener("load", connectEditor);
        } else if (window.attachEvent) {
            window.attachEvent("load", connectEditor);
        }
    </script>
    <title>在线编辑文档</title>
</head>
<body style="height: 100%; margin: 0;">
<div id="placeholder" style="height: 100%"></div>
</body>
</html>

更加具体的config对象和回调处理接口内容参考官网:

https://api.onlyoffice.com/editors/getdocs

四、测试

当我调用config接口时,打开不同类型的文件,展示返回html页面如下。

10e8237c33fee3903c46fd4b2af893ba.png

b63c798ec38d438cb320f1b29463227b.png

839af4c13f023a4bd845065a0bd6c524.png

‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍‍五、总结

1、要使用onlyoffice去在线编辑不难,主要是掌握config的配置。

2、它的一个工作流程:当我打开在线编辑时,接口设置数据返回html页面,并将数据拼接到config上。接着页面会根据config的url地址去下载源文件,最后将内容展示到html上。最后当我们修改完毕关闭了窗口时,会调用callbackurl的接口进行文件保存。

### 实现在线文档编辑功能的方法 为了构建高效的在线文档编辑平台,可以采用多种技术和框架来满足不同需求。以下是几种常见的技术方案: #### 使用 Java 和 MySQL 构建基础架构 对于希望基于Java生态系统搭建应用的服务提供商来说,可以选择使用Java作为服务器端编程语言,并利用MySQL数据库存储文档内容和其他元数据[^1]。 ```java // 建立与MySQL连接的示例代码片段 String url = "jdbc:mysql://localhost:3306/documentdb"; Connection conn = DriverManager.getConnection(url, username, password); Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * FROM documents"); while (rs.next()){ System.out.println(rs.getString("content")); } ``` 这种组合提供了稳定的数据管理和处理能力,适用于大多数中小型项目的快速开发阶段。 #### 利用 Slate.js 创建富文本编辑器 如果目标是打造一个具有高度自定义特性的前端编辑界面,则Slate.js是一个不错的选择。通过继承`BaseEditor`类并重写特定行为,开发者可以根据实际应用场景灵活调整编辑逻辑[^2]。 ```javascript import { Editor as SlateEditor } from 'slate'; class CustomEditor extends SlateEditor { // 自定义编辑器的行为... } const editorInstance = withReact(new CustomEditor()); ``` 此方法特别适合那些追求极致用户体验的应用程序,在保证性能的同时给予设计师极大的自由度去塑造理想的交互模式。 #### 结合 Yjs 和 Quill 达成实时协作体验 当涉及到多用户间的即时互动时,Yjs库加上Quill编辑组件构成了强有力的技术栈之一。借助前者强大的CRDT算法保障无冲突的操作合并机制;后者则负责呈现美观易用的文字输入环境[^3]。 ```typescript import * as Y from 'yjs'; import QuillBinding from 'quill-yjs'; let ydoc = new Y.Doc(); // 初始化Yjs文档实例 let quill = new Quill('#editor'); // 获取页面中的Quill容器 new QuillBinding(ydoc.getText('shared-text'), quill); // 将两者关联起来 ``` 这套解决方案不仅简化了复杂场景下的同步难题,而且极大地提高了系统的可维护性和扩展性。 #### 集成 ONLYOFFICE 文档服务 针对更广泛的企业级市场或者需要全面办公套件集成的支持者而言,ONLYOFFICE提供了一整套成熟的API和服务接口,允许第三方轻松接入其丰富的特性集,包括但不限于WordExcel以及PPT格式文件的查看、修改等功能[^4]。 ```json { "document": { "fileType": "docx", "key": "some_unique_key_here", "title": "Example Document" }, "info": { "canEdit": true, "userId": "current_user_id" } } ``` 上述JSON配置展示了调用ONLYOFFICE API所需的部分参数设置,具体细节需参照官方文档进一步确认。 综上所述,每种途径都有各自的优势所在,最终选择取决于项目背景和个人偏好等因素综合考量的结果。
评论 18
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT学习小镇

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值