本快速指南提供了有关如何将 PDF 转换为 C# 中的图像的详细信息。您可以设置分辨率、高度、宽度和其他属性,例如设置默认字体、缩放图像以适应页面宽度等等。为了将 PDF 页面转换为图像,使用了 C# 代码,下面给出了将 PDF 文件转换为 PNG 图像的详细步骤。
在 C# 中将 PDF 转换为图像的步骤
- 使用 NuGet 包管理器安装 Aspose.PDF 以将 PDF 转换为图像
- 将源 PDF 文件加载到 Document 类对象中以转换为图像
- 创建分辨率对象以设置输出图像分辨率
- 使用分辨率对象初始化 PngDevice 类对象
- 使用 Document.Pages 集合解析源 PDF 中的所有页面
- 调用 PngDevice.Process 函数将每个 PDF 页面转换为图像并保存在磁盘上
在这里,您可以通过添加必要的引用然后加载目标 PDF 将 PDF 渲染为 C# 中的图像的分步详细信息。您可以为所有输出图像文件设置不同的配置,并解析所有 PDF 文件页面以转换为图像。最后,每个转换后的图像都保存到磁盘上的单独文件中。
在 C# 中将 PDF 导出为图像的代码
using Aspose.Pdf; | |
using Aspose.Pdf.Devices; | |
using System.IO; | |
namespace ConvertPdfToImageInCSharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
// Instantiate the license as the first step to avoid trial version restrictions and watermark | |
License PdfToImageLicense = new License(); | |
PdfToImageLicense.SetLicense("Aspose.PDF.lic"); | |
// Load the source PDF file to be converted to PDF | |
Document sourcePdfDoc = new Document("ConvertAllPagesToPng.pdf"); | |
// Create Resolution object | |
Resolution imgResolution = new Resolution(300); | |
// Initialize the PngDevice object to create and configure output images | |
PngDevice pngDevice = new PngDevice(imgResolution); | |
// Parse through all the pages in the PDF for conversion to image | |
for (int pageNumber = 1; pageNumber <= sourcePdfDoc.Pages.Count; pageNumber++) | |
{ | |
// Create the output file stream by providing different name for each image | |
using (FileStream fileStream = new FileStream($"image{pageNumber}_out.png", | |
FileMode.Create)) | |
{ | |
// Convert a particular page and save the image to stream | |
pngDevice.Process(sourcePdfDoc.Pages[pageNumber], fileStream); | |
// Close stream | |
fileStream.Close(); | |
} | |
} | |
} | |
} | |
} |
此代码使用 Document 类对象加载源 PDF,其中 Document 类包含用于迭代的 pages 集合。为了设置输出图像的不同属性,Resolution 和 PngDevice 对象被声明支持设置各种参数,如图像分辨率、高度、宽度、BarcodeOptimization、InterpolationHighQuality 和 OptimizeDimensions。请注意,您可以使用 BmpDevice、EmfDevice、GifDevice 和许多其他工具来创建不同类型的图像。
我们已经学习了使用 C#* 将 PDF 页面传输到图像的过程。如果您想从头开始学习 PDF 文件的创建,请参阅 如何在 C# 中创建 PDF 上的文章。