すべてのプロダクト
Search
ドキュメントセンター

Object Storage Service:ドキュメント変換

最終更新日:Mar 26, 2026

ドキュメント変換機能を使用すると、さまざまな種類のドキュメントを目的のフォーマットに変換し、結果を指定された Object Storage Service (OSS) パスに保存できます。

ユースケース

  • オンラインプレビューの最適化:PDF、Word、Excel、PPT などのドキュメントを OSS にアップロードした後、ドキュメント変換 API を呼び出してドキュメントをイメージに変換できます。これにより、ユーザーはダウンロードせずに Web ブラウザーやモバイルアプリで直接ドキュメントをプレビューできます。

  • クロスプラットフォーム互換性の確保:ドキュメント変換により、ユーザーが異なるデバイスやオペレーティングシステム間でドキュメントをスムーズに閲覧できるようになります。

サポートされる入力ファイル形式

ファイル形式

ファイル拡張子

Word

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

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 を使用してドキュメント変換 API を呼び出し、変換後のファイルを指定されたバケットに保存できます。ドキュメント変換の非同期処理は、Java、Python、Go の SDK のみでサポートされています。

Java

この例では、OSS SDK for Java バージョン 3.17.4 以降が必要です。

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 {
        // Set endpoint to the endpoint of the region where the bucket is located.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Set region to the region ID, for example, cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before running this 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 bucket name.
        String bucketName = "examplebucket";
        // Specify the name of the destination file.
        String targetKey = "dest.png";
        // Specify the name of the source document.
        String sourceKey = "src.docx";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Build the string for document processing styles and conversion parameters.
            String style = String.format("doc/convert,target_png,source_docx");
            // Build the asynchronous processing instruction.
            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);
            // Create an AsyncProcessObjectRequest object.
            AsyncProcessObjectRequest request = new AsyncProcessObjectRequest(bucketName, sourceKey, process);
            // Initiate the asynchronous task.
            AsyncProcessObjectResult response = ossClient.asyncProcessObject(request);
            System.out.println("EventId: " + response.getEventId());
            System.out.println("RequestId: " + response.getRequestId());
            System.out.println("TaskId: " + response.getTaskId());

        } finally {
            // Shut down the OSSClient instance.
            ossClient.shutdown();
        }
    }
}

Python

この例では、OSS SDK for Python バージョン 2.18.4 以降が必要です。

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

def main():
    # Obtain access credentials from environment variables. Before running this sample code, make sure that the OSS_ACCESS_KEY_ID and OSS_ACCESS_KEY_SECRET environment variables are configured.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    # Set endpoint to the endpoint of the region where the bucket is located. For example, for China (Hangzhou), set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # Specify the general-purpose Alibaba Cloud region ID, for example, cn-hangzhou.
    region = 'cn-hangzhou'

    # Specify the bucket name, for example, examplebucket.
    bucket = oss2.Bucket(auth, endpoint, 'examplebucket', region=region)

    # Specify the name of the source document.
    source_key = 'src.docx'

    # Specify the name of the destination file.
    target_key = 'dest.png'

    # Build the string for document processing styles and conversion parameters.
    animation_style = 'doc/convert,target_png,source_docx'

    # Build the processing instruction, including the save path and the Base64-encoded bucket name and destination file name.
    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:
        # Initiate the asynchronous task.
        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

この例では、OSS SDK for Go バージョン 3.0.2 以降が必要です。

package main

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

func main() {
    // Obtain access credentials from environment variables. Before running this sample code, 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 the endpoint to the one for your bucket's region. For the China (Hangzhou) region, for example, use https://oss-cn-hangzhou.aliyuncs.com. Set the endpoint based on your actual region.
    // Specify the general-purpose Alibaba Cloud region ID, for example, 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)
    }
    // Specify the bucket name, for example, examplebucket.
    bucketName := "examplebucket"

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

    // Specify the name of the source document.
    sourceKey := "src.docx"
    // Specify the name of the destination file.
    targetKey := "dest.png"

    // Build the string for document processing styles and conversion parameters.
    animationStyle := "doc/convert,target_png,source_docx"

    // Build the processing instruction, including the save path and the Base64-encoded bucket name and destination file name.
    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)

    // Initiate the asynchronous task.
    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

  • doc

  • pptx

  • ppt

  • pdf

  • xlsx

  • xls

pages

string

いいえ

変換するページ番号。

たとえば、1,2,4-10 は、ページ 1、ページ 2、およびページ 4~10 を変換することを指定します。

変換後のドキュメントを指定されたバケットに保存するには、sys/saveas パラメーターを使用する必要があります。詳細については、「sys/saveas」をご参照ください。変換タスクの処理結果を受け取る必要がある場合は、notify パラメーターを使用します。詳細については、「メッセージ通知」をご参照ください。

高度なシナリオ

ドキュメント変換タスクは非同期リクエストとして送信されます。つまり、即時の応答には変換の最終結果(成功または失敗など)は含まれません。結果を取得するには、Simple Message Queue (SMQ)(旧称 MNS)を使用してイベント通知を設定してください。これにより、タスク完了時に即座に通知が届き、ステータスをポーリングする必要がなくなります。

