全部產品
Search
文件中心

Object Storage Service:文檔格式轉換

更新時間:Jun 07, 2025

通過文檔格式轉換功能,您可以將各類文檔轉換為目標格式,並支援將轉換結果儲存至指定OSS路徑。

使用情境

  • 線上預覽最佳化:上傳PDF、Word、Excel、PPT等文檔至OSS後,可以調用文檔轉換介面,將文檔轉換成圖片,方便在網頁端或移動端直接預覽,無需下載。

  • 跨平台相容性:通過文檔轉換服務,不同裝置和作業系統的使用者都能順暢查看文檔。

支援的輸入檔案類型

檔案類型

檔案尾碼

Word

doc、docx、wps、wpss、docm、dotm、dot、dotx、html

PPT

pptx、ppt、pot、potx、pps、ppsx、dps、dpt、pptm、potm、ppsm、dpss

Excel

xls、xlt、et、ett、xlsx、xltx、csv、xlsb、xlsm、xltm、ets

PDF

pdf

如何使用

前提條件

轉換文檔格式

您可以使用SDK調用文檔轉換介面進行處理,並將處理後的檔案儲存到指定的Bucket。僅支援使用Java、Python、Go SDK通過非同步處理的方式完成文檔轉換。

Java

要求使用3.17.4及以上版本的Java SDK。

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.AsyncProcessObjectRequest;
import com.aliyun.oss.model.AsyncProcessObjectResult;
import com.aliyuncs.exceptions.ClientException;

import java.util.Base64;

public class Demo1 {
    public static void main(String[] args) throws ClientException {
        // yourEndpoint填寫Bucket所在地區對應的Endpoint。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 填寫Endpoint對應的Region資訊,例如cn-hangzhou。
        String region = "cn-hangzhou";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 指定Bucket名稱。
        String bucketName = "examplebucket";
        // 指定轉換後的檔案名稱。
        String targetKey = "dest.png";
        // 指定轉換前的文檔名稱。
        String sourceKey = "src.docx";

        // 建立OSSClient執行個體。
        // 當OSSClient執行個體不再使用時,調用shutdown方法以釋放資源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 構建文檔處理樣式字串以及文檔轉換處理參數。
            String style = String.format("doc/convert,target_png,source_docx");
            // 構建非同步處理指示。
            String bucketEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(bucketName.getBytes());
            String targetEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(targetKey.getBytes());
            String process = String.format("%s|sys/saveas,b_%s,o_%s", style, bucketEncoded, targetEncoded);
            // 建立AsyncProcessObjectRequest對象。
            AsyncProcessObjectRequest request = new AsyncProcessObjectRequest(bucketName, sourceKey, process);
            // 執行非同步處理任務。
            AsyncProcessObjectResult response = ossClient.asyncProcessObject(request);
            System.out.println("EventId: " + response.getEventId());
            System.out.println("RequestId: " + response.getRequestId());
            System.out.println("TaskId: " + response.getTaskId());

        } finally {
            // 關閉OSSClient。
            ossClient.shutdown();
        }
    }
}

Python

要求使用Python SDK 2.18.4及以上版本。

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

def main():
    # 從環境變數中擷取臨時訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    # 填寫Bucket所在地區對應的Endpoint。以華東1(杭州)為例,Endpoint填寫為https://oss-cn-hangzhou.aliyuncs.com。
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # 指定阿里雲通用Region ID,例如cn-hangzhou。
    region = 'cn-hangzhou'

    # 指定Bucket名稱,例如examplebucket。
    bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

    # 指定轉換前的文檔名稱。
    source_key = 'src.docx'

    # 指定轉換後的檔案名稱。
    target_key = 'dest.png'

    # 構建文檔處理樣式字串以及文檔轉換處理參數。
    animation_style = 'doc/convert,target_png,source_docx'

    # 構建處理指示,包括儲存路徑和Base64編碼的Bucket名稱和目標檔案名稱。
    bucket_name_encoded = base64.urlsafe_b64encode('examplebucket'.encode()).decode().rstrip('=')
    target_key_encoded = base64.urlsafe_b64encode(target_key.encode()).decode().rstrip('=')
    process = f"{animation_style}|sys/saveas,b_{bucket_name_encoded},o_{target_key_encoded}"

    try:
        # 執行非同步處理任務。
        result = bucket.async_process_object(source_key, process)
        print(f"EventId: {result.event_id}")
        print(f"RequestId: {result.request_id}")
        print(f"TaskId: {result.task_id}")
    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    main()

