Document preview

更新时间:
复制 MD 格式

The document preview feature lets you preview spreadsheet, word processing, presentation, and PDF files online. This feature helps you manage and access your document content.

Important

New features and optimizations for Intelligent Media Management (IMM) will be primarily available in the new version. The old version will be gradually phased out. For a better experience, use the WebOffice online preview feature provided by the new version of IMM. For a comparison between the new and old versions of IMM, see Usage guide for new and old versions.

Prerequisites

  • You have activated IMM and bound it to Object Storage Service (OSS). For more information, see Quick Start.

  • If you use a Resource Access Management (RAM) user to use IMM features, make sure the RAM user has the following permissions:

Precautions

  • Supported file types for online preview

    • Spreadsheet files: et, xls, xlt, xlsx, xlsm, xltx, xltm, csv

    • Word processing files: doc, docx, txt, dot, wps, wpt, dotx, docm, dotm, rtf

    • Presentation files: ppt, pptx, pptm, ppsx, ppsm, pps, potx, potm, dpt, dps

    • PDF files: pdf

  • File size limit

    You cannot preview files larger than 200 MB.

  • Preview method

    To preview a document, you must use a URL signed with an AccessKey ID and an AccessKey secret, regardless of whether the document's access control list (ACL) is set to public-read or private.

  • Billing

    The document preview operation described in this topic uses the IMM document preview V1 API. For more information about the billing for this API, see Billing for the old version of IMM.

Parameter

Operation: imm/previewdoc

The parameters are as follows:

Name

Description

copy

Specifies whether to allow copying the content of the document during preview. Valid values:

1. You can copy document content.

0: Document content cannot be copied.

Flow overview

image

A document object is previewed in the following process:

  1. A client app or web client sends a preview request to the business server and provides the name of the file to preview.

  2. The business server signs the URL based on the requested file and provides the signed URL to the client app or web client.

  3. The client app or web client uses the signed URL to directly access and preview the OSS file.

    Important

    You cannot directly preview encrypted files using a signed URL. To preview an encrypted file, follow these steps:

    1. Set up the decryption process for the encrypted file using the JavaScript API. For more information, see Set up the decryption process for an encrypted file.

    2. Call the IMM CreateOfficeConversionTask operation to convert the original document into the VECTOR format and output it to the specified OSS folder.

Use Alibaba Cloud SDKs

The method for generating a signed URL for document preview is similar to that for image processing. You only need to replace the image processing action with the document preview action.

The following code examples show how to generate a signed URL for document preview using common software development kits (SDKs). For more information about other SDKs, see SDKs.

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 {
        // The China (Hangzhou) region is used as an example. Specify the actual endpoint.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the region that corresponds to the endpoint. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // We strongly recommend that you do not save your access credentials in your project code. This may lead to credential leakage and threaten the security of all resources in your account. This example shows how to obtain access credentials from environment variables. Before you run the example, configure the environment variables.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the bucket name. Example: examplebucket.
        String bucketName = "examplebucket";
        // Specify the full path of the object. The full path cannot contain the bucket name.
        String objectName = "exampledir/exampleobject.txt";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer used, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        // 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 {
            // Set the style. The style contains the document preview parameters.
            String style = "imm/previewdoc,copy_1";
            // Set the expiration time of the signed URL to 10 minutes.
            Date expiration = new Date(new Date().getTime() + 1000 * 60 * 10 );
            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();
            }
        }
    }
}
<?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;

// Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
$accessKeyId = getenv("OSS_ACCESS_KEY_ID");
$accessKeySecret = getenv("OSS_ACCESS_KEY_SECRET");
// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
$endpoint = "yourEndpoint";
// Specify the bucket name. Example: examplebucket.
$bucket= "examplebucket";
// Specify the full path of the document to preview. The full path cannot contain the bucket name.
$object = "exampledir/exampleobject.txt";

$ossClient = new OssClient($accessKeyId, $accessKeySecret, $endpoint);

// Generate a signed URL that contains document preview parameters. The URL is valid for 3,600 seconds and can be accessed in a browser.
$timeout = 3600;

