onlyoffice 在线编辑

一、拉取镜像,启动

要使用onlyoffice的在线编辑,需要从docker拉取镜像

onlyoffice/documentserver
docker pull onlyoffice/documentserver

启动onlyoffice

docker run --name onlyoffice -i -t -d -p 8000:80 onlyoffice/documentserver

查看日志
docker logs -f --tail=100 [容器id]

启动后通过ip和设置的端口打开页面查看是否启动成功

二、配置onlyoffice

创建页面,导入api.js

<script type="text/javascript" src="http://192.168.3.19:8000/web-apps/apps/api/documents/api.js"></script>

添加div

<div id="placeholder" style="height: 100%;"></div>

配置如下:需要注意的是,onlyoffice中的配置的地址都是onlyoffice服务能直接访问到的地址,如:http://192.168.2.172:25001/documen/aaa.docx,不能使用127.0.0.1和localhost

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html style="height: 100%;">
<head>
    <title></title>
    <meta name="keywords" content="HTML5 Bootstrap 3 Admin Template UI Theme" />
    <meta name="description" content="Monster Dashboard - Multiskin Premium Admin Dashboard">
    <meta name="author" content="MonsterDashboard">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script type="text/javascript" src="${pageContext.request.contextPath}/static/public/js/jquery/jquery-1.11.1.min.js"></script>
    <script type="text/javascript" src="http://192.168.3.19:8000/web-apps/apps/api/documents/api.js"></script>

    <style type="text/css">

    </style>
</head>
<body style="height: 100%; margin: 0;">
    <div id="placeholder" style="height: 100%;"></div>
</body>
<script>
    (function(){
        //业务id
        var busid="${param.busid}";
        console.log(getRealUrl());
        $.ajax({
            type:"post",
            url:"${pageContext.request.contextPath}/file/getFileByBusId",
            data:{busId:busid},
            success:function(res){
                var data = jQuery.parseJSON(res);
                if(data.list.length>0){
                    var json=data.list[0];
                    editFile(json.id,json.temp1+json.filePath);
                }
            }
        })
function editFile(key,path){
    console.log("path:"+path);
    var fileName=path.substring(path.lastIndexOf("/")+1);
    console.log("fileName:"+fileName);
    var suff=fileName.substring(fileName.lastIndexOf(".")+1);
    console.log("suff:"+suff);
    var documentType="word";
    //跟据后缀判断打开文件类型
    var WORD=["doc", "docm", "docx", "dot", "dotm", "dotx", "epub", "fodt", "fb2", "htm", "html", "mht", "odt", "ott", "pdf", "rtf", "txt", "djvu", "xml", "xps"];
    var CELL=["csv", "fods", "ods", "ots", "xls", "xlsm", "xlsx", "xlt", "xltm", "xltx"];
    var SLIDE=["fodp", "odp", "otp", "pot", "potm", "potx", "pps", "ppsm", "ppsx", "ppt", "pptm", "pptx"];
    if(WORD.indexOf(suff)>-1){
        documentType="word";
    }
    if(CELL.indexOf(suff)>-1){
        documentType="cell";
    }
    if(SLIDE.indexOf(suff)>-1){
        documentType="slide";
    }
    var config={
        "height": "100%",
        "width": "100%",
        "documentType": documentType,//文件类型word,cell,slide
        "lang": "zh-CN",//中文菜单
        //要打开的文档配置
        "document": {
            "fileType": suff, //文件类型(后缀)
            "key": new Date().getTime()+"",//根据key判断打开的文件 
            "title": fileName,//文件名称(不含后缀)
            "url": path//文件路径,必须是onlyoffice服务能直接访问的文件路径
        },
        //编辑配置
        "editorConfig": {
            "lang": "zh-CN",//中文菜单
            "mode": "edit",//编辑模式
            //保存文件的回调
            "callbackUrl": getRealUrl()+"/document/saveOnliOfficeFile?fid="+key,
            "customization":{
                "forcesave":"true",//开启手动保存
                "atuosave":"false", //开启自动保存
            }
        }
    };

    new DocsAPI.DocEditor("placeholder", config);
}
//===========获取基础地址=============
        function getRealUrl(){
            var curWwwPath = window.document.location.href;
            var pathname= window.document.location.pathname;
            var contentPath=pathname.substring(0,find(pathname,"/",1));
            var pos = curWwwPath.indexOf(pathname);
            var localhostPath = curWwwPath .substring(0,pos);
            var real_url = localhostPath+contentPath;//拼接项目基础路径
            return real_url;
        }
        function find(str,cha,num){
            var x=str.indexOf(cha);
            for(var i=0;i<num;i++){
                x=str.indexOf(cha,x+1);
            }
            return x;
        }
        //===========获取基础地址 end=============




    })();
</script>
</html>

三、编写保存接口

