PDF处理控件Aspose.PDF功能演示:使用C#将PDF页面转换为PNG图像

PDF被认为是适合打印和共享的文档格式。但是,在某些情况下,需要将PDF文件中的页面转换为PNG图像。例如,当要将PDF页面嵌入网页或生成PDF封面等时。在本文中,将学习如何在.NET应用程序中自动将PDF转换为PNG。

  • PDF至PNG的转换
  • 将PDF单页转换为PNG

点击下载最新版Aspose.PDF(qun:761297826)icon-default.png?t=N7T8https://www.evget.com/product/565/download


使用C#将PDF至PNG C#的转换

以下是使用Aspose.PDF for .NET将PDF文档中的页面转换为PNG图像的步骤。

  • 使用Document类加载PDF文件。
  • 使用Document.Pages集合循环浏览PDF页面。
  • 在每次迭代中,为输出的PNG图像创建一个FileStream对象。
  • 创建并初始化一个PngDevice对象的对象。
  • 使用PngDevice.Process(Page,Stream)方法将页面转换为PNG 。

下面的代码示例演示如何使用C#将PDF中的页面转换为PNG。

// Open PDF document
Document pdfDocument = new Document("Document.pdf");

// Loop through each page
foreach (var page in pdfDocument.Pages)
{
    // Create file stream for output image
    using (FileStream imageStream = new FileStream(string.Format("page_{0}.png", page.Number), FileMode.Create))
    {
        // Create Resolution object
        Resolution resolution = new Resolution(300);
        
        // Create Png device with specified attributes
        // Width, Height, Resolution
        PngDevice PngDevice = new PngDevice(500, 700, resolution);

        // Convert a particular page and save the image to stream
        PngDevice.Process(page, imageStream);

        // Close stream
        imageStream.Close();
    }
}

使用C#将PDF单页转换为PNG

有时只能将PDF的一页转换为PNG。在这种情况下,您可以从Document.Pages集合中访问所需的页面。以下是仅将PDF的单个页面转换为PNG的步骤。

  • 使用Document类加载PDF文件。
  • 为输出的PNG图像创建FileStream。
  • 创建并初始化PngDevice对象。
  • 使用PngDevice.Process(Page,Stream)将页面转换为PDF 。

以下代码示例显示了如何将PDF中的单个页面转换为PNG。

// Open PDF document
Document pdfDocument = new Document("Document.pdf");

// Set page index
int page = 1;

// Create FileStream for the output image
using (FileStream imageStream = new FileStream(string.Format("page_{0}.png", page), FileMode.Create))
{
    // Create Resolution object
    Resolution resolution = new Resolution(300);

    // Create Png device with specified attributes
    // Width, Height, Resolution
    PngDevice PngDevice = new PngDevice(500, 700, resolution);

    // Convert a particular page and save the image to stream
    PngDevice.Process(pdfDocument.Pages[page], imageStream);

    // Close stream
    imageStream.Close();
}

猜你喜欢

转载自blog.csdn.net/m0_67129275/article/details/132871727