All Products
Search
Document Center

Object Storage Service:WebOffice online preview

Last Updated:Jun 14, 2025

For text documents (Word), presentation documents (PPT), and spreadsheet documents (Excel) that cannot be directly previewed in browsers, you can use the WebOffice online preview feature to view document content directly in browsers without downloading the documents.

Scenarios

  • Knowledge bases or document management systems for enterprises: The online document preview feature allows you to preview documents online. This feature improves document access efficiency and security.

  • Online education platforms: By using the online document preview feature, educators and learners can check digital textbooks, documents, and homework in real time, providing a more interactive and engaging experience.

  • Document collaboration and project management tools: Team members can view and share plans, design drafts, and reports directly in web browsers, improving team collaboration efficiency.

Supported file types

File Type

File extension

Word

doc, dot, wps, wpt, docx, dotx, docm, dotm, and rtf

PPT

ppt, pptx, pptm, ppsx, ppsm, pps, potx, potm, dpt, and dps

Excel

xls, xlt, et, xlsx, xltx, csv, xlsm, and xltm

PDF

pdf

How to use

Prerequisites

Generate a URL link for preview

Java

Java SDK 3.17.4 or later is required. For more information about how to install the Java SDK, 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 a custom domain name. Example: http://static.example.com.
        String endpoint = "http://static.example.com";
        // Obtain access credentials from environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket. 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 of the object.
        String objectName = "exampledir/exampleobject.docx";
        // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to cn-hangzhou.
        String region = "cn-hangzhou";
        // Create an OSSClient instance.
        // When you no longer use the OSSClient instance, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // Note: To enable CNAME, set this parameter to true.
        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 validity period of the signed URL to 3600 seconds)
            Date expiration = new Date(new Date().getTime() + 3600 );
            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

Python SDK 2.18.4 or later is required. For more information about how to install the Python SDK, see Installation.

# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

# Obtain access credentials from environment variables. Before you run the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())

# Specify the name of the bucket
bucket = 'examplebucket'

# Specify a custom domain name. Example: https://static.example.com.
endpoint = 'https://static.example.com'

# Specify the ID of the Alibaba Cloud region in which the bucket is located
region = 'cn-hangzhou'

# Initialize the bucket with a custom domain name
bucket = oss2.Bucket(auth, endpoint, bucket, is_cname=True, region=region)

# Specify the file to process
key = 'example.docx'

# Specify the expiration time. Unit: 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

Go SDK 3.0.2 or later is required. For more information about how to install the Go SDK, see Install the 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 the global variables
var (
	region     string // The region.
	bucketName string // The name of the bucket.
	objectName string // The name of the object.
)