$options = array(
    // Set the style. The style contains the document preview parameters.
    OssClient::OSS_PROCESS => "imm/previewdoc,copy_1" );

$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print("signed url: \n" . $signedUrl);  
const OSS = require('ali-oss');

const client = new OSS({
  // Set yourregion to the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the region to oss-cn-hangzhou.
  region: 'yourregion',
  // Obtain access credentials from environment variables. Before you run this example, 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,
  // Set yourbucketname to the bucket name.
  bucket: 'yourbucketname'
});
// Set the style. The style contains the document preview parameters.
// Generate a signed URL and set the expiration time to 10 minutes.
const signUrl = client.signatureUrl('exampledir/exampleobject.txt', {expires: 600, 'process' : 'imm/previewdoc,copy_1'});
console.log("signUrl="+signUrl);
# -*- coding: utf-8 -*-
import oss2
from oss2.credentials import EnvironmentVariableCredentialsProvider

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

# Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
# Specify the bucket name. Example: examplebucket.
bucket = oss2.Bucket(auth, 'https://oss-cn-hangzhou.aliyuncs.com', 'examplebucket')
# Specify the full path of the document to preview. The full path cannot contain the bucket name.
key = 'example.txt'

# If the file is not in the specified bucket, upload the file to the destination bucket.
# bucket.put_object_from_file(key, 'D:\\localpath\\example.txt')
# Set the style. The style contains the document preview parameters.
style = 'imm/previewdoc,copy_1'
# Generate a signed URL and set the expiration time to 10 minutes. The unit of the expiration time is seconds.
url = bucket.sign_url('GET', key, 10 * 60, params={'x-oss-process': style})
print(url)
using Aliyun.OSS;
using Aliyun.OSS.Common;

// Set yourEndpoint to the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
var endpoint = "yourEndpoint";
// Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
var accessKeyId = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_ID");
var accessKeySecret = Environment.GetEnvironmentVariable("OSS_ACCESS_KEY_SECRET");
// Specify the name of the bucket where the document is stored. Example: examplebucket.
var bucketName = "examplebucket";
// Specify the full path of the document to preview. The full path cannot contain the bucket name.
var objectName = "exampledir/exampleobject.txt";
// Create an OSSClient instance.
var client = new OssClient(endpoint, accessKeyId, accessKeySecret);
try
{
    // Set the style. The style contains the document preview parameters.
    var process = "imm/previewdoc,copy_1";
    var req = new GeneratePresignedUriRequest(bucketName, objectName, SignHttpMethod.Get)
    {
        Expiration = DateTime.Now.AddHours(1),
        Process = process
    };
    // Generate a signed URI.
    var uri = client.GeneratePresignedUri(req);
    Console.WriteLine("Generate Presigned Uri:{0} with process:{1} succeeded ", uri, process);
}
catch (OssException ex)
{
    Console.WriteLine("Failed with error code: {0}; Error info: {1}. \nRequestID:{2}\tHostID:{3}",
        ex.ErrorCode, ex.Message, ex.RequestId, ex.HostId);
}
catch (Exception ex)
{
    Console.WriteLine("Failed with error info: {0}", ex.Message);
}
// Specify the bucket name. Example: examplebucket.
String bucketName = "examplebucket";
// Specify the full path of the source object, excluding the bucket name. Example: exampleobject.txt.
String objectKey = "exampleobject.txt";
String url = null;
// Set the style. The style contains the document preview parameters.
String style = "imm/previewdoc,copy_1";
try {
    // Generate a signed URL for the object.
    GeneratePresignedUrlRequest request = new GeneratePresignedUrlRequest(bucketName, objectKey);
    // Set the expiration time of the signed URL to 30 minutes.
    request.setExpiration(30*60);
    request.setProcess(style);
    url = oss.presignConstrainedObjectURL(request);
    Log.d("url", url);
} catch (ClientException e) {
    e.printStackTrace();
}
package main

    import (
        "fmt"
        "os"
        "github.com/aliyun/aliyun-oss-go-sdk/oss"
    )