イベント通知

イベント通知を受信するには、まずバケットと同じリージョンにトピックを作成する必要があります。手順については、「トピックモデルのクイックスタート」をご参照ください。次のコードを使用して、ドキュメント変換タスクのイベント通知を設定できます。リクエスト内のトピック名は URL セーフ Base64 エンコーディングされている必要があります。たとえば、トピック名が test-topic の場合、エンコードされた名前は dGVzdC10b3BpYw です。

サンプルコード

ドキュメント変換の非同期処理は、Java、Python、Go の SDK のみでサポートされています。

Java

この例では、OSS SDK for Java バージョン 3.17.4 以降が必要です。

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 {
        // Set endpoint to the endpoint of the region where the bucket is located.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Set region to the region ID, for example, cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain access credentials from environment variables. Before running this 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 bucket name.
        String bucketName = "examplebucket";
        // Specify the name of the destination file.
        String targetKey = "dest.png";
        // Specify the name of the source document.
        String sourceKey = "src.docx";

        // Create an OSSClient instance.
        // When the OSSClient instance is no longer needed, call the shutdown method to release its resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Build the string for document processing styles and conversion parameters.
            String style = String.format("doc/convert,target_png,source_docx");
            // Build the asynchronous processing instruction.
            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);
            // Create an AsyncProcessObjectRequest object.
            AsyncProcessObjectRequest request = new AsyncProcessObjectRequest(bucketName, sourceKey, process);
            // Initiate the asynchronous task.
            AsyncProcessObjectResult response = ossClient.asyncProcessObject(request);
            System.out.println("EventId: " + response.getEventId());
            System.out.println("RequestId: " + response.getRequestId());
            System.out.println("TaskId: " + response.getTaskId());

        } finally {
            // Shut down the OSSClient instance.
            ossClient.shutdown();
        }
    }
}

Python

この例では、OSS SDK for Python バージョン 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())
    # エンドポイントをバケットが配置されているリージョンのエンドポイントに設定します。たとえば、中国 (杭州) の場合、エンドポイントを https://oss-cn-hangzhou.aliyuncs.com に設定します。
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # 汎用的なAlibaba CloudリージョンIDを指定します。たとえば、cn-hangzhou です。
    region = 'cn-hangzhou'

    # バケット名を指定します。たとえば、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_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

この例では、OSS SDK for Go バージョン 3.0.2 以降が必要です。

package main

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

func main() {
    // Obtain access credentials from environment variables. Before running this sample code, 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 the endpoint to the one for your bucket's region. For the China (Hangzhou) region, for example, use https://oss-cn-hangzhou.aliyuncs.com. Set the endpoint based on your actual region.
    // Specify the general-purpose Alibaba Cloud region ID, for example, 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)
    }
    // Specify the bucket name, for example, examplebucket.
    bucketName := "examplebucket"

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

    // Specify the name of the source document.
    sourceKey := "src.docx"
    // Specify the name of the destination file.
    targetKey := "dest.png"

    // Build the string for document processing styles and conversion parameters.
    animationStyle := "doc/convert,target_png,source_docx"

    // Build the processing instruction, including the save path and the Base64-encoded bucket name and destination file name.
    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)

    // Initiate the asynchronous task.
    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 リファレンス

SDK のメソッドは RESTful API 上に構築されています。高度なカスタマイズを行う場合は、RESTful API を直接呼び出すことができます。この場合、Authorization ヘッダーの署名を手動で計算する必要があります。手順については、「署名バージョン 4(推奨)」をご参照ください。

ドキュメントの変換

  • 変換前

    • ドキュメント形式:DOCX

    • ドキュメント名:example.docx

  • 変換後

    • ファイル形式:PNG

    • 保存パス:oss://test-bucket/doc_images/{index}.png

      • b_dGVzdC1idWNrZXQ=:トランスコード完了後に test-bucket という名前のバケットに出力を保存します(dGVzdC1idWNrZXQ=test-bucket の Base64 エンコード値です)。

      • o_ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==:オブジェクトを doc_images ディレクトリに保存します。{index} 変数は example.docx のページ番号に置き換えられ、イメージのファイル名が生成されます(ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==doc_images/{index}.png の Base64 エンコード値です)。

    • 変換完了通知:Simple Message Queue (SMQ)(旧称 MNS)の test-topic という名前のトピックにメッセージが送信されます。

リクエスト例

// Convert the example.docx file to PNG images.
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 です。この制限は固定されています。

よくある質問

特定の Excel ワークシートを変換する方法

いいえ。OSS ドキュメント変換は Excel ワークブック内のすべてのワークシートを変換します。特定のワークシートを変換するには、IMM の CreateOfficeConversionTask 操作を呼び出し、SheetIndex パラメーターを設定してください。

関連ドキュメント

ドキュメント変換の詳細については、「document conversion」をご参照ください。