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

C# 使用自己的 API 将图像插入到 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 文档。 1.获取要添加图像的页面。 1.将图像添加到页面的资源集合中。 1.使用 GSave 运算符保存当前的图形状态。 1.使用 concateNateMatrix 运算符指定图像的放置位置。 1.使用 Do 运算符在页面上绘制图像。 1.使用 GreStore 运算符保存更新的图形状态。 1.保存 PDF 文件。

将图像添加到 PDF 文档-C#。

<% images-add.code-block.subtitle %>


    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);