Quick Start

Updated at:

Obtain the preview URL and AccessToken for a document. You do not need to specify an iframe element because the JavaScript (JS) file automatically creates an iframe within a custom block element. You can set the AccessToken in the JS file to quickly enable document preview. You can also customize configurations during the preview, such as component status, events, and settings for text and tables.

Important

This document is no longer maintained. Use the new version of Intelligent Media Management.

  • For a comparison between the new and old versions of Intelligent Media Management, see Guide to new and old versions.

  • To start using the document processing features of the new version of Intelligent Media Management, see Quick Start.

How it works

Obtain the preview URL and AccessToken for a document. You do not need to specify an iframe element. The JS file automatically creates an iframe within a custom block element. Set the AccessToken in the JS file to quickly enable document preview.

fig_IMM_preview001

Preparations

If the domain name of the Object Storage Service (OSS) bucket that you access is different from the domain name of the preview engine, you must add the preview service domain name to the cross-origin access list of the bucket that stores the converted documents. You can perform this action in the OSS console. For more information, see Configure cross-origin access.

Workflow

  1. Upload the source document to Object Storage Service (OSS). For more information, see Upload files.

  2. Encapsulate the GetWebofficeURL and RefreshWebofficeToken APIs on the server side.

  3. Use the JS software development kit (SDK) to mount the returned preview URL to an HTML block element and set the AccessToken.

Usage

Step 1: Encapsulate APIs on the server side

Encapsulate the GenerateWebofficeToken - Get Web Office credential and RefreshWebofficeToken - Refresh Web Office credential APIs on the server side. This allows the frontend to call them directly to obtain the editing URL and AccessToken. The following example shows how to encapsulate the APIs. The project name is immtest and the OSS file path is oss://bucket1/1.docx.

  1. Call the GenerateWebofficeToken - Get Web Office credential API to obtain the collaboration URL.

    • Request sample

      {
          "ProjectName": "immtest", // The IMM project name.
          "SourceURI": "oss://bucket1/1.docx", // The URI of the OSS file.
          "Filename": "1.docx", // The file name.
          "UserData": "{\"fid\": \"123\"}", // The user data. This data is returned as is in MNS notifications.
          "PreviewPages": 3, // The number of pages to preview.
          "Permission": "{\"Rename\": \"true\", \"Readonly\": \"false\"}", // The permissions.
          "User": "{\"Id\": \"test\", \"Name\": \"testuser\", \"Avatar\": \"http://xx.com/avatar.jpg\"}", // The user information displayed for online collaboration.
          "Watermark": "{\"Type\": \"1\", \"Value\": \"imm\"}" // The watermark.
      }
    • Response sample

      {
          "RefreshToken": "f1fd1afd79ee445f95d3dd99f34f35ffv3",
          "RequestId": "BC63D209-5E53-00E9-8D24-7043943DBC89",
          "AccessToken": "3de242da81e1433abefbbea000aaae39v3",
          "RefreshTokenExpiredTime": "2022-07-06T23:18:52.856132358Z",
          "WebofficeURL": "https://office-cn-shanghai.imm.aliyuncs.com/office/w/7c1a7b53d6a4002751ac4bbaea69405a01475f4a?_w_tokentype=1",
          "AccessTokenExpiredTime": "2022-07-05T23:48:52.856132358Z"
      }
    • Complete sample code (Python SDK v1.27.3)

      # -*- coding: utf-8 -*-
      
      from alibabacloud_imm20200930.client import Client as imm20200930Client
      from alibabacloud_tea_openapi import models as open_api_models
      from alibabacloud_imm20200930 import models as imm_20200930_models
      from alibabacloud_tea_util import models as util_models
      from alibabacloud_tea_util.client import Client as UtilClient
      
      
      class Sample:
          def __init__(self):
              pass
      
          @staticmethod
          def create_client(
              access_key_id: str,
              access_key_secret: str,
          ) -> imm20200930Client:
              """
              Use the AccessKey ID and AccessKey secret to initialize the client.
              @param access_key_id:
              @param access_key_secret:
              @return: Client
              @throws Exception
              """
              config = open_api_models.Config(
                  # Your AccessKey ID.
                  access_key_id=access_key_id,
                  # Your AccessKey secret.
                  access_key_secret=access_key_secret
              )
              # The endpoint.
              config.endpoint = f'imm.cn-shenzhen.aliyuncs.com'
              return imm20200930Client(config)
      
          @staticmethod
          def main() -> None:
              # The AccessKey ID and AccessKey secret for IMM. Read them from a configuration file.
              imm_access_key_id = "AccessKeyId"
              imm_access_key_secret = "AccessKeySecret"
              client = Sample.create_client(imm_access_key_id, imm_access_key_secret)
              # Set the watermark.
              weboffice_watermark = imm_20200930_models.WebofficeWatermark(
                  type=1,
                  value='imm'
              )
              # The user information for collaboration.
              weboffice_user = imm_20200930_models.WebofficeUser(
                  id='test',
                  name='testuser',
                  avatar='http://xx.com/avatar.jpg'
              )
              # Set the permissions.
              weboffice_permission = imm_20200930_models.WebofficePermission(
                  rename=True
              )
              get_weboffice_urlrequest = imm_20200930_models.GenerateWebofficeTokenRequest(
                  # The IMM project name.
                  project_name='immtest',
                  # The URI of the file for collaboration.
                  source_uri='oss://bucket1/1.docx',
                  # The file name.
                  filename='1.docx',
                  # The user data.
                  user_data='{"fid": "123"}',
                  preview_pages=3,
                  external_uploaded=False,
                  permission=weboffice_permission,
                  user=weboffice_user,
                  watermark=weboffice_watermark
              )
              runtime = util_models.RuntimeOptions()
              try:
                  # Print the return value of the API.
                  response = client.get_weboffice_urlwith_options(get_weboffice_urlrequest, runtime)
                  print(response.body.to_map())
              except Exception as error:
                  # If an error occurs, print the error message.
                  UtilClient.assert_as_string(error.message)
                  print(error)
      
      
      if __name__ == '__main__':
          Sample.main()
  2. Call the RefreshWebofficeToken - Refresh Web Office credential API to refresh the AccessToken.

    The AccessToken is time-sensitive. When an AccessToken expires, the frontend must call the RefreshWebofficeToken API to obtain a new one. You must encapsulate this API on the server side. The response format of this API is the same as that of the GenerateWebofficeToken API.

