从 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的摘要,确认提取成功。
完整代码示例:使用 GroupDocs.Parser 从 PDF 文档中提取图像
以下示例演示了上述完整工作流。它包括配置、上传、图像提取、保存以及可选的清理。
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 图像提取功能。
FAQs
如何使用 C# 从 PDF 文档中提取图像?
在使用 StorageApi.UploadFile 上传 PDF 后,使用 Parser API 的 GetDocumentImages 方法。解码返回的 Base64 字符串并写入磁盘,如代码示例所示。
如果 PDF 受密码保护怎么办?
在请求模型中包含密码。SDK 将在提取图像之前解密文件。请参阅文档以获取确切的属性名称。
我可以将提取限制在特定页面吗?
是的,在 GetDocumentImagesRequest 上设置 pages 属性为逗号分隔的列表或范围(例如 "1-3,5")。API 将仅返回这些页面的图像。
提取的图像是否有大小限制?
SDK 返回原始图像数据,不进行缩放。如果需要更小的文件,请使用任何图像处理库对保存的图像进行后处理。