func main() {
    // Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Create an OSSClient instance.
    // Set yourEndpoint to the endpoint of the bucket. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify the actual region.
    client, err := oss.New("yourEndpoint", "", "", oss.SetCredentialsProvider(&provider))
    if err != nil {
        fmt.Println("Error:", err)
        os.Exit(-1)
    }

    // Specify the name of the bucket where the document is stored. Example: examplebucket.
    bucketName := "examplebucket"
    bucket, err := client.Bucket(bucketName)
    if err != nil {
    fmt.Println("Error:", err); os.Exit(-1)
    }
    // Specify the full path of the document to preview. The full path cannot contain the bucket name.
    ossImageName := "exampledir/exampleobject.txt"
    // Set the style. The style contains the document preview parameters.
    // Generate a signed URL and set the expiration time to 600s.
    signedURL, err := bucket.SignURL(ossImageName, oss.HTTPGet, 600, oss.Process("imm/previewdoc,copy_1"))
    if err != nil {
    fmt.Println("Error:", err); os.Exit(-1)
    } else {
    fmt.Println(signedURL)
    }
}
// Specify the name of the bucket where the document is stored. Example: examplebucket.
NSString *bucketName = @"examplebucket";
// Specify the full path of the document to preview. The full path cannot contain the bucket name.
NSString *objectKey = @"exampleobject.txt";
NSString *method = @"GET";
// Set the style. The style contains the document preview parameters.
NSDictionary *params = @{@"x-oss-process": @"imm/previewdoc%2Ccopy_1"};
// Generate a signed URL and set the expiration time to 30 minutes.
OSSTask *ossTask = [client presignConstrainURLWithBucketName:bucketName
                                               withObjectKey:objectKey
                                                  httpMethod:method
                                      withExpirationInterval:30 * 60
                                              withParameters:params];

[ossTask continueWithBlock:^id _Nullable(OSSTask * _Nonnull task) {
    if (!task.error) {
        NSString *url = task.result;
        NSLog(@"url: %@", url);
    } else {
        NSLog(@"error: %@", task.error);
    }
    return nil;
}];
#include <alibabacloud/oss/OssClient.h>
using namespace AlibabaCloud::OSS;