Step 2: Use the frontend JS SDK

Use the JS SDK to mount the returned preview URL to an HTML block element and set the AccessToken.

  1. Import the JS SDK.

    In the example, ${x.y.z} represents the latest version number of the JS SDK. Replace it with the actual version number. For the latest version, see Versions.

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
      <meta http-equiv="X-UA-Compatible" content="ie=edge">
      <title>Demo</title>
    </head>
    <body>
      <script src="https://g.alicdn.com/IMM/office-js/${x.y.z}/aliyun-web-office-sdk.min.js"></script>
      <script>
        console.log('You can now use the JS SDK.');
        console.log(aliyun); // The global variable name.
      </script>
    </body>
    </html>
  2. Integrate with WebOffice.

    Obtain the tokenInfo object using the GenerateWebofficeToken API that you encapsulated on the server side.

    Assume that the tokenInfo object has the same structure as the response from the GenerateWebofficeToken API. The following code provides an example where the server-side GenerateWebofficeToken API is available at /getTokenInfo.

    // Get the collaboration URL and AccessToken.
    var tokenInfo = await $.get('http://example.com/getTokenInfo')
     
    let instance = aliyun.config({
      url: tokenInfo.WebofficeURL // Set the document collaboration URL.
    })
    // Set the AccessToken.
    instance.setToken({
      token: tokenInfo.AccessToken
    })
  3. Customize the Office (iframe) mount target.

    Note

    After the DOMContentLoaded event is triggered, make sure the mount node exists before initialization.

    By default, the iframe (#iframe) is mounted to the body. You can customize the mount target for the iframe (#iframe) as needed.

    <div id="container"></div>
    aliyun.config({
      mount: document.querySelector('#container'),
      url: 'Document collaboration URL' // The document collaboration URL from the example in Step 2 (tokenInfo.WebofficeURL).
    })

    To perform special processing on the iframe object, you can use the JS SDK instance object to quickly obtain the iframe's Document Object Model (DOM) object.

    var instance = aliyun.config({
        mount: document.querySelector('#container')
       //...
    })
    console.log(instance.iframe)
  4. Set the token.

    • After you obtain the collaboration URL, you must set a token to enable online collaboration.

    • After each token refresh, you must also use this method to set the new token.

    // Get the token through an asynchronous request or template output as needed.
    var token = 'yourToken'; 
    // Set the token.
    instance.setToken({
      token: token, 
      timeout: 10 * 60 * 1000, // Required. The timeout period for the token, in milliseconds. This example uses 10 minutes. Note: The JS SDK calls the token refresh method 5 minutes before the token expires. Set the timeout to more than 10 minutes (greater than 10 * 60 * 1000 ms) to avoid frequent refreshes.
    }) 
  5. Update the token upon timeout.

    Obtain the tokenInfo object using the RefreshWebofficeToken API that you encapsulated on the server side. Assume that the tokenInfo object has the same structure as the response from the RefreshWebofficeToken API.

    You can pass a function to obtain the token. When the token times out, the JS SDK automatically calls the function to obtain a new token. The function returns a promise or an object.

    In the following example, the endpoint for the server-side GetWebofficeToken interface is /refreshTokenInfo.

    // Cache the previous tokenInfo to refresh the token.
      let lastTokenInfo = tokenInfo
    
    // The function to get the token.
    // Note: refreshToken does not support async. It only supports returning a Promise or a {token, timeout} object.
      const refreshToken = function() {
        return new Promise(function(resolve){
          // Business logic to call the encapsulated refreshToken API on the server side.
          $.get('http://example.com/refreshTokenInfo',{
            RefreshToken: lastTokenInfo.RefreshToken,
            AccessToken: lastTokenInfo.AccessToken,
            //....
          }).then(function(tokenInfo){
            lastTokenInfo = tokenInfo
            resolve({
              token: tokenInfo.AccessToken, // Required.
              timeout: 10 * 60 * 1000, // Required. The timeout period for the token, in milliseconds. Use this with the refreshToken function to get a new token before the current one expires.
            })
          })
        })
      }
    // Configure the function to get a token upon timeout.
    aliyun.config({
      //...
      refreshToken
    })