Embed Spire.Cloud.Office in Your Web Application

Spire.Cloud.Office is a JavaScript document editor which you can use to create, edit, convert, print, view and save MS Word and Excel documents in a browser on Windows, Linux and Mac. This article demonstrates how to incorporate Spire.Cloud.Office online editor (JavaScript) into a HTML document, so you can run the editor directly in your web application or cloud application.

Step 1. Install Spire.Cloud.Office

Before you can embed the document editor in your HTML file, you’ll need to install Spire.Cloud.Office on your system.

After installation, you can visit our sample file management system and editor on port 3000, and connect to our service via port 8000. In this tutorial, Spire.Cloud.Office is installed on our local server 192.168.0.111.

Step 2. Embed Editor in Your HTML Document

Below is a sample HTML in which our document editor is embedded. You can download it and modify some key parameters in it to run our editor in a HTML page.

<!DOCTYPE html>
<html>
<head runat="server">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" />
    <meta name="apple-mobile-web-app-capable" content="yes" />
    <meta name="mobile-web-app-capable" content="yes" />
    <meta HTTP-EQUIV="pragma" CONTENT="no-cache"/>
    <meta HTTP-EQUIV="Cache-Control" CONTENT="no-cache, must-revalidate"/>
    <meta HTTP-EQUIV="expires" CONTENT="0">
    <title>Spire.Cloud</title>
	<style>
	
html {
    height: 100%;
    width: 100%;
}

body {
    background: #fff;
    color: #333;
    font-family: Arial, Tahoma,sans-serif;
    font-size: 12px;
    font-weight: normal;
    height: 100%;
    margin: 0;
    overflow-y: hidden;
    padding: 0;
    text-decoration: none;
}
iframe {
    border: none !important;
}

.form {
    height: 100%;
}

div {
    margin: 0;
    padding: 0;
}

	</style>
</head>
<body>
<div class="form">
    <div id="iframeEditor">
    </div>
