OSS'de depolanan belgeleri PNG, JPG, PDF veya TXT gibi hedef biçimlere dönüştürün ve sonuçları belirtilen bir yola kaydedin.
Senaryolar
Çevrimiçi önizleme: PDF, Word, Excel veya PPT belgelerini görsellere dönüştürerek web veya mobil cihazlarda indirmeye gerek kalmadan doğrudan önizleyin.
Platformlar arası uyumluluk: Belgelerin cihazlar ve işletim sistemleri arasında sorunsuz görüntülenmesini sağlayın.
Desteklenen giriş dosya türleri
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Başlangıç
Önkoşullar
OSS'de paket oluşturun, dönüştürülecek belgeyi pakete yükleyin ve pakete bir Intelligent Media Management (IMM) projesi bağlayın. IMM projesi, paket ile aynı bölgede bulunmalıdır.
IMM işleme için gerekli ilgili izinlere sahip olmanız gerekir.
Belge biçimini dönüştürme
Belge dönüştürme API'sini çağırmak ve sonuçları belirtilen bir pakete kaydetmek için Java, Python veya Go için OSS SDK'yı kullanın.
Java
Java için OSS SDK V3.17.4 veya sonraki bir sürüm gereklidir.
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
Python için OSS SDK 2.18.4 veya sonraki bir sürüm gereklidir.
# -*- 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
Go için OSS SDK 3.0.2 veya sonraki bir sürüm gereklidir.
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)
}
Parametre açıklaması
Eylem: doc/convert
Parametreler:
|
Parametre adı |
Tür |
Gerekli |
Açıklama |
|
target |
string |
Evet |
Çıktı nesnesinin biçimi. Geçerli değerler:
|
|
source |
string |
Hayır |
Kaynak dosya biçimi. Varsayılan olarak nesne adı uzantısı kullanılır. Geçerli değerler:
|
|
pages |
string |
Hayır |
Dönüştürülecek sayfa numaraları. Örneğin: |
Dönüştürülen belgeleri belirtilen bir pakete kaydetmek için sys/saveas kullanın. Farklı Kaydet. Dönüştürme sonucunu almak için notify parametresini kullanın. Bildirimler.
Olay bildirimleri
Belge dönüştürme işlemi eşzamansızdır. İşlem sonucunu yoklama yapmadan almak için Simple Message Queue (SMQ, eski adıyla MNS) ile olay bildirimlerini yapılandırın.
Olay bildirimlerini yapılandırma
İlgili API'ler
Gelişmiş özelleştirme için RESTful API'yi doğrudan çağırın. Kodunuzda imza hesaplamasını dahil edin. İmza Sürüm 4 (Önerilen).
Belge biçimini dönüştürme
-
Kaynak nesne
Belge biçimi: DOCX
Belge adı: example.docx
-
Hedef nesne
Nesne biçimi: PNG
-
Depolama yolu: oss://test-bucket/doc_images/{index}.png
b_dGVzdC1idWNrZXQ=: Dönüştürme tamamlandığında test-bucket adlı bir pakete kaydedilir (
dGVzdC1idWNrZXQ=değeri,test-bucketdeğerinin Base64 ile kodlanmış halidir).o_ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==: Nesne, {index} değişkenini kullanarak example.docx sayfa numaralarını dosya adı olarak doc_images dizinine kaydeder (
ZG9jX2ltYWdlcy97aW5kZXh9LnBuZw==değeri,doc_images/{index}.pngdeğerinin Base64 ile kodlanmış halidir).
Dönüştürme tamamlanma bildirimi:
test-topicadlı Simple Message Queue (SMQ, eski adıyla MNS) konusuna gönderilir
İşleme örneği
// 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
Notlar
Belge dönüştürme yalnızca eşzamansız işlemeyi (x-oss-async-process) destekler.
Anonim erişim desteklenmez.
Belge biçimi dönüştürme için desteklenen maksimum dosya boyutu 200 MB'tır ve bu değer değiştirilemez.
SSS
OSS belge dönüştürme, bir Excel sayfasının içeriğinin belirtilmesini destekler mi?
Hayır. OSS belge dönüştürme, bir Excel dosyasındaki tüm sayfaları dönüştürür. Belirli bir sayfayı dönüştürmek için SheetIndex parametresiyle IMM CreateOfficeConversionTask - Belge dönüştürme görevi oluşturma API'sini çağırın.