從雲端儲存的 PDF 文件中提取單獨的圖像是現代 C# 應用程式常見的需求,因為它們需要重新使用或分析視覺資產。Aspose.PDF for .NET 提供強大的雲端 API,簡化此任務。您將學習如何使用 C# 和 Aspose.PDF Cloud SDK 從 PDF 檔案中提取圖像。完成本指南後,您將擁有一個完整、可投入生產的解決方案,包含 SDK 程式碼以及等效的 cURL 呼叫。

C# 中 PDF 圖像提取的需求

開發人員在構建雲原生文件處理管道時,通常需要從位於遠端儲存的 PDF 中提取圖形。典型的需求包括:

  • 存取儲存在 Aspose Cloud 儲存體中的 PDF。
  • 能夠列舉文件中嵌入的每個圖像物件。
  • 以原始格式下載每個圖像,且不會失真。
  • 最小的記憶體佔用,以在伺服器上處理大型 PDF。

通用檔案系統工具無法直接存取雲端儲存,且使用桌面軟體的手動提取無法滿足自動化工作負載的規模需求。使用雲端就緒的程式庫進行程式化處理是必不可少的。

Aspose.PDF Cloud SDK for .NET 如何適用於 PDF 圖像提取

Aspose.PDF Cloud SDK for .NET 提供基於 REST 的 API,可用於處理存儲在 Aspose Cloud 中的 PDF。它提供諸如 GetDocumentImages 之類的方法來列出圖像,並使用 GetImage 下載它們,全部通過 HTTPS。該 SDK 處理身份驗證、存儲管理以及二進制數據流,讓您專注於業務邏輯。

SDK 也支援透過分塊上傳和高效的記憶體使用來處理大型檔案,符合伺服器端應用程式的效能需求。詳細的 API 使用說明可在官方文件以及API 參考中找到。

建置解決方案:在 C# 中從 PDF 提取圖像

安裝 Aspose.PDF Cloud SDK for .NET

首先,將 SDK 套件加入您的專案。

dotnet add package Aspose.PDF-Cloud

您也可以從下載頁面下載二進位檔案。

設定 Aspose Cloud 憑證

使用您的客戶端 ID 和密鑰建立配置物件。

var config = new Configuration
{
    ClientId = "YOUR_CLIENT_ID",
    ClientSecret = "YOUR_CLIENT_SECRET"
};
var pdfApi = new PdfApi(config);

Configuration 類別的文件位於 API 參考。

將 PDF 上傳至雲端儲存

如果 PDF 尚未在 Aspose Cloud 儲存中,請上傳它。

using (var fileStream = File.OpenRead(pdfFileName))
{
    byte[] fileBytes = new byte[fileStream.Length];
    fileStream.Read(fileBytes, 0, fileBytes.Length);
    pdfApi.UploadFile(Path.Combine("Temp", pdfFileName), fileBytes);
}

UploadFile 方法會將檔案儲存在 Temp 資料夾下。

檢索嵌入圖像的列表

呼叫 API 以取得每張圖片的資訊。

ImagesResponse imagesResponse = pdfApi.GetDocumentImages(pdfFileName);

ImagesResponse 包含一個 ImageInfo 物件的集合,每個物件都有 Id 和 ImageFormat。

下載每張圖片並儲存至本機

遍歷圖像列表,下載並寫入磁碟。

foreach (ImageInfo imageInfo in imagesResponse.Images.List)
{
    int imageId = imageInfo.Id ?? 0;
    string format = imageInfo.ImageFormat?.ToLower() ?? "png";
    string outputFileName = $"extracted_image_{imageId}.{format}";
    byte[] imageBytes = pdfApi.GetImage(pdfFileName, imageId);
    File.WriteAllBytes(outputFileName, imageBytes);
}

此迴圈保留原始圖像格式,並建立名為 extracted_image_<id>.<ext> 的檔案。

使用雲端儲存從 PDF 提取圖像的完整工作範例

以下程式碼示範了從驗證到清理的完整工作流程。

using System;
using System.IO;
using Aspose.Pdf.Cloud.Sdk.Api;
using Aspose.Pdf.Cloud.Sdk.Client;
using Aspose.Pdf.Cloud.Sdk.Model;