Go

要求使用Go SDK 3.0.2及以上版本。

package main

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

func main() {
    // 從環境變數中擷取臨時訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }
    // 建立OSSClient執行個體。
    // yourEndpoint填寫Bucket對應的Endpoint,以華東1(杭州)為例,填寫為https://oss-cn-hangzhou.aliyuncs.com。其他Region請按實際情況填寫。
    // yourRegion指定阿里雲通用Region ID,例如cn-hangzhou。
    client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }
    // 指定Bucket名稱,例如examplebucket。
    bucketName := "examplebucket"

    bucket, err := client.Bucket(bucketName)
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }

    // 指定轉換前的文檔名稱。
    sourceKey := "src.docx"
    // 指定轉換後的檔案名稱。
    targetKey := "dest.png"

    // 構建文檔處理樣式字串以及文檔轉換處理參數
    animationStyle := "doc/convert,target_png,source_docx"

    // 構建處理指示,包括儲存路徑和Base64編碼的Bucket名稱和目標檔案名稱。
    bucketNameEncoded := base64.URLEncoding.EncodeToString([]byte(bucketName))
    targetKeyEncoded := base64.URLEncoding.EncodeToString([]byte(targetKey))
    process := fmt.Sprintf("%s|sys/saveas,b_%v,o_%v", animationStyle, bucketNameEncoded, targetKeyEncoded)

    // 執行非同步處理任務。
    result, err := bucket.AsyncProcessObject(sourceKey, process)
    if err != nil {
    log.Fatalf("Failed to async process object: %s", err)
    }

    fmt.Printf("EventId: %s\n", result.EventId)
    fmt.Printf("RequestId: %s\n", result.RequestId)
    fmt.Printf("TaskId: %s\n", result.TaskId)
}

參數說明

操作名稱:doc/convert

具體參數如下表所示。

參數名稱

類型

是否必須

描述

target

string

目標檔案類型。取值:

  • pdf

  • png

  • jpg

  • txt

source

string

源檔案格式,預設使用對象名尾碼。取值:

  • docx(在轉換html文檔時,需填寫docx以完成格式轉換)

  • doc

  • pptx

  • ppt

  • pdf

  • xlsx

  • xls

pages

string

轉換的頁碼。

例如:1,2,4-10分別表示轉換第1頁、第2頁、第4頁~第10頁。

需使用sys/saveas參數將轉換後的文檔儲存在指定的Bucket中,請參見另存新檔。若您需要擷取轉換任務的處理結果,需使用notify參數,請參見訊息通知

更多情境

文檔格式轉換是以非同步請求形式提交的,即在返回處理結果時無法直接獲得文檔轉換的結果(如處理成功或失敗等資訊)。如果您需要擷取處理結果,建議結合輕量訊息佇列SMQ(原MNS)配置事件通知,即可在處理完成後收到即時通知,無需重複查詢任務狀態。

配置事件通知

實現事件通知,您需要先參考主題模型快速入門建立一個與您的Bucket位於同一地區的訊息主題。​您可以通過以下代碼在進行文檔轉換時配置事件通知,其中的主題名稱需經過URL安全的Base64編碼處理。​例如,訊息主題名稱為test-topic,則編碼後的名稱為dGVzdC10b3BpYw。 ​

範例程式碼

僅支援使用Java、Python、Go SDK通過非同步處理的方式完成文檔轉換。

Java

要求使用3.17.4及以上版本的Java SDK。