// Use the init function to initialize parameters
func init() {
	flag.StringVar(&region, "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 the command line parameters
	flag.Parse()

	// Check whether the bucket name is specified
	if len(bucketName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, bucket name required")
	}

	// Check whether the region is specified
	if len(region) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, region required")
	}

	// Check whether the object name is specified
	if len(objectName) == 0 {
		flag.PrintDefaults()
		log.Fatalf("invalid parameters, object name required")
	}

	// Load the default configurations and specify the credential provider and region
	cfg := oss.LoadDefaultConfig().
		WithCredentialsProvider(credentials.NewEnvironmentVariableCredentialsProvider()).
		WithRegion(region).
        // Specify a 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 signed URL for the GetObject request
	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 {
		// When the result contains signed headers, include the corresponding request headers when sending a GET request using the signed URL to avoid inconsistencies that may lead to 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

Node.js SDK 8.0 or later is required. For more information about how to install the Node.js SDK, see Installation.

const OSS = require("ali-oss");

// Specify a function used to generate a signed URL
async function generateSignatureUrl(fileName) {
  // Obtain the signed URL
  const client = await new OSS({
    // Specify a custom domain name. Example: http://static.example.com.
    endpoint: 'http://static.example.com',
    // Obtain access credentials from environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    accessKeyId: process.env.OSS_ACCESS_KEY_ID,
    accessKeySecret: process.env.OSS_ACCESS_KEY_SECRET,
    bucket: 'examplebucket',
    // Specify the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
    region: 'oss-cn-hangzhou',
    authorizationV4: true,
    cname: true
  });

  // Generate a signed URL with document processing parameters
  return await client.signatureUrlV4('GET', 3600, {
    headers: {}, // Set the request headers based on the actual request headers
    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 in the object name
generateSignatureUrl('yourFileName').then(url => {
  console.log('Generated Signature URL:', url);
}).catch(err => {
  console.error('Error generating signature URL:', err);
});

PHP

PHP SDK 2.7.0 or later is required. For more information about how to install the PHP SDK, 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 a credential from the environment variables. Before you execute the sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$provider = new EnvironmentVariableCredentialsProvider();
//Specify a custom domain name. Example: http://static.example.com.
$endpoint = "http://static.example.com";
// Specify the name of the bucket. Example: examplebucket.
$bucket= "examplebucket";
// If the document is located in the root directory of the bucket, specify the document name. If the document is not located in the root directory of the bucket, you must 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 with processing parameters. The validity period is 3600 seconds. You can directly access the URL 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 sample code provides an example on how to generate a 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=514ed93accdb80921c4b2897c6147fdb1599308c6457f68ee0ac2f771c7d0312

Copy the generated URL and paste it into the address bar of your browser. Press Enter to preview the WebOffice document.

Parameter description

Action: doc/preview

The following table describes the parameters.

Parameter name

Type

Required

Description

print

int

No

Specifies whether the document can be printed. Valid values:

  • 1: allows the document to be printed.

  • 0: does not allow the document to be printed.

copy

int

No

Specifies whether the document can be copied. Valid values:

  • 1: allows the document to be copied.

  • 0: does not allow the document to be copied.

export

int

No

Specifies whether to export the processed file as a PDF file. Valid values:

  • 1: Allowed.

  • 0: does not allow the document to be exported as a PDF file.

maxpage

int

No

The maximum number of rendered pages. The value must be an integer greater than zero.

watermark

string

No

The configurations of the watermark.

text

string

No

The text in the watermark. The value must be a URL-safe, Base64-encoded string. For more information, see Watermark encoding. We recommend that you use base64url encoder for encoding.

Parent nodes: watermark

size

int

No

The font size of the text in the watermark, which must be an integer greater than 0.

Parent nodes: watermark

t

int

No

The opacity of the text in the watermark. Valid values: 0 to 100. Default value: 100 (opaque).

Parent nodes: watermark

color

string

No

The color of the text in the watermark. The value is an RGB color value. Default value: #FFFFFF.

For example, #000000 indicates black, and #FFFFFF indicates white.

Parent nodes: watermark

rotate

int

No

The degree by which the text watermark is rotated clockwise. Valid values: 0 to 360. Default value: 0 (no rotation).

Parent nodes: watermark

type

string

No

The font of the text in the watermark. The value must be a URL-safe, Base64-encoded string. For more information, see Watermark encoding. We recommend that you use base64url encoder for encoding.

The following fonts are supported:

  • Chinese fonts:

    • SimSun (default)

    • KaiTi

  • English fonts:

    • Arial

    • Georgia

    • Tahoma

    • Comic Sans MS

    • Times New Roman

    • Courier New and Verdana

Parent nodes: watermark

Related API operations

If your business requires a high level of customization, you can directly call RESTful APIs. To directly call an API, you must include the signature calculation in your code. For more information about how to calculate the Authorization header, see Signature version 4 (recommended).

Preview information

  • The document to be previewed: example.docx

  • The pages to be previewed: the first three pages

  • Watermark for the preview:

    • Watermark type: text watermark

    • Watermark text: internal data

    • Text font size: 30

    • Watermark opacity: 60

  • Preview page permissions: allows 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: SignatureValue

Permission description

By default, an Alibaba Cloud account has full permissions on resources in the account. RAM users or RAM roles under an Alibaba Cloud account do not have permissions by default. The Alibaba Cloud account or the administrator must grant permissions to RAM users or RAM roles by using RAM Policy or Bucket Policy.

API

Action

Description

GetObject

oss:GetObject

Downloads an object.

oss:GetObjectVersion

Grants the permission to query object versions. This permission is required if you want to download a specific version of an object.

kms:Decrypt

This permission is required if the metadata of the object contains X-Oss-Server-Side-Encryption: KMS when you download the object.

API

Action

Description

None

oss:ProcessImm

Allows the use of data processing capabilities of IMM in OSS.

API

Action

Description

GenerateWebofficeToken

imm:GenerateWebofficeToken

Used to obtain a Weboffice credential.

RefreshWebofficeToken

imm:RefreshWebofficeToken

Used to refresh a Weboffice credential.

Billing

The WebOffice online preview feature incurs the following fees. For more information about the pricing of these billing items, see OSS Pricing and Billing 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 (x-oss-process processing method).

FAQ

Does WebOffice online preview support animations and videos in dynamic PPT files?

Yes, WebOffice online preview supports animations and videos in dynamic PPT files. However, note that the online preview feature supports documents up to 200 MB in size. Documents larger than 200 MB cannot be accessed.

Does WebOffice online preview support image files?

Not supported.

The error message Either the Signature query string parameter or the Authorization header should be specified, not both. is returned when I generate a signed document URL after CDN is enabled

If you enable back-to-origin for a private bucket and access files in the bucket that is bound to an IMM project through a CDN domain name, you do not need to provide additional signature information. Configure the following settings:

  1. Authorize the default role You need to grant the oss:ProcessImm, imm:GenerateWebofficeToken, and imm:RefreshWebofficeToken permissions to the default CDN role AliyunCDNAccessingPrivateOSSRole.

  2. When you access resources, use URLs that do not contain signature information.

    For example, you can use a URL in the following format to use the document online preview feature: http://cdn.example.info/demo.ppt?x-oss-process=doc/preview,export_1,print_1.