WebOffice lets you preview Word, PPT, and Excel documents directly in a browser without needing to download the files.
Scenarios
Corporate knowledge bases or document management systems: Employees can upload files and convert them to a web format for quick viewing. This improves the efficiency and security of information access.
Online education platforms: Teachers and students can view course materials, lecture notes, and assignments in real time. This enhances interaction and the learning experience.
Collaboration and project management tools: Team members can view shared work plans, design drafts, and reports directly in the browser. This improves team collaboration.
Supported file types
File type | File extension |
Word | doc, .dot, .wps, .wpt, .docx, .dotx, .docm, .dotm, .rtf |
PPT | ppt, .pptx, .pptm, .ppsx, .ppsm, .pps, .potx, .potm, .dpt, .dps |
Excel | xls, .xlt, .et, .xlsx, .xltx, .csv, .xlsm, .xltm |
How to use
Prerequisites
In OSS, create a bucket, upload the Office document to the bucket, and attach an Intelligent Media Management (IMM) project to the bucket. The IMM project must be in the same region as the bucket.
Attach a custom domain name to the default domain name of the bucket. Files can be previewed only when accessed through the custom domain name.
NoteIf you are prompted that the domain name is not configured in the miniapp's WebView whitelist, contact the Intelligent Media Management helpdesk through the DingTalk group (ID: 88490020073). The helpdesk will configure the whitelist based on the WeChat trusted domain validation file you provide.
Get a URL to enable preview
Java
Use Java SDK 3.17.4 or later. For installation instructions, see Installation.
package com.aliyun.oss.demo;
import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.*;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.GeneratePresignedUrlRequest;
import java.net.URL;
import java.util.Date;
public class Demo {
public static void main(String[] args) throws Throwable {
// Specify your custom domain name. Example: http://static.example.com.
String endpoint = "http://static.example.com";
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the object. If the object is not in the root directory of the bucket, you must specify the full path.
String objectName = "exampledir/exampleobject.docx";
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to cn-hangzhou.
String region = "cn-hangzhou";
// Create an OSSClient instance.
// When the OSSClient instance is no longer used, call the shutdown method to release resources.
ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
// Note: Set the value to true to enable the CNAME option.
clientBuilderConfiguration.setSupportCname(true);
// Explicitly declare the use of the V4 signature algorithm.
clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
OSS ossClient = OSSClientBuilder.create()
.endpoint(endpoint)
.credentialsProvider(credentialsProvider)
.clientConfiguration(clientBuilderConfiguration)
.region(region)
.build();
try {
// Document processing parameters.
String style = "doc/preview,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60";
// Set the expiration time of the signed URL to 3600 seconds.
Date expiration = new Date(new Date().getTime() + 3600 * 1000L );
GeneratePresignedUrlRequest req = new GeneratePresignedUrlRequest(bucketName, objectName, HttpMethod.GET);
req.setExpiration(expiration);
req.setProcess(style);
URL signedUrl = ossClient.generatePresignedUrl(req);
System.out.println(signedUrl);
} catch (OSSException oe) {
System.out.println("Caught an OSSException, which means your request made it to OSS, "
+ "but was rejected with an error response for some reason.");
System.out.println("Error Message:" + oe.getErrorMessage());
System.out.println("Error Code:" + oe.getErrorCode());
System.out.println("Request ID:" + oe.getRequestId());
System.out.println("Host ID:" + oe.getHostId());
} catch (ClientException ce) {
System.out.println("Caught an ClientException, which means the client encountered "
+ "a serious internal problem while trying to communicate with OSS, "
+ "such as not being able to access the network.");
System.out.println("Error Message:" + ce.getMessage());
} finally {
if (ossClient != null) {
ossClient.shutdown();
}
}
}
}Python
Use Python SDK 2.18.4 or later. For installation instructions, see Installation (Python SDK V1).
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider
# Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
# Specify the bucket name.
bucket = 'examplebucket'
# Specify your custom domain name. Example: https://static.example.com.
endpoint = 'https://static.example.com'
# Specify the general-purpose Alibaba Cloud region ID.
region = 'cn-hangzhou'
# Use the custom domain name to initialize the bucket.
bucket = oss2.Bucket(auth, endpoint, bucket, is_cname=True, region=region)
# Specify the file to process.
key = 'example.docx'
# Specify the expiration time in seconds.
expire_time = 3600
# Construct the processing instruction for online preview.
image_process = 'doc/preview,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60'
# Generate a signed URL with processing parameters.
url = bucket.sign_url('GET', key, expire_time, params={'x-oss-process': image_process}, slash_safe=True)
# Print the signed URL.
print(url)Go
Use Go SDK 3.0.2 or later. For installation instructions, see Install OSS Go SDK.
package main
import (
"context"
"flag"
"log"
"time"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss"
"github.com/aliyun/alibabacloud-oss-go-sdk-v2/oss/credentials"
)
// Define global variables.
var (
region string // Storage region
bucketName string // Bucket name
objectName string // Object name
)
// The init function is used to initialize command line parameters.
func init() {
flag.StringVar(®ion, "region", "", "The region in which the bucket is located.")
flag.StringVar(&bucketName, "bucket", "", "The name of the bucket.")
flag.StringVar(&objectName, "object", "", "The name of the object.")
}
func main() {
// Parse command line parameters.
flag.Parse()
// Check if the bucket name is empty.
if len(bucketName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, bucket name required")
}
// Check if the region is empty.
if len(region) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, region required")
}
// Check if the object name is empty.
if len(objectName) == 0 {
flag.PrintDefaults()
log.Fatalf("invalid parameters, object name required")
}
// Load the default configuration and set the credential provider and region.
cfg := oss.LoadDefaultConfig().
WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
WithRegion(region).
// Specify your custom domain name. Example: http://static.example.com.
WithEndpoint("http://static.example.com").
WithUseCName(true)
// Create an OSS client.
client := oss.NewClient(cfg)
// Generate a presigned URL for GetObject.
result, err := client.Presign(context.TODO(), &oss.GetObjectRequest{
Bucket: oss.Ptr(bucketName),
Key: oss.Ptr(objectName),
// Set document processing parameters.
Process: oss.Ptr("doc/preview,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60"),
}, oss.PresignExpires(10*time.Minute))
if err != nil {
log.Fatalf("failed to get object presign %v", err)
}
log.Printf("request method:%v\n", result.Method)
log.Printf("request expiration:%v\n", result.Expiration)
log.Printf("request url:%v\n", result.URL)
if len(result.SignedHeaders) > 0 {
// If the returned result contains signed headers, include the corresponding request headers when you send a GET request using the signed URL. This prevents inconsistencies that may cause request failures and signature errors.
log.Printf("signed headers:\n")
for k, v := range result.SignedHeaders {
log.Printf("%v: %v\n", k, v)
}
}
}Node.js
Use Node.js SDK 8.0 or later. For installation instructions, see Installation.
const OSS = require("ali-oss");
// Define a function to generate a signed URL.
async function generateSignatureUrl(fileName) {
// Get the signed URL.
const client = await new OSS({
// Specify your custom domain name. Example: http://static.example.com.
endpoint: 'http://static.example.com',
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
accessKeyId: process.env.OSS_ACCESS_KEY_ID,
accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
bucket: 'examplebucket',
// Specify the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set Region to oss-cn-hangzhou.
region: 'oss-cn-hangzhou',
authorizationV4: true,
cname: true
});
// Generate a signed URL that includes document processing parameters.
return await client.signatureUrlV4('GET', 3600, {
headers: {}, // Set the request headers based on the actual request you send.
queries: {
"x-oss-process": "doc/preview,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60" // Add document processing parameters.
}
}, fileName);
}
// Call the function and pass the file name.
generateSignatureUrl('yourFileName').then(url => {
console.log('Generated Signature URL:', url);
}).catch(err => {
console.error('Error generating signature URL:', err);
});
PHP
Use PHP SDK 2.7.0 or later. For installation instructions, see Installation.
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use OSS\Credentials\EnvironmentVariableCredentialsProvider;
// Obtain access credentials from environment variables. Before you run this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are set.
$provider = new EnvironmentVariableCredentialsProvider();
// Specify your custom domain name. Example: http://static.example.com.
$endpoint = "http://static.example.com";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// If the document is in the root directory of the bucket, specify the document name. If the document is not in the root directory, specify the full path of the document. Example: exampledir/example.docx.
$object = 'example.docx';
$config = array(
"provider" => $provider,
"endpoint" => $endpoint,
"signatureVersion" => OssClient::OSS_SIGNATURE_VERSION_V4,
"cname" => true,
"region"=> "cn-hangzhou"
);
$ossClient = new OssClient($config);
// Generate a signed URL that includes processing parameters. The URL is valid for 3600 seconds and can be accessed directly in a browser.
$timeout = 3600;
$options = array(
// Construct the processing instruction for online preview.
OssClient::OSS_PROCESS => "doc/preview,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60");
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("url: \n" . $signedUrl);The following is an example of a generated signed URL:
http://static.example.com/example.docx?x-oss-process=doc%2Fpreview%2Cexport_1%2Cprint_1%2Fwatermark%2Ctext_5YaF6YOo6LWE5paZ%2Csize_30%2Ct_60&x-oss-date=20250122T020741Z&x-oss-expires=3600&x-oss-signature-version=OSS4-HMAC-SHA256&x-oss-credential=LTAI********************%2F20250122%2Fcn-hangzhou%2Foss%2Faliyun_v4_request&x-oss-signature=514ed93accdb80921c4b2897c6147fdb1599308c6457f68ee0ac2f771c7d0312Copy the generated URL, paste it into the address bar of your browser, and press Enter to preview the WebOffice document.
Parameters
Action: doc/preview
The following table describes the parameters.
Parameter | Type | Required | Description |
int | No | Specifies whether to allow printing. Valid values:
| |
copy | int | No | Specifies whether to allow copying. Valid values:
|
export | int | No | Specifies whether to allow exporting to PDF. Valid values:
|
maxpage | int | No | The maximum number of pages to render. The value must be an integer greater than 0. |
watermark | string | No | Watermark parameters. |
text | string | No | The watermark text. The text must be URL-safe Base64 encoded. For more information, see Watermark encoding. We recommend that you use a base64url encoder for encoding. Parent node: watermark |
size | int | No | The font size of the watermark text. The value must be an integer greater than 0. Parent node: watermark |
t | int | No | The transparency of the watermark text. Valid values: 0 to 100. Default value: 100 (opaque). Parent node: watermark |
color | string | No | The color of the watermark text. The value is an RGB color value. Default value: #FFFFFF. Examples: #000000 indicates black, and #FFFFFF indicates white. Parent node: watermark |
rotate | int | No | The clockwise rotation angle of the text. Valid values: 0 to 360. Default value: 0 (no rotation). Parent node: watermark |
type | string | No | The font of the text watermark. The font must be URL-safe Base64 encoded. For more information, see Watermark encoding. We recommend that you use a base64url encoder for encoding. The following fonts are supported:
Parent node: watermark |
Related API operations
The operations described previously are based on API operations. If your program requires a high degree of customization, you can directly initiate REST API requests. To do this, you must manually write the code to calculate the signature. For more information about how to calculate the Authorization common request header, see Signature V4 (recommended).
Preview information
Document to preview: example.docx
Pages to preview: The first 3 pages of the document
Watermark information for preview pages:
Watermark type: Text watermark
Watermark text: Internal Material
Font size: 30
Transparency: 60
Permissions for preview pages: Allow users to copy, export, and print
Processing example
GET /example.docx?x-oss-process=doc/preview,export_1,print_1/watermark,text_5YaF6YOo6LWE5paZ,size_30,t_60 HTTP/1.1
Host: doc-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValuePermissions
By default, an Alibaba Cloud account has all permissions. In contrast, a Resource Access Management (RAM) user or RAM role associated with an Alibaba Cloud account has no permissions by default. The Alibaba Cloud account owner or an administrator must grant permissions to the RAM user or RAM role using a RAM policy or a bucket policy.
API operation | Action | Description |
GetObject |
| Download an object. |
| If you specify the version of an object using versionId when you download the object, you must have the permissions for this action. | |
| If the metadata of an object contains X-Oss-Server-Side-Encryption: KMS when you download the object, you must have the permissions for this action. |
API operation | Action | Description |
None |
| The permissions to use IMM through OSS for data processing. |
API operation | Action | Description |
GenerateWebofficeToken |
| Used to obtain a Weboffice credential. |
RefreshWebofficeToken |
| Used to refresh a Weboffice credential. |
Billing
The WebOffice online preview feature incurs charges for the following items. For more information about pricing, see OSS Pricing and Billable items.
API | Billable item | Description |
GetObject | GET requests | You are charged request fees based on the number of successful requests. |
Outbound traffic over the Internet | If you call the GetObject operation by using a public endpoint, such as oss-cn-hangzhou.aliyuncs.com, or an acceleration endpoint, such as oss-accelerate.aliyuncs.com, you are charged fees for outbound traffic over the Internet based on the data size. | |
Retrieval of IA objects | If IA objects are retrieved, you are charged IA data retrieval fees based on the size of the retrieved IA data. | |
Retrieval of Archive objects in a bucket for which real-time access is enabled | If you retrieve Archive objects in a bucket for which real-time access is enabled, you are charged Archive data retrieval fees based on the size of retrieved Archive objects. | |
Transfer acceleration fees | If you enable transfer acceleration and use an acceleration endpoint to access your bucket, you are charged transfer acceleration fees based on the data size. |
API | Billable item | Description |
GenerateWebofficeToken | DocumentWebofficePreview | You are charged document processing fees based on the number of API calls. Important You are charged for previewing a document online based on the number of times the document is opened for projects created before December 1, 2023, and based on the number of API calls for projects created on and after this date. |
RefreshWebofficeToken |
Notes
WebOffice online preview supports only synchronous processing (the x-oss-process method).
FAQ
Can I preview animations and videos in dynamic PPTs?
Yes, you can. However, the online preview feature supports documents up to 200 MB. Documents that exceed this size limit cannot be accessed.
Can I preview image files?
Not supported.
After I enable CDN, an error is reported when I generate a signed URL for a document: Either the Signature query string parameter or the Authorization header should be specified, not both.
If you enable origin fetch for a private bucket and then use a CDN domain name to access a file in the bucket that is attached to an IMM project, you do not need to provide additional signature information. To resolve this issue, configure the settings as follows:
You must grant the
oss:ProcessImm,imm:GenerateWebofficeToken, andimm:RefreshWebofficeTokenpermissions to the default CDN roleAliyunCDNAccessingPrivateOSSRole.Access the resource using a URL that does not contain signature information.
For example, you can use a URL in the following format to use the online document preview feature: http://cdn.example.info/demo.ppt?x-oss-process=doc/preview,export_1,print_1