OnlyOffice集成 Document Serve Api简介

Posted by 橙叶 on Mon, Nov 4, 2019

OnlyOffice提供了一系列文档在线编辑工具,这些都依托于Document Server。我之前做过将在Nextcloud上使用OnlyOffice的文章,现在我们来试试单独使用OnlyOffice。

两年多不见,OnlyOffice对中文的支持已经相当不错了。

对OnlyOffice Editor的简单介绍

首先我们需要弄清楚OnlyOffice(Editor)的整体结构。下文中称为Editor,Document Server的地址假定为https://documentserver。

Editor的界面和功能全部由Docuemnt Server提供,前端的静态文件包含了供Editor使用的Div块和对Document Server Api的调用代码。

Document Server提供了一个api.js:https://documentserver/web-apps/apps/api/documents/api.js,这个api.js封装了Document Server Api,使用起来相当方便。通过调用api.js中的DocsApi.docEditor就可以创建一个文档编辑界面。

DocsApi.docEditor有两个参数,第一个参数是放置Editor的div块的id,第二个参数是配置信息。下面是一个示例

...
<header>
    <!-- 引入api.js 注意api.js来自Document Server --!>
    <script type="text/javascript" src="https://documentserver/web-apps/apps/api/documents/api.js"></script> 
</header>
<body>
    <div id="placeholder"></div>
</body>
...

JavaScript部分

... 
var docEditor = new DocsAPI.DocEditor("placeholder", {
     "documentType": "text",
     "height": "100%",
     "token": "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.e30.t-IDcSemACt8x4iTMCda8Yhe3iZaWbvV5XKSTbuAn0M",
     "type": "desktop",
     "width": "100%",     
... });
... 

关于第二个参数的用法,可以在 https://api.onlyoffice.com/editors/advanced 找到。

使用Demo

官方提供了一些前端的demo:https://api.onlyoffice.com/editors/demopreview ,这里以nodejs为例。(假设已经拥有完好的NodeJs环境)

首先下载Node.js版本的Demo,点击NODE.JS EXAMPLE下载。

下载得到zip包,解压后目录如下:

找到config/default.json,修改其中的server.siteUrl字段为你自己的Document Server地址。

 "siteUrl": "https://documentserver/", 

然后npm install安装依赖(根目录下):

出现错误就执行npm audit fix,然后再npm install

然后运行Demo:node ./bin/www

访问Demo,地址:http://demo所在的地址/index.html

如果Document Server和这个Demo在同一个主机,直接访问localhost就行了。否则需要确保Demo的地址能由被Document Server访问。

点击Create Document/Spreadsheet/Presentation即可编辑一个新的文档。

关于Demo

这个Demo可以直接告诉我们怎样使用DocumentServer。

关键的一点在于生成config:

config.ejs

NodeJs的Demo中,通过渲染js内容来生成最终的用于调用DocsApi的参数。

editor.ejs

关于DocsApi的使用,会在以后讲到,就先到这里了。



comments powered by Disqus