import com.aliyun.oss.ClientBuilderConfiguration;
import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.EnvironmentVariableCredentialsProvider;
import com.aliyun.oss.common.comm.SignVersion;
import com.aliyun.oss.model.AsyncProcessObjectRequest;
import com.aliyun.oss.model.AsyncProcessObjectResult;
import com.aliyuncs.exceptions.ClientException;

import java.util.Base64;

public class Demo1 {
    public static void main(String[] args) throws ClientException {
        // yourEndpoint填寫Bucket所在地區對應的Endpoint。
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // 填寫Endpoint對應的Region資訊,例如cn-hangzhou。
        String region = "cn-hangzhou";
        // 從環境變數中擷取訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // 指定Bucket名稱。
        String bucketName = "examplebucket";
        // 指定轉換後的檔案名稱。
        String targetKey = "dest.png";
        // 指定轉換前的文檔名稱。
        String sourceKey = "src.docx";

        // 建立OSSClient執行個體。
        // 當OSSClient執行個體不再使用時,調用shutdown方法以釋放資源。
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // 構建文檔處理樣式字串以及文檔轉換處理參數。
            String style = String.format("doc/convert,target_png,source_docx");
            // 構建非同步處理指示。
            String bucketEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(bucketName.getBytes());
            String targetEncoded = Base64.getUrlEncoder().withoutPadding().encodeToString(targetKey.getBytes());
            String process = String.format("%s|sys/saveas,b_%s,o_%s/notify,topic_dGVzdC10b3BpYw", style, bucketEncoded, targetEncoded);
            // 建立AsyncProcessObjectRequest對象。
            AsyncProcessObjectRequest request = new AsyncProcessObjectRequest(bucketName, sourceKey, process);
            // 執行非同步處理任務。
            AsyncProcessObjectResult response = ossClient.asyncProcessObject(request);
            System.out.println("EventId: " + response.getEventId());
            System.out.println("RequestId: " + response.getRequestId());
            System.out.println("TaskId: " + response.getTaskId());

        } finally {
            // 關閉OSSClient。
            ossClient.shutdown();
        }
    }
}

Python

要求使用Python SDK 2.18.4及以上版本。

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

def main():
    # 從環境變數中擷取臨時訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    # 填寫Bucket所在地區對應的Endpoint。以華東1(杭州)為例,Endpoint填寫為https://oss-cn-hangzhou.aliyuncs.com。
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # 指定阿里雲通用Region ID,例如cn-hangzhou。
    region = 'cn-hangzhou'

    # 指定Bucket名稱,例如examplebucket。
    bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

    # 指定轉換前的文檔名稱。
    source_key = 'src.docx'

    # 指定轉換後的檔案名稱。
    target_key = 'dest.png'

    # 構建文檔處理樣式字串以及文檔轉換處理參數。
    animation_style = 'doc/convert,target_png,source_docx'

    # 構建處理指示,包括儲存路徑和Base64編碼的Bucket名稱和目標檔案名稱。
    bucket_name_encoded = base64.urlsafe_b64encode('examplebucket'.encode()).decode().rstrip('=')
    target_key_encoded = base64.urlsafe_b64encode(target_key.encode()).decode().rstrip('=')
    process = f"{animation_style}|sys/saveas,b_{bucket_name_encoded},o_{target_key_encoded}/notify,topic_dGVzdC10b3BpYw"

    try:
        # 執行非同步處理任務。
        result = bucket.async_process_object(source_key, process)
        print(f"EventId: {result.event_id}")
        print(f"RequestId: {result.request_id}")
        print(f"TaskId: {result.task_id}")
    except Exception as e:
        print(f"Error: {e}")


if __name__ == "__main__":
    main()

Go

要求使用Go SDK 3.0.2及以上版本。

package main

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

