OnlyOffice集成到Vue与Spring项目

Posted on 2026-03-03 16:59  笔名钟意  阅读(1)  评论(0)    收藏  举报

基础环境

  • 需安装依赖:@onlyoffice/document-editor-vue
  • 需自行搭建OnlyOffice服务:https://office.thatcoder.cn/ (仅供测试使用,请勿用于生产环境,随时可能关闭)
  • 补充:搭建OnlyOffice要开启ssl按官方的比较麻烦,可以移步底下目录有解锁版,调教了配置。

简单使用

一口吃不成胖子,先从最简单的DEMO,来测试所用服务的可靠性。

测试的DEMO,仅需要替换以下变量即可跑通测试。

  • documentSite:自行搭建的OnlyOffice服务地址。可用 https://office.thatcoder.cn/ 进行测试。
  • documentUrl: DOCX文档地址。
<template>
	<DocumentEditor
	    id="docEditor"
	    :documentServerUrl="documentSite"
	    :config="editorConfig"
	    :events_onDocumentReady="onDocumentReady"
	/>
</template>

<script setup>  
import {ref} from "vue";  
import { DocumentEditor } from '@onlyoffice/document-editor-vue';  
import axios from "axios";  

// DOCX文档地址
const documentUrl = ref('https://resumes.thatcdn.cn/public/template/resumes_001.docx'); 
const documentTitle = ref('论Vue如何使用OnlyOffice');
const documentType = ref('docx');  
// 文档标识符
const documentKey = ref('your-document-key');
// 私有化的OnlyOffice地址
const documentSite = 'https://office.thatcoder.cn/'
// Vue处理OnlyOffice事务的回调地址
const documentCallSite = 'https://www.baidu.com/'

// 文档加载完毕的回调
const onDocumentReady = () => {  
  console.log('Document is ready');  
};  
// 文档变更的回调
const onDocumentStateChange = (event) => {  
  if (event.data === 'onDocumentStateChange') {  
    saveDocument();  
  }  
};  

// 处理文档另存为的回调事件
const onRequestSaveAs = (event) => {  
  console.log('Document save as requested');  
  // 执行文档另存为的逻辑,例如弹出保存对话框等  
};  

// 插入图片的回调事件
const onRequestInsertImage = (event) => {    
  console.log('Insert image requested');  
  // 执行插入图片的逻辑,例如打开图片选择器等  
};  

// 文档保存回调方法
const saveDocument = () => {  
  axios.post('https://www.baidu.com/save-document', {  
    documentUrl: documentUrl.value,  
    documentType: documentType.value,  
    documentKey: documentKey.value,  
  })  
      .then(response => {  
        console.log('Document saved successfully');  
      })  
      .catch(error => {  
        console.error('Document save error:', error);  
      });  
};

// 初始化OnlyOffice
const editorConfig = ref({  
  document: {  
    title: documentTitle.value,  
    url: documentUrl.value,  
    fileType: documentType.value,  
    key: documentKey.value,  
  },  
  editorConfig: {  
    mode: 'edit',  
    lang: 'zh',  
    callbackUrl: documentCallSite,  
  },  
  events: {  
    onReady: onDocumentReady,  
    onDocumentStateChange: onDocumentStateChange,  
    onRequestSaveAs: onRequestSaveAs,  
    onRequestInsertImage: onRequestInsertImage,  
    // 添加其他需要处理的回调事件  
  },   
});  
</script>

配置参数

Config提供了大量配置,不过社区版支持的参数不是特别多。