int main(void)
{
    /* Initialize OSS account information. */
            
    /* Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
    std::string Endpoint = "yourEndpoint";
    /* Specify the name of the bucket where the document is stored. Example: examplebucket. */
    std::string BucketName = "examplebucket";
    /* Specify the full path of the document to preview. The full path cannot contain the bucket name. */
    std::string ObjectName = "exampledir/exampleobject.txt";

      /* Initialize resources such as the network. */
    InitializeSdk();

    ClientConfiguration conf;
    /* Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */
    auto credentialsProvider = std::make_shared<EnvironmentVariableCredentialsProvider>();
    OssClient client(Endpoint, credentialsProvider, conf);


    /* Set the style. The style contains the document preview parameters. */
    std::string Process = "imm/previewdoc,copy_1";
    GeneratePresignedUrlRequest request(BucketName, ObjectName, Http::Get);
    request.setProcess(Process);
    auto outcome = client.GeneratePresignedUrl(request);

    /* Release resources such as the network. */
    ShutdownSdk();
    return 0;
}
#include "oss_api.h"
#include "aos_http_io.h"
/* Specify the endpoint of the region where the bucket is located. For example, if the bucket is in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. */
const char *endpoint = "yourEndpoint";
/* Obtain access credentials from environment variables. Before you run this example, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured. */  
const char *access_key_id = getenv("OSS_ACCESS_KEY_ID");
const char *access_key_secret = getenv("OSS_ACCESS_KEY_SECRET");
/* Specify the name of the bucket where the document is stored. Example: examplebucket. */
const char *bucket_name = "examplebucket";
/* Specify the full path of the document to preview. The full path cannot contain the bucket name. */
const char *object_name = "exampledir/exampleobject.txt";
void init_options(oss_request_options_t *options)
{
    options->config = oss_config_create(options->pool);
    /* Initialize the aos_string_t type with a char* string. */
    aos_str_set(&options->config->endpoint, endpoint);
    aos_str_set(&options->config->access_key_id, access_key_id);
    aos_str_set(&options->config->access_key_secret, access_key_secret);
    /* Specifies whether a CNAME is used. 0 indicates that no CNAME is used. */
    options->config->is_cname = 0;
    /* Set network-related parameters, such as the timeout period. */
    options->ctl = aos_http_controller_create(options->pool, 0);
}
int main(int argc, char *argv[])
{
    /* Call the aos_http_io_initialize method at the program entrance to initialize global resources such as the network and memory. */
    if (aos_http_io_initialize(NULL, 0) != AOSE_OK) {
        exit(1);
    }
    /* The memory pool (pool) is used for memory management and is equivalent to apr_pool_t. The implementation code is in the apr library. */
    aos_pool_t *pool;
    /* Re-create a memory pool. The second parameter is NULL, which indicates that no other memory pools are inherited. */
    aos_pool_create(&pool, NULL);
    /* Create and initialize options. This parameter includes global configuration information such as the endpoint, access_key_id, access_key_secret, is_cname, and curl. */
    oss_request_options_t *oss_client_options;
    /* Allocate memory to options in the memory pool. */
    oss_client_options = oss_request_options_create(pool);
    /* Initialize the client option oss_client_options. */
    init_options(oss_client_options);
    /* Initialize parameters. */
    aos_string_t bucket;
    aos_string_t object;
    aos_table_t *params = NULL;
    aos_http_request_t *req;
    char *url_str;
    apr_time_t now;
    int64_t expire_time; 
    aos_str_set(&bucket, bucket_name);
    aos_str_set(&object, object_name);
    /* Set the style. The style contains the document preview parameters. */
    params = aos_table_make(pool, 1);
    apr_table_set(params, OSS_PROCESS, "imm/previewdoc,copy_1");
    req = aos_http_request_create(pool);
    req->method = HTTP_GET;
    req->query_params = params;
    /* Specify the expiration time (expire_time) in seconds. */
    now = apr_time_now();
    expire_time = now / 1000000 + 10 * 60;
    /* Generate a signed URL. */
    url_str = oss_gen_signed_url(oss_client_options, &bucket, &object, expire_time, req);
    printf("url: %s\n", url_str);
    /* Release the memory pool. This is equivalent to releasing the memory allocated to each resource during the request. */
    aos_pool_destroy(pool);
    /* Release the previously allocated global resources. */
    aos_http_io_deinitialize();
    return 0;
}

FAQ

Can I set the document preview interface to English?

Yes, you can. To set the language to English, add the `lang=en-US` parameter to the URL. For more information, see Internationalization - multi-language support.

Can I print a file that is being previewed online?

There are two ways to print a file from the online preview:

  • Download the file to your local machine and then print it.

  • Use the online document collaboration feature of IMM to print the file online. For more information, see Print.

Signed document URL error: The resource Project cannot be found. bucket does not bind any project.

  • Cause: The current bucket is not bound to an IMM project.

  • Solution: Bind the current bucket to an IMM project. For more information, see Bind IMM.

What do I do if I cannot preview a PPT file with more than 200 pages?

The V1 document preview feature of IMM supports stable previews for documents with up to 200 pages. To preview a document that has more than 200 pages, use the V2 document preview feature of IMM. For more information, see Quick Start.

How do I configure the preview interface to disallow copying?

You can disallow copying by setting the document preview parameters in the style. For example, if you use the SDK for Java, you can use the following style: String style = "imm/previewdoc,copy_0". A value of 0 for the `copy` parameter indicates that copying is not allowed.

Can I add watermarks during document preview?

Document preview does not support adding watermarks. To preview a document with a watermark, you must first use Intelligent Media Management to add the watermark to the document. For more information, see Add a watermark.

Error generating a signed document URL after enabling CDN: Either the Signature query string parameter or the Authorization header should be specified, not both.

If you enable back-to-origin for a private bucket and access a file in the bucket through a CDN domain name, you do not need to provide additional signature information. This applies only if the bucket is bound to an IMM project. You must configure the following settings:

  1. Authorize the default role by granting the `oss:ProcessImm` permission to the default CDN role `AliyunCDNAccessingPrivateOSSRole`.

  2. Access the resource using a URL that does not contain signature information.

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