Tous les produits
Search
Centre de documentation

Object Storage Service:Conversion de format de document

Dernière mise à jour :Aug 18, 2026

Convertissez les documents stockés dans OSS vers des formats cibles tels que PNG, JPG, PDF ou TXT, et enregistrez les résultats dans un chemin d'accès spécifié.

Scénarios

  • Aperçu en ligne : convertissez les documents PDF, Word, Excel ou PPT en images pour un aperçu direct sur le web ou les appareils mobiles sans téléchargement.

  • Compatibilité multiplateforme : permettez une visualisation fluide des documents sur différents appareils et systèmes d'exploitation.

Types de fichiers d'entrée pris en charge

Type de fichier

Extension de fichier

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

Prise en main

Prérequis

Convertir le format du document

Utilisez le SDK OSS pour Java, Python ou Go afin d'appeler l'API de conversion de document et d'enregistrer les résultats dans un bucket spécifié.

Java

Le SDK OSS pour Java version 3.17.4 ou ultérieure est requis.

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 {
        // Specify the endpoint of the region in which the bucket is located.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain a credential from the 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.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket.
        String bucketName = "examplebucket";
        // Specify the name of the output object.
        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 in use, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Create a style variable of the string type to store document conversion parameters.
            String style = String.format("doc/convert,target_png,source_docx");
            // Create an 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);
            // Execute the asynchronous processing 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 {
            // Close your OSSClient.
            ossClient.shutdown();
        }
    }
}

Python

Le SDK OSS pour Python version 2.18.4 ou ultérieure est requis.

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

def main():
    # Obtain the temporary access credentials 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.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    # Specify the endpoint for the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
    region = 'cn-hangzhou'

    # Specify the name of the bucket. 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 output object.
    target_key = 'dest.png'

    # Create a style variable of the string type to store document conversion parameters.
    animation_style = 'doc/convert,target_png,source_docx'

    # Create a processing instruction, in which the name of the bucket and the name of the output object are Base64-encoded.
    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:
        # Execute the asynchronous processing 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

Le SDK OSS pour Go version 3.0.2 ou ultérieure est requis.

package main

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

func main() {
    // Obtain the temporary access credentials 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, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }
    // Create an OSSClient instance.
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
    // Specify the ID of the Alibaba Cloud region in which the bucket is located. 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 name of the bucket. 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 output object.
    targetKey := "dest.png"

    // Create a style variable of the string type to store document conversion parameters.
    animationStyle := "doc/convert,target_png,source_docx"

    // Create a processing instruction, in which the name of the bucket and the name of the output object are Base64-encoded.
    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)

    // Execute the asynchronous processing 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)
}

description des paramètres

Action : doc/convert

Paramètres :

Nom du paramètre

Type

Obligatoire

Description

target

string

Oui

Format de l'objet de sortie. Valeurs valides :

  • pdf

  • png

  • jpg

  • txt

source

string

Non

Format du fichier source. La valeur par défaut correspond à l'extension du nom de l'objet. Valeurs valides :

  • docx (requis lors de la conversion de documents HTML)

  • doc

  • pptx

  • ppt

  • pdf

  • xlsx

  • xls

pages

string

Non

Numéros de page à convertir.

Par exemple : 1,2,4-10 indique la conversion de la page 1, de la page 2 et des pages 4 à 10.

Utilisez sys/saveas pour enregistrer les documents convertis dans un bucket spécifié. Enregistrer sous. Pour recevoir le résultat de la conversion, utilisez le paramètre notify. Notifications.

Notifications d'événements

La conversion de document est asynchrone. Pour recevoir le résultat du traitement sans interrogation (polling), configurez des notifications d'événements avec Simple Message Queue (SMQ, anciennement MNS).

Configurer les notifications d'événements

Commencez par créer un topic de message dans la même région que votre bucket. Démarrage rapide pour le modèle basé sur les topics. Le nom du topic doit être encodé en Base64 URL-safe. Par exemple, test-topic devient dGVzdC10b3BpYw.

Exemple de code

Les SDK OSS pour Java, Python et Go prennent en charge la conversion de document.

Java