上一步的保存文件的接口为/document/saveOnliOfficeFile,在自动保存和手动保存时都会调用

         6 - 文档正在编辑,但当前文档状态已保存,
         7 - 强制保存文档时出错.
       * */
      //关闭后保存
      if (status == 2 || status == 3 ) {
         /*
          * 当我们关闭编辑窗口后,十秒钟左右onlyoffice会将它存储的我们的编辑后的文件,
          * 此时status = 2,通过request发给我们,我们需要做的就是接收到文件然后回写该文件。
          * */
         /*
          * 定义要与文档存储服务保存的编辑文档的链接。
          * 当状态值仅等于2或3时,存在链路。
          * */
         String downloadUri = (String) jsonObj.get("url");
         System.out.println("====文档编辑完成,现在开始保存编辑后的文档,其下载地址为:" + downloadUri);
         //解析得出文件名
         //String fileName = downloadUri.substring(downloadUri.lastIndexOf('/')+1);
         String fileName = request.getParameter("fileName");
         System.out.println("====下载的文件名:" + fileName);

         URL url = new URL(downloadUri);
         java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
         InputStream stream = connection.getInputStream();
         //更换为实际的路径,保存硬盘中
         File savedFile = new File("E:\\onlyoffice\\"+DateTools.getFormatDate("yyyy-MM-dd")+"\\"+fileName);
         try (FileOutputStream out = new FileOutputStream(savedFile)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = stream.read(bytes)) != -1) {
               out.write(bytes, 0, read);
            }
            out.flush();
         }
         connection.disconnect();
      }
      //手动保存时
      if(status == 6){
         /*
          * 当我们关闭编辑窗口后,十秒钟左右onlyoffice会将它存储的我们的编辑后的文件,
          * 此时status = 2,通过request发给我们,我们需要做的就是接收到文件然后回写该文件。
          * */
         /*
          * 定义要与文档存储服务保存的编辑文档的链接。
          * 当状态值仅等于2或3时,存在链路。
          * */
         String downloadUri = (String) jsonObj.get("url");
         System.out.println("====文档编辑完成,现在开始保存编辑后的文档,其下载地址为:" + downloadUri);
         //解析得出文件名
         //String fileName = downloadUri.substring(downloadUri.lastIndexOf('/')+1);
         String fileid = request.getParameter("fid");
         File_Entity fe=fileService.getFileById(fileid);
         String fileName=fe.getFileName();
         String uuidFileName=fe.getUuidFileName();
         String filePath=fe.getFilePath();
         System.out.println("====下载的文件名:" + fileName);

         URL url = new URL(downloadUri);
         java.net.HttpURLConnection connection = (java.net.HttpURLConnection) url.openConnection();
         InputStream stream = connection.getInputStream();
         //保存到原路径中
         File savedFile = new File(BigFileUploadUtil.getBasePath()+"/"+filePath);
         //另存为,保存硬盘中,原文件不变
         //File savedFile = new File("E:\\onlyoffice\\"+DateTools.getFormatDate("yyyy-MM-dd")+"\\"+fileName);
         if (!savedFile.getParentFile().exists()) {
            savedFile.getParentFile().mkdirs();
         }
         try (FileOutputStream out = new FileOutputStream(savedFile)) {
            int read;
            final byte[] bytes = new byte[1024];
            while ((read = stream.read(bytes)) != -1) {
               out.write(bytes, 0, read);
            }
            out.flush();
         }
         connection.disconnect();
      }
   } catch (Exception e) {
      e.printStackTrace();
   }
   /*
    * status = 1,我们给onlyoffice的服务返回{"error":"0"}的信息,
    * 这样onlyoffice会认为回调接口是没问题的,
    * 这样就可以在线编辑文档了,
    * 否则的话会弹出窗口说明
    * */
   JSONObject obj=new JSONObject();
   obj.put("error","0");
   writer.write(JSONObject.fromObject(obj).toString());
       writer.close();
       writer.flush();

}

四、添加中文字体

先删除onlyoffice自带的字体

docker exec -it (容器id) /bin/bash 进入容器删除默认字体
cd /usr/share/fonts/
rm -rf *
cd /var/www/onlyoffice/documentserver/core-fonts/
rm -rf *

将字体cp到容器内

docker cp /home/fonts/(当前字体目录) 容器id:/usr/share/fonts/truetype/custom(目标目录)
//再次进入容器:
docker exec -i -t adb(adb是容器id的前三位) /bin/bash
//执行:
/usr/bin/documentserver-generate-allfonts.sh

执行结束之后,不用重启onlyoffice,清一下浏览器缓存,再查看效果

修改好的字体
最后看一下效果图
在这里插入图片描述

  • 2
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 5
    评论
要在Vue中获取OnlyOffice在线编辑器的HTML,你可以使用OnlyOfficeJavaScript API。以下是一个示例代码: ```javascript // 获取OnlyOffice在线编辑器的HTML function getDocumentContent() { const docEditor = window.documentEditor; docEditor.document.getContent((content) => { console.log(content); // 这里可以将content保存到数据库或者发送到后端服务器 }); } // 在Vue组件中使用 export default { mounted() { // 在组件挂载后,初始化OnlyOffice编辑器 this.initEditor(); }, methods: { initEditor() { const editorElement = this.$refs.onlyOfficeEditor; const editorConfig = { type: 'desktop', document: { fileType: 'docx', url: 'http://your-document-url', }, editorConfig: { callbackUrl: 'http://your-callback-url', }, events: { onDocumentStateChange: (event) => { // 处理文档状态变化的事件 }, }, }; window.documentEditor = new DocsAPI.DocEditor(editorElement, editorConfig); }, getContent() { // 调用getDocumentContent()获取文档内容 getDocumentContent(); }, }, }; ``` 在这个示例代码中,我们首先定义了一个名为`getDocumentContent()`的函数,用于获取OnlyOffice在线编辑器的HTML内容。然后,在Vue组件中,我们通过`initEditor()`方法初始化OnlyOffice编辑器,并且将编辑器实例保存到`window.documentEditor`对象中,以便在其他方法中使用。最后,我们在组件中定义了一个名为`getContent()`的方法,用于在用户点击按钮时调用`getDocumentContent()`方法来获取文档内容。
评论 5
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值