從 PDF 文件中提取圖像是構建文檔處理流水線時的常見需求,尤其是用於生成縮略圖或在其他地方重新使用圖形。GroupDocs.Parser Cloud SDK for .NET 提供了強大的 API,使此任務在 C# 中變得簡單直觀。在本指南中,您將學習如何上傳 PDF、檢索所有嵌入的圖像、將其本地保存,並可選擇清理遠端文件,並提供完整的代碼和 REST 示例。
在 C# 中從 PDF 文檔提取圖像的步驟
- 將 PDF 上傳至 GroupDocs Cloud 儲存: 使用
StorageApi.UploadFile將來源 PDF 放置於雲端。
var uploadRequest = new UploadFileRequest(remotePdfPath, File.ReadAllBytes(localPdfPath));
storageApi.UploadFile(uploadRequest);
此呼叫確保檔案可供解析。
- 請求文件圖像:呼叫
ParserApi.GetDocumentImages並傳入GetDocumentImagesRequest。
var imagesRequest = new GetDocumentImagesRequest(remotePdfPath);
ImagesResult imagesResult = parserApi.GetDocumentImages(imagesRequest);
回應包含一系列 ImageInfo 物件,每個物件都包含 Base64 資料和中繼資料。請參閱 API 參考 以獲取完整細節。
- 解碼並保存每個圖像:遍歷
imagesResult.Images,將 Base64 字串轉換為位元組陣列,並將檔案寫入磁碟。
foreach (ImageInfo imgInfo in imagesResult.Images)
{
byte[] imageBytes = Convert.FromBase64String(imgInfo.Base64Data);
string extension = imgInfo.FileExtension?.TrimStart('.').ToLower() ?? "bin";
string fileName = $"extracted_page{imgInfo.PageNumber}_img{imgInfo.ImageIndex}_{imageCounter}.{extension}";
File.WriteAllBytes(fileName, imageBytes);
}
控制台會記錄已保存的檔案名稱、尺寸和 DPI 以供驗證。
- (可選)清理遠端 PDF:提取後,您可以刪除已上傳的文件以保持儲存空間整潔。
var deleteRequest = new DeleteFileRequest(remotePdfPath);
storageApi.DeleteFile(deleteRequest);
此步驟已包裹在 try‑catch 區塊中,以忽略任何清理錯誤。
- 檢查輸出: 控制台將顯示類似
Total images extracted: 12的摘要,確認提取成功。
完整程式碼範例:從 PDF 文件中提取圖像,使用 GroupDocs.Parser
以下範例示範了上述完整工作流程。它包括配置、上傳、圖像提取、保存以及可選的清理。
using System;
using System.IO;
using System.Collections.Generic;
using GroupDocs.Parser.Cloud.Sdk.Api;
using GroupDocs.Parser.Cloud.Sdk.Client;
using GroupDocs.Parser.Cloud.Sdk.Model;
using GroupDocs.Parser.Cloud.Sdk.Model.Requests;
namespace ExtractImagesFromPdf
{
class Program
{
static void Main(string[] args)
{
// Configuration – replace with your actual credentials
var config = new Configuration
{
ClientId = "YOUR_CLIENT_ID",
ClientSecret = "YOUR_CLIENT_SECRET"
};
// APIs
var storageApi = new StorageApi(config);
var parserApi = new ParserApi(config);
// Input PDF path (local) and remote name in storage
const string localPdfPath = "input.pdf";
const string remotePdfPath = "input.pdf";
try
{
// -------------------------------------------------
// 1. Upload PDF to GroupDocs Cloud storage (if not already there)
// -------------------------------------------------
if (!File.Exists(localPdfPath))
throw new FileNotFoundException($"Local file not found: {localPdfPath}");
var uploadRequest = new UploadFileRequest(remotePdfPath, File.ReadAllBytes(localPdfPath));
storageApi.UploadFile(uploadRequest);
// -------------------------------------------------
// 2. Retrieve document images (all pages)
// -------------------------------------------------
var imagesRequest = new GetDocumentImagesRequest(remotePdfPath);
ImagesResult imagesResult = parserApi.GetDocumentImages(imagesRequest);
// -------------------------------------------------
// 3. Save each extracted image to disk
// -------------------------------------------------
int imageCounter = 0;
foreach (ImageInfo imgInfo in imagesResult.Images)
{
// Image data is returned as Base64 string
byte[] imageBytes = Convert.FromBase64String(imgInfo.Base64Data);
// Build a descriptive file name
string extension = imgInfo.FileExtension?.TrimStart('.').ToLower() ?? "bin";
string fileName = $"extracted_page{imgInfo.PageNumber}_img{imgInfo.ImageIndex}_{imageCounter}.{extension}";
File.WriteAllBytes(fileName, imageBytes);
Console.WriteLine($"Saved: {fileName} ({imgInfo.Width}x{imgInfo.Height} px, {imgInfo.Resolution} DPI)");
imageCounter++;
}
Console.WriteLine($"Total images extracted: {imageCounter}");
}
catch (ApiException apiEx)
{
Console.Error.WriteLine($"GroupDocs API error: {apiEx.ErrorCode} - {apiEx.Message}");
}
catch (Exception ex)
{
Console.Error.WriteLine($"Unexpected error: {ex.Message}");
}
finally
{
// -------------------------------------------------
// 4. Optional cleanup – delete the uploaded PDF from storage
// -------------------------------------------------
try
{
var deleteRequest = new DeleteFileRequest(remotePdfPath);
storageApi.DeleteFile(deleteRequest);
}
catch
{
// Ignored – cleanup is optional
}
}
}
}
}
注意: 此程式碼範例展示了核心功能。在將其用於您的專案之前,請確保更新所有檔案路徑和設定值以符合實際環境,驗證所有必要的相依項已正確安裝,並在開發環境中徹底測試。如果您遇到任何問題,請參閱官方文件或聯繫支援團隊以獲得協助。
使用 cURL 透過 REST API 提取圖像
相同的操作可以透過直接的 REST 呼叫來執行。以下是一個最小的 cURL 工作流程。
- 取得存取權杖 (OAuth 2.0 用戶端憑證授權)。
curl -X POST "https://api.groupdocs.cloud/v2.0/oauth2/token" \
-H "Content-Type: application/x-www-form-urlencoded" \
-d "grant_type=client_credentials&client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET"
回應中包含 access_token。
- 上傳 PDF 到雲端儲存。
curl -X PUT "https://api.groupdocs.cloud/v2.0/storage/file/input.pdf" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" \
-H "Content-Type: application/pdf" \
--data-binary "@input.pdf"
- 請求圖像 針對已上傳的文件。
curl -X GET "https://api.groupdocs.cloud/v2.0/parser/input.pdf/images" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN"
JSON 回應包含一個圖像陣列,其中包含 base64Data、fileExtension、pageNumber 等。
- 儲存每張圖像 本機(示例使用
jq和base64)。
curl -X GET "https://api.groupdocs.cloud/v2.0/parser/input.pdf/images" \
-H "Authorization: Bearer YOUR_ACCESS_TOKEN" | \
jq -r '.images[] | "\(.pageNumber)_\(.imageIndex).\(.fileExtension) \(.base64Data)"' | \
while read filename b64; do
echo "$b64" | base64 -d > "$filename"
done
如需了解端點和參數的更多詳細資訊,請參閱官方 API 文檔。
準備環境
- 透過 NuGet 安裝 .NET 用戶端程式庫:
dotnet add package GroupDocs.Parser-Cloud
此套件可從官方下載頁面取得。
確保已安裝 .NET 6.0 或更高版本,並擁有有效的 GroupDocs Cloud 帳戶及客戶端憑證。
(可選)克隆示例倉庫以供參考:
git clone https://github.com/groupdocs-parser-cloud/groupdocs-parser-cloud-dotnet.git
什麼使 GroupDocs.Parser 適合圖像提取
- 直接圖像檢索:
GetDocumentImages呼叫返回原始格式的圖像,無需額外轉換步驟。 - Base64 交付:圖像以 Base64 字串形式提供,便於在任何語言中解碼。
- 頁面級元資料:每個
ImageInfo包含頁碼、尺寸、解析度和索引,有助於組織提取的資產。 - 支援所有常見點陣圖格式:PNG、JPEG、BMP、GIF、TIFF 等均會如 PDF 中存儲的那樣完整保留。
- 可擴展的雲端處理:大型 PDF 由 GroupDocs 伺服器處理,減少應用程式的記憶體壓力。
配置圖像提取選項
雖然基本範例即開即用,但您可以微調請求:
- 指定頁面範圍:將
pages = "1-5"添加到GetDocumentImagesRequest以限制提取。 - 設定影像品質:如果需要壓縮輸出,請使用
imageQuality參數(0‑100)。 - 依格式篩選:提供
fileExtensions = ["png","jpeg"]以僅接收所選格式。
這些選項已在 API 參考 中記錄。
結論
在 C# 中從 PDF 文檔提取圖像變得簡單且可靠,只需利用 GroupDocs.Parser Cloud SDK for .NET。該 SDK 處理上傳、解析和 Base64 轉換,讓您專注於保存文件並將其整合到工作流程中。請務必保護您的客戶端憑證,遵守許可條款,並考慮在 臨時許可頁面 獲取臨時許可以進行評估。使用提供的代碼和 REST 示例,您即可在任何 .NET 應用程序中添加強大的 PDF 圖像提取功能。
常見問題
如何使用 C# 從 PDF 文檔中提取圖像?
使用 Parser API 的 GetDocumentImages 方法,在使用 StorageApi.UploadFile 上傳 PDF 後。解碼返回的 Base64 字串並寫入磁碟,如代碼示例所示。
如果 PDF 受密碼保護怎麼辦?
在請求模型中包含密碼。 SDK 會在提取圖像之前解密文件。 請參閱文檔以獲取確切的屬性名稱。
我可以將提取限制在特定頁面嗎?
是的,將 pages 屬性設定在 GetDocumentImagesRequest 上為逗號分隔的列表或範圍(例如,"1-3,5")。API 將僅返回這些頁面的圖像。
是否對提取的圖像有大小限制?
SDK 返回原始圖像數據,未進行縮放。如果需要更小的文件,請使用任何圖像處理庫對保存的圖像進行後處理。