Le SDK OSS pour Java version 3.17.4 ou ultérieure est requis.

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 {
        // Specify the endpoint of the region in which the bucket is located.
        String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        // Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
        String region = "cn-hangzhou";
        // Obtain a credential from the 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.
        EnvironmentVariableCredentialsProvider credentialsProvider = CredentialsProviderFactory.newEnvironmentVariableCredentialsProvider();
        // Specify the name of the bucket.
        String bucketName = "examplebucket";
        // Specify the name of the output object.
        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 in use, call the shutdown method to release resources.
        ClientBuilderConfiguration clientBuilderConfiguration = new ClientBuilderConfiguration();
        clientBuilderConfiguration.setSignatureVersion(SignVersion.V4);
        OSS ossClient = OSSClientBuilder.create()
                .endpoint(endpoint)
                .credentialsProvider(credentialsProvider)
                .clientConfiguration(clientBuilderConfiguration)
                .region(region)
                .build();

        try {
            // Create a style variable of the string type to store document conversion parameters.
            String style = String.format("doc/convert,target_png,source_docx");
            // Create an 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);
            // Execute the asynchronous processing 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 {
            // Close your OSSClient.
            ossClient.shutdown();
        }
    }
}

Python

Le SDK OSS pour Python version 2.18.4 ou ultérieure est requis.

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

def main():
    # Obtain the temporary access credentials 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.
    auth = oss2.ProviderAuthV4(EnvironmentVariableCredentialsProvider())
    # Specify the endpoint for the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com.
    endpoint = 'https://oss-cn-hangzhou.aliyuncs.com'
    # Specify the ID of the Alibaba Cloud region in which the bucket is located. Example: cn-hangzhou.
    region = 'cn-hangzhou'

    # Specify the name of the bucket. 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 output object.
    target_key = 'dest.png'

    # Create a style variable of the string type to store document conversion parameters.
    animation_style = 'doc/convert,target_png,source_docx'

    # Create a processing instruction, in which the name of the bucket and the name of the output object are Base64-encoded.
    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:
        # Execute the asynchronous processing 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

Le SDK OSS pour Go version 3.0.2 ou ultérieure est requis.

package main

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

func main() {
    // Obtain the temporary access credentials 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, err := oss.NewEnvironmentVariableCredentialsProvider()
    if err != nil {
    fmt.Println("Error:", err)
    os.Exit(-1)
    }
    // Create an OSSClient instance.
    // Specify the endpoint of the region in which the bucket is located. For example, if the bucket is located in the China (Hangzhou) region, set the endpoint to https://oss-cn-hangzhou.aliyuncs.com. Specify your actual endpoint.
    // Specify the ID of the Alibaba Cloud region in which the bucket is located. 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 name of the bucket. 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 output object.
    targetKey := "dest.png"

    // Create a style variable of the string type to store document conversion parameters.
    animationStyle := "doc/convert,target_png,source_docx"

    // Create a processing instruction, in which the name of the bucket and the name of the output object are Base64-encoded.
    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)

    // Execute the asynchronous processing 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 connexes

Pour une personnalisation avancée, appelez directement l'API RESTful. Incluez le calcul de signature dans votre code. Version de signature 4 (recommandée).

Convertir le format du document

  • Objet source

    • Format du document : DOCX

    • Nom du document : example.docx

  • Objet de destination

    • Format de l'objet : PNG

    • Chemin de stockage : oss://test-bucket/doc_images/{index}.png

      • b_dGVzdC1idWNrZXQ=: Une fois la conversion terminée, enregistrement dans un bucket nommé test-bucket (dGVzdC1idWNrZXQ= est la valeur encodée en Base64 de test-bucket).

      • o_ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==: L'objet utilise la variable {index} pour enregistrer les images avec les numéros de page de example.docx comme noms de fichiers dans le répertoire doc_images (ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw== est la valeur encodée en Base64 de doc_images/{index}.png).

    • Notification de fin de conversion : envoi vers le topic Simple Message Queue (SMQ, anciennement MNS) nommé test-topic

Exemple de traitement

// Convert the example.docx file to PNG format image files.
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

notes

  • La conversion de document prend uniquement en charge le traitement asynchrone (x-oss-async-process).

  • L'accès anonyme n'est pas pris en charge.

  • La taille maximale de fichier prise en charge pour la conversion de format de document est de 200 Mo et ne peut pas être ajustée.

FAQ

La conversion de document OSS permet-elle de spécifier le contenu d'une feuille Excel ?

Non. La conversion de document OSS convertit toutes les feuilles d'un fichier Excel. Pour convertir une feuille spécifique, appelez l'API IMM CreateOfficeConversionTask - Créer une tâche de conversion de document avec le paramètre SheetIndex.

Références

Conversion de format de document.