PDF处理控件aspose.PDF功能演示:在 C# .NET 中将图像转换为 PDF

本文将为你介绍如何在 C++ 中将PDF转换为Doc 、Docx 。

在某些情况下,您可能需要将PNG、JPG或其他图像文件转换为PDF文档。这在将扫描的发票页面转换为 PDF 等场景中可能很有用。在本文中,您将学习如何在 C# 中将图像转换为 PDF 格式。我们还将演示如何以编程方式将多个图像转换为 PDF。

第一、C# Image to PDF Converter API – 免费下载

对于图像到 PDF 的转换,我们将使用Aspose.PDF for .NET。它是一个功能强大的 PDF API,可让您从 .NET 应用程序中创建和操作 PDF 文件。此外,它还提供 PDF 文件的高保真来回转换。您可以下载API 或使用NuGet安装它。

PM> Install-Package Aspose.Pdf
第二、在 C# 中将图像转换为 PDF

让我们先来看看如何在 C# 中将单个图像转换为 PDF 文件。以下是执行此操作的步骤。

  • 创建文档类的实例。
  • 使用Document.Pages.Add()方法向 PDF 文档添加一个新页面并设置页面的属性。
  • 将图像文件加载到FileStream对象中。
  • 使用Page.Paragraphs.Add(Image)方法向页面添加新图像。
  • 使用Image.ImageStream属性设置图像的流。
  • 最后,使用Document.Save(String)方法保存 PDF 文档。

以下代码示例显示了如何在 C# 中将 PNG 图像转换为 PDF。

// Create a new documentDocument doc = new Document();// Path of the image filestring imageFile = @"aspose.png";// Add a page to pages collection of documentvar page = doc.Pages.Add();// Load image into streamFileStream imageStream = new FileStream(imageFile, FileMode.Open);// Set margins so image will fit, etc.page.PageInfo.Margin.Bottom = 0;page.PageInfo.Margin.Top = 0;page.PageInfo.Margin.Left = 0;page.PageInfo.Margin.Right = 0;page.CropBox = new Aspose.Pdf.Rectangle(0, 0, 400, 400);// Create an image objectImage image1 = new Image();// Add the image into paragraphs collection of the sectionpage.Paragraphs.Add(image1);// Set the image file streamimage1.ImageStream = imageStream;// Save resultant PDF filedoc.Save("image-to-pdf.pdf");
第三、在 C# 中将多个图像转换为 PDF

以下是在 C# 中将多个图像转换为单个 PDF 文件的步骤。

  • 创建文档类的实例。
  • 使用Directory.GetFiles(string)方法获取数组中图像文件名称的列表。
  • 对于列表中的每个图像文件,执行以下操作: 使用Document.Pages.Add()方法向 PDF 文档添加一个新页面并设置页面的属性。
  • 将图像文件加载到FileStream对象中。
  • 使用Page.Paragraphs.Add(Image)方法向页面添加新图像。
  • 使用Image.ImageStream属性设置图像的流。
  • 最后,使用Document.Save(String)方法保存 PDF 文档。

以下代码示例显示了在 C# 中将多个图像转换为单个 PDF。

// Create a new documentDocument doc = new Document();// Access image files in the folderstring[] fileList = Directory.GetFiles(@"D:/images/");foreach (String file in fileList){// Add a page to pages collection of documentvar page = doc.Pages.Add();// Load image into streamFileStream imageStream = new FileStream(file, FileMode.Open);// Set margins so image will fit, etc.page.PageInfo.Margin.Bottom = 0;page.PageInfo.Margin.Top = 0;page.PageInfo.Margin.Left = 0;page.PageInfo.Margin.Right = 0;page.CropBox = new Pdf.Rectangle(0, 0, 400, 400);// Create an image objectImage image1 = new Image();// Add the image into paragraphs collection of the sectionpage.Paragraphs.Add(image1);// Set the image file streamimage1.ImageStream = imageStream;}// Save resultant PDF filedoc.Save("multiple-images-to-pdf.pdf");

以上便是如何在 C# .NET 中将图像转换为 PDF详细步骤,要是您还有其他关于产品方面的问题,欢迎咨询我们,或者加入我们官方技术交流群。


欢迎下载|体验更多Aspose产品

获取更多信息请咨询在线客服 或 加入Aspose技术交流群(
标签:

来源:慧都

声明:本站部分文章及图片转载于互联网,内容版权归原作者所有,如本站任何资料有侵权请您尽早请联系jinwei@zod.com.cn进行处理,非常感谢!

上一篇 2023年1月3日
下一篇 2023年1月3日

相关推荐

发表回复

登录后才能评论