func main() {
    // 從環境變數中擷取臨時訪問憑證。運行本程式碼範例之前,請確保已設定環境變數OSS_ACCESS_KEY_ID和OSS_ACCESS_KEY_SECRET。
    provider, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }
    // 建立OSSClient執行個體。
    // yourEndpoint填寫Bucket對應的Endpoint,以華東1(杭州)為例,填寫為https://oss-cn-hangzhou.aliyuncs.com。其他Region請按實際情況填寫。
    // yourRegion指定阿里雲通用Region ID,例如cn-hangzhou。
    client, err := oss.New("https://oss-cn-hangzhou.aliyuncs.com", "", "", oss.SetCredentialsProvider(&provider), oss.AuthVersion(oss.AuthV4), oss.Region("cn-hangzhou"))
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }
    // 指定Bucket名稱,例如examplebucket。
    bucketName := "examplebucket"

    bucket, err := client.Bucket(bucketName)
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }

    // 指定轉換前的文檔名稱。
    sourceKey := "src.docx"
    // 指定轉換後的檔案名稱。
    targetKey := "dest.png"

    // 構建文檔處理樣式字串以及文檔轉換處理參數
    animationStyle := "doc/convert,target_png,source_docx"

    // 構建處理指示,包括儲存路徑和Base64編碼的Bucket名稱和目標檔案名稱。
    bucketNameEncoded := base64.URLEncoding.EncodeToString([]byte(bucketName))
    targetKeyEncoded := base64.URLEncoding.EncodeToString([]byte(targetKey))
    process := fmt.Sprintf("%s|sys/saveas,b_%v,o_%v/notify,topic_dGVzdC10b3BpYw", animationStyle, bucketNameEncoded, targetKeyEncoded)

    // 執行非同步處理任務。
    result, err := bucket.AsyncProcessObject(sourceKey, process)
    if err != nil {
    log.Fatalf("Failed to async process object: %s", err)
    }

    fmt.Printf("EventId: %s\n", result.EventId)
    fmt.Printf("RequestId: %s\n", result.RequestId)
    fmt.Printf("TaskId: %s\n", result.TaskId)
}

相關API

以上操作方式底層基於API實現,如果您的程式自訂要求較高,您可以直接發起REST API請求。直接發起REST API請求需要手動編寫代碼計算簽名。關於公用要求標頭Authorization的計算方法,請參見簽名版本4(推薦)

轉換文檔格式

  • 轉換前

    • 文檔格式:DOCX

    • 文檔名稱:example.docx

  • 轉換後

    • 檔案格式:PNG

    • 檔案儲存體路徑:oss://test-bucket/doc_images/{index}.png

      • b_dGVzdC1idWNrZXQ=:轉碼完成後儲存到名為test-bucket的Bucket中(dGVzdC1idWNrZXQ=test-bucket進行Base64編碼後的值)。

      • o_ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==:object使用{index}變數以example.docx頁碼作為圖片檔案名稱儲存到doc_images目錄下(ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==doc_images/{index}.png進行Base64編碼之後的值)。

    • 轉換完成訊息通知:發送到 topic 名為test-topic的輕量訊息佇列SMQ(原MNS)

處理樣本

// 將檔案example.docx轉換為PNG格式的圖片檔案。
POST /example.docx?x-oss-async-process HTTP/1.1
Host: doc-demo.oss-cn-hangzhou.aliyuncs.com
Date: Fri, 28 Oct 2022 06:40:10 GMT
Authorization: SignatureValue

x-oss-async-process=doc/convert,target_png,source_docx|sys/saveas,b_dGVzdC1idWNrZXQ=,o_ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==/notify,topic_dGVzdC10b3BpYw

注意事項

  • 文檔轉換僅支援非同步處理(x-oss-async-process處理方式)。

  • 不支援匿名訪問。

  • 文檔格式轉換支援的檔案大小最大均為200 MB,不支援調整。

常見問題

OSS文檔轉換支援指定Excel表sheet頁的內容嗎?

不支援。OSS文檔轉換僅支援轉換Excel表所有sheet頁。如果您需要轉換特定sheet頁,建議調用IMM提供的CreateOfficeConversionTask - 建立文檔轉換任務介面,設定SheetIndex參數。

相關文檔

關於文檔格式轉換的更多內容,請參見文檔格式轉換