通过 C# 将图像添加到 PDF 文档

使用适用于 .NET 库的 Aspose.PDF 以编程方式将图像插入到 PDF 文档

使用 C# 工具将图像添加到 PDF 文档

为了添加 PDF 格式的图像,我们将使用 Aspose.PDF for .NET API,这是一款功能丰富、功能强大且易于使用的适用于 net 平台的文档处理 API。打开 NuGet 软件包管理器,搜索 aspose.pdf 然后安装。您也可以从软件包管理器控制台使用以下命令。

Package Manager Console

PM > Install-Package Aspose.PDF

使用 C# 将图像添加到 PDF


你需要 Aspose.PDF for .NET 在你的环境中试用代码。

  1. 创建文档对象并打开输入 PDF 文档。
  2. 获取要添加图像的页面。
  3. 将图像添加到页面的资源集合中。
  4. 使用 GSave 运算符保存当前的图形状态。
  5. 使用 concateNateMatrix 运算符指定图像的放置位置。
  6. 使用 Do 运算符在页面上绘制图像。
  7. 使用 GreStore 运算符保存更新的图形状态。
  8. 保存 PDF 文件。

向 PDF 文档添加图片-C#

此示例代码说明如何将图像添加到 PDF 页面-C#


    Document pdfDocument = new Document(dataDir+ "AddImage.pdf");
    int lowerLeftX = 100;
    int lowerLeftY = 100;
    int upperRightX = 200;
    int upperRightY = 200;

    Page page = pdfDocument.Pages[1];

    FileStream imageStream = new FileStream(dataDir + "aspose-logo.jpg", FileMode.Open);

    page.Resources.Images.Add(imageStream);

    page.Contents.Add(new Aspose.Pdf.Operators.GSave());

    Aspose.Pdf.Rectangle rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
    Matrix matrix = new Matrix(new double[] { rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY });

    page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
    XImage ximage = page.Resources.Images[page.Resources.Images.Count];

    page.Contents.Add(new Aspose.Pdf.Operators.Do(ximage.Name));

    page.Contents.Add(new Aspose.Pdf.Operators.GRestore());
    dataDir = dataDir + "AddImage_out.pdf";
    
    pdfDocument.Save(dataDir);