const editorConfig = ref({  
  editorConfig: {  
    mode: 'edit',  
    lang: 'zh',  
    customization: {  
      anonymous: {  
        request: true,  
        label: "Guest"  
      },  
      autosave: false,  
      comments: true,  
      compactHeader: true,  
      compactToolbar: false,  
      compatibleFeatures: true,  
      customer: {  
        address: "A small corner of China",  
        info: "A member of the open source spirit of the Internet",  
        logo: "https://resume.app.thatcoder.cn/favicon.ico",  
        logoDark: "https://resume.app.thatcoder.cn/favicon.ico",  
        mail: "thatcoder@163.com",  
        name: "钟意",  
        phone: 13305374721,  
        www: "https://blog.thatcoder.cn"  
      },  
      forcesave: false,  
      goback: {  
        blank: true,  
        requestClose: false,  
        text: "回到简历列表",  
        url: "https://resume.app.thatcoder.cn/mine/folder"  
      },  
      help: false,  
      hideRightMenu: false,  
      hideRulers: true,  
      integrationMode: "embed",  
      logo: {  
        image: "https://resume.app.thatcoder.cn/favicon.ico",  
        imageDark: "https://resume.app.thatcoder.cn/favicon.ico",  
        imageEmbedded: "https://resume.app.thatcoder.cn/favicon.ico",  
        url: "https://resume.app.thatcoder.cn"  
      },  
      macros: true,  
      macrosMode: "禁用",  
      mentionShare: false,  
      mobileForceView: true,  
      plugins: false,  
      toolbarHideFileName: true,  
      toolbarNoTabs: true,  
      // uiTheme: "theme-dark",  
      unit: "厘米",  
      zoom: 100  
    },  
    // callbackUrl: 'https://resume.app.thatcoder.cn/onlyoffice-callback',  
    callbackUrl: 'https://resume.thatapi.cn/office/callback',  
  },  
  document: {  
    title: documentName,  
    url: documentUrl,  
    fileType: documentType,  
    key: documentKey,  
    info: {  
      favorite: false,  
      folder: "" + thatLocal.getItem('userId'),  
      owner: "" + thatLocal.getItem('userName'),  
      sharingSettings: [  
        {  
          permissions: "Full Access",  
          user: "" + thatLocal.getItem('userName')  
        }  
      ],  
      uploaded: "2010-07-07 3:46 PM"  
    }  
  },  
  events: {  
    onReady: onDocumentReady,  
    // onDocumentStateChange: onDocumentStateChange,  
    onRequestSaveAs: onRequestSaveAs,  
    // onRequestInsertImage: onRequestInsertImage,  
    // 添加其他需要处理的回调事件  
  },  
  // documentServerUrl: 'https://office.thatcoder.cn', // 指定 ONLYOFFICE 服务器的网址  
});

回调服务

回调服务是指OnlyOffice与你的服务端的通讯地址,主要用于处理文档的保存、另存为等事件。
这里实例用spring演示,仅供参考,逻辑部分请自行编写。
建议边参考官方文档看代码。ONLYOFFICE API 文档 - 回调处理程序

package cn.onestack.project.office.controller;

import cn.hutool.json.JSONObject;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;

@RestController
@RequestMapping("/office")
public class OfficeCallbackDemoController {

    private static final String SAVE_DIRECTORY = "/path/to/save/directory"; // 替换为你的保存路径

    @RequestMapping("/callback")
    public void callback(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter writer = response.getWriter();

        Scanner scanner = new Scanner(request.getInputStream()).useDelimiter("\\A");
        String body = scanner.hasNext() ? scanner.next() : "";

        JSONObject jsonObj = new JSONObject(body);
        System.out.println(jsonObj);

        if(jsonObj.getInt("status") == 2)
        {
            System.out.println("Office文档可保存");
        }
        else if(jsonObj.getInt("status") == 1)
        {
            System.out.println("Office文档已连接");
        }
        else if(jsonObj.getInt("status") == 4){
            System.out.println("Office文档已断开");
        }
        System.out.println(jsonObj);
        writer.write("{\"error\":0}");
    }
}

社区解锁版

镜像地址

出自oo中文交流群,企鹅群号 186184848。

  • 国内地址1:docker pull registry.cn-hangzhou.aliyuncs.com/186184848/documentserver
  • 国内地址2:docker pull registry.cn-hangzhou.aliyuncs.com/miiror/only-office:v8.0.1
  • DockerHub:docker pull 186184848/documentserver

修改说明

  • 基于docker镜像制作,最新版本号: 8.0.1
  • 关闭地址过滤,导入镜像后可以完美通过IP局域网运行(在7.4以上版本默认无法通过IP访问)
  • 去除最大在线编辑人数限制
  • 完美解锁手机端浏览和编辑(无需设置手机UA为电脑模式)
  • 添加中文字体,加入了常用的十几种字体
  • 支持http/https快速部署(默认开启ssl非常繁琐)
  • 优化文档打开速度(进一步优化,打开速度提升20%)
  • 最大支持300M文档在线编辑(7.5以上新增)(默认30M)。
  • 关闭SSL证书校验,自签证书也可以直接使用了。(7.6新增)

使用说明

镜像包含amd64,arm64架构
运行镜像遇到启动不起来问题报端口错误需要加上命令:--privileged=true
相关教程文档请参考:《从零使用onlyoffice及各类网盘》

插件扩展

未来写吧,有需要的可以参考官方文档。