</div>
    <script type="text/javascript" src="http://192.168.0.118:8000/web/editors/spireapi/SpireCloudEditor.js"></script>
    <script type="text/javascript" language="javascript">
        var docEditor;
        var config = {
  "fileAttrs": {
    "fileInfo": {
      "name": "sample.docx",
      "ext": "docx",
      "primary": String(new Date().getTime()),//this is key
      "creator": "Jonn",
      "createTime": "2022-04-18 11:30:43"
    },
	/*Open your document from sourceUrl*/
    "sourceUrl": "https://cloud.e-iceblue.cn/demo/sample.docx",
    "createUrl": "http://192.168.0.118:3000/open", 
    //"callbackUrl": "http://192.168.0.118:3000/save?filename=new%20(1).docx&useraddress=__ffff_192.168.0.118",   
	/*This item can be empty, but only if the 'onSave' callback function must be defined in events. If the callback function is undefined and this item is empty, Cloud Editor will not provide save function. */
    "verification": "",
    "templates": {}
  },
  "user": {
    "id": "uid-1",
    "name": "Jonn",
    "canSave": true,
    "customization" : {
      "public": { 
        "common": {
          "whiteLabel": false,
          "defaultZoom": 1,
          "openReviewChanges": false,
          "viewVersion": false,
          "tokenValue": "",
          "permGroups": ["everyone"],
          "socket_url": "", 
          "header": {
            "hideTitle": false,
            "defaultView": "full"
          },
          "goback": { "url" : "https://www.cloudxdocs.com/cloudwordthirty/" }
        }
      }
    }
  },
  "editorAttrs": {
    "editorMode": "edit",
    "editorWidth": "100%",
    "editorHeight": "100%",
    "editorType": "document", 
    "platform": "desktop", //desktopì mobileì embedded
    "viewLanguage": "en", //en/zh
    "events": {}
  }
}
;
        var innerAlert = function (message) {
            if (console && console.log)
                console.log(message);
        };

        var onAppReady = function () {
        };

        var onDocumentStateChange = function (event) {
            var title = document.title.replace(/\*$/g, "");
            document.title = title + (event.data ? "*" : "");
        };

        var onRequestEditRights = function () {
            location.href = location.href.replace(RegExp("mode=view\&?", "i"), "");
        };

        var onRequestHistory = function (event) {
            var historyObj = null;

            docEditor.refreshHistory(
                {
                    currentVersion: "1",
                    history: historyObj
                });
        };

        var onRequestHistoryData = function (data) {
            var version = data.data;
            var historyData = null;

            docEditor.setHistoryData(historyData[version-1]);
        };

        var onRequestHistoryClose = function (event){
            document.location.reload();
        };

        var onError = function (event) {
            if (event)
                innerAlert(event.data);
        };

        var onOutdatedVersion = function (event) {
            location.reload(true);
        };
        var onDownload = function(props){
            alert('fileName:'+props.data[0]+'fileUrl:'+props.data[1]);
            console.log('fileName:'+props.data[0]);
            console.log('fileUrl:'+props.data[1]);
        };

        var reloadFrame = function(){
            docEditor.reload();
        };

        var connectEditor = function () {
            config.editorAttrs.events = {
                "onReady": onAppReady,
                "onDocumentStateChange": onDocumentStateChange,
                'onRequestEditRights': onRequestEditRights,
                "onError": onError,
                "onRequestHistory":  onRequestHistory,
                "onRequestHistoryData": onRequestHistoryData,
                "onRequestHistoryClose": onRequestHistoryClose,
                "onOutdatedVersion": onOutdatedVersion,
                'onSave': callbackfn
            };
            docEditor = new SpireCloudEditor.OpenApi('iframeEditor', config);
            fixSize();
        };

        var onSaveClick = function () {
            docEditor.onSaveClick();
        }
        
        var callbackfn = function (result) {
		    console.log("save function");
		    if (result && result.data) {
                var data = result.data,
                    fileName = data[0],
                    url = data[1];
                if (fileName.indexOf('=') > -1)
                    fileName = fileName.split('=')[1];
                var host = location.hostname;        
                ajax({
                    url: 'Customize the address of the interface that saves edited document data on the backend',
                    type: 'post',
                    data: { 'filename': fileName, 'fileuri': url },
                    dataType: 'json',
                    async: false,
                    success: function (json) {
                        if (json.code == 200 || json.code == '200') {
                            alert('Save Successfully');
                        } else {
                            this.error(json, 'fail to save');
                        }
                    },
                    error: function (json, msg) {
                        alert(+msg);
                    }
                });
            }
		    };
        
        var fixSize = function () {
            var wrapEl = document.getElementsByClassName("form");
            if (wrapEl.length) {
                wrapEl[0].style.height = screen.availHeight + "px";
                window.scrollTo(0, -1);
                wrapEl[0].style.height = window.innerHeight + "px";
            }
        };

        if (window.addEventListener) {
            window.addEventListener("load", connectEditor);
            window.addEventListener("resize", fixSize);
        } else if (window.attachEvent) {
            window.attachEvent("onload", connectEditor);
            window.attachEvent("onresize", fixSize);
        }
		
    </script>
</body>
</html>

Key Parameters

Parameter Description Optional value range
fileAttrs
fileInfo The information of the file
name The name of the document Cannot be null
ext The suffix of the document docx, xlsx,
primary This is the key Cannot be null, must be set value.
creator The author of the document Can be null
createTime The date Can be null
sourceUrl URL Cannot be null and access rights must be ensured.
createUrl URL
callbackUrl Callback URL Can be null. But if you need to use the save function, you must define callback URL.
templates The template of the document Can be null
user User Cannot be null
Id Your id Can be null
name Your Name Can be null
canSave The save rights of the user The default value is True. When it is false, the document cannot be saved.
customization Customize options
public
common
whiteLabel Whether to display the logo The default value is false. When it is true, the logo will be hided.
defaultZoom Zoom level 1
OpenReviewChagnes Whether to track changes The default value is false. When it is true, the changes will be displayed.
viewVersion The setting of view The default value is False. When it is true, the document cannot be saved.
permGroups The user groups to edit document everyone
socket_url URL Can be null.
header
hideTitle Whether to hide the title The default value is false. When it is true, the title will be hided.
defaultView The default view style full
goback URL Can be null
editorAttrs
editorMode Editor type Cannot be null, must be set to "edit" or "view"
editorWidth Editor width Can be null, 100% by default.
editorHeight Editor height Can be null, 100% by default.
editorType Document type
Must be set to "document" or "spreadsheet"
platform desktop, mobile, or embedded Cannot be null, must be set to "desktop", "mobile", or "embedded".
viewLanguage Language Can be null. "en" or "zh". If it is null, the default language is the same as browser.
events Events "onReady", "onDocumentStateChange", "onRequestEditRights", "onError", "onOutdatedVersion"
"onSave"