class ExtractImagesFromPdf
{
    static void Main()
    {
        // Replace with your actual Aspose Cloud credentials
        string clientId = "YOUR_CLIENT_ID";
        string clientSecret = "YOUR_CLIENT_SECRET";

// Initialize Aspose.PDF Cloud configuration
        var config = new Configuration
        {
            ClientId = clientId,
            ClientSecret = clientSecret
        };
        var pdfApi = new PdfApi(config);

// PDF file name (must be present in Aspose Cloud storage)
        string pdfFileName = "input.pdf";

// Optional: upload the PDF to cloud storage if it does not exist there
        if (!File.Exists(pdfFileName))
        {
            Console.WriteLine($"Local file '{pdfFileName}' not found.");
            return;
        }
        using (var fileStream = File.OpenRead(pdfFileName))
        {
            byte[] fileBytes = new byte[fileStream.Length];
            fileStream.Read(fileBytes, 0, fileBytes.Length);
            pdfApi.UploadFile(Path.Combine("Temp", pdfFileName), fileBytes);
        }

// Retrieve list of images embedded in the PDF
        ImagesResponse imagesResponse = pdfApi.GetDocumentImages(pdfFileName);
        if (imagesResponse?.Images?.List == null || imagesResponse.Images.List.Count == 0)
        {
            Console.WriteLine("No images found in the PDF.");
            return;
        }

// Extract each image and save locally
        foreach (ImageInfo imageInfo in imagesResponse.Images.List)
        {
            int imageId = imageInfo.Id ?? 0;
            string format = imageInfo.ImageFormat?.ToLower() ?? "png";
            string outputFileName = $"extracted_image_{imageId}.{format}";

// Download image bytes from the cloud
            byte[] imageBytes = pdfApi.GetImage(pdfFileName, imageId);
            if (imageBytes == null || imageBytes.Length == 0)
            {
                Console.WriteLine($"Failed to download image ID {imageId}.");
                continue;
            }

// Write image to local file system
            File.WriteAllBytes(outputFileName, imageBytes);
            Console.WriteLine($"Image ID {imageId} saved as '{outputFileName}'.");
        }

// Optional: clean up uploaded PDF from cloud storage
        pdfApi.DeleteFile(Path.Combine("Temp", pdfFileName));
    }
}

注意: 此程式碼範例展示了核心功能。在將其用於您的專案之前,請確保更新任何檔案路徑和設定值以符合實際環境,驗證所有必要的相依項目已正確安裝,並在開發環境中徹底測試。如果遇到任何問題,請參閱官方文件或聯繫支援團隊以獲得協助。

使用 cURL 和 REST API 執行 PDF 圖像提取

以下是等效的 cURL 命令,可在不編寫 C# 代碼的情況下執行相同的操作。

1. 驗證並取得存取權杖

curl -X POST "https://api.aspose.cloud/v3.0/oauth2/token?grant_type=client_credentials" \
     -u "YOUR_CLIENT_ID:YOUR_CLIENT_SECRET"

回應包含一個在後續呼叫中使用的 access_token。

2. 上傳來源 PDF

curl -X PUT "https://api.aspose.cloud/v3.0/pdf/storage/file/Temp/input.pdf" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -T "input.pdf"

3. 列出嵌入式圖像

curl -X GET "https://api.aspose.cloud/v3.0/pdf/input.pdf/images" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN"

The JSON 回應包含圖像 ID 與格式的陣列。

4. 下載每張圖片

curl -X GET "https://api.aspose.cloud/v3.0/pdf/input.pdf/images/1" \
     -H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
     -o "extracted_image_1.png"

將 1 替換為前一步中的實際圖像 ID。對所有 ID 重複此命令。

如需更多詳細資訊,請參閱官方 API 文件。

PDF 圖像提取的配置選項

設定儲存資料夾

您可以透過修改 UploadFile 和 DeleteFile 呼叫中的路徑來變更預設的儲存資料夾。例如,使用 "Documents" 取代 "Temp"。

選擇目標影像格式

SDK 會返回原始格式,但您可以在保存檔案時指定不同的副檔名來進行轉換。如果需要統一的輸出(例如 png),請在下載迴圈中調整 format 變數。

控制請求逾時

PdfApi 用戶端允許您設定自訂逾時時間:

pdfApi.Configuration.Timeout = 300000; // 5 minutes

增加逾時時間有助於處理非常大的 PDF。

結論

從雲端儲存的 PDF 檔案中提取圖像變得簡單,使用 Aspose.PDF for .NET。SDK 處理驗證、儲存和圖像檢索,讓您專注於應用程式邏輯。請記得為正式環境取得適當的授權;產品頁面提供價格資訊,您亦可從臨時授權頁面取得臨時授權。使用提供的程式碼和 cURL 範例,您即可將 PDF 圖像提取整合到任何 .NET 雲端服務中。

常見問題

如何使用 Aspose.PDF Cloud SDK for .NET 從 PDF 中提取圖像?
使用 PdfApi.GetDocumentImages 方法列出圖像,並使用 PdfApi.GetImage 下載每個圖像。完整的工作流程在上面的程式碼示例中說明。

我可以在不編寫任何程式碼的情況下從 PDF 中提取圖像嗎?
是的,可以使用 REST API 搭配 cURL 命令執行相同的操作,如「透過 cURL 和 REST API 執行 PDF 圖像提取」章節所示。

從 PDF 中可以提取哪些圖像格式?
API 會返回每個嵌入圖像的原始格式,例如 PNG、JPEG、BMP,或 TIFF。您可以檢查 ImageInfo.ImageFormat 屬性以確定格式。

我需要許可證才能在生產環境中運行嗎?
生產部署需要商業許可證。您可以在產品頁面查看價格,並從臨時許可證頁面獲取臨時許可證。

Read More