ドキュメント変換機能を使用すると、さまざまな種類のドキュメントを目的のフォーマットに変換し、結果を指定された 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 |
使用方法
前提条件
Object Storage Service (OSS) にバケットを作成し、ソースドキュメントをバケットにアップロードし、そのバケットをIntelligent Media Management (IMM) プロジェクトに関連付けてください。IMM プロジェクトはバケットと同じリージョンにある必要があります。
IMM によるドキュメント処理に必要な権限を保有している必要があります。
ドキュメントの変換
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 | はい | 出力ファイル形式。有効な値:
|
source | string | いいえ | ソースファイル形式。デフォルトでは、オブジェクトのファイル拡張子から形式が決定されます。有効な値:
|
pages | string | いいえ | 変換するページ番号。 たとえば、 |
変換後のドキュメントを指定されたバケットに保存するには、sys/saveas パラメーターを使用する必要があります。詳細については、「sys/saveas」をご参照ください。変換タスクの処理結果を受け取る必要がある場合は、notify パラメーターを使用します。詳細については、「メッセージ通知」をご参照ください。
高度なシナリオ
ドキュメント変換タスクは非同期リクエストとして送信されます。つまり、即時の応答には変換の最終結果(成功または失敗など)は含まれません。結果を取得するには、Simple Message Queue (SMQ)(旧称 MNS)を使用してイベント通知を設定してください。これにより、タスク完了時に即座に通知が届き、ステータスをポーリングする必要がなくなります。
イベント通知
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」をご参照ください。