通過C#將圖像添加到PDF文檔

C# 庫,用於使用自己的 API 將圖像插入 PDF。

使用 C# 庫將圖像添加到 PDF 文件

為了在PDF中添加圖像,我們將使用[Aspose.PDF用於.NET](https://products.aspose.com/pdf/net)API,這是一個功能豐富,功能強大且易於使用的文檔操作API,適用於 net 平臺。打開 [NuGet](https://www.nuget.org/packages/aspose.pdf) 包管理器,搜索“.PDF”並安裝。您也可以從程式包管理器主控台使用以下命令。

Package Manager Console

PM > Install-Package Aspose.PDF

使用C#將圖像添加到 PDF


您需要使用 [Aspose.PDF for .NET](https://releases.aspose.com/pdf/net) 來嘗試環境中的代碼。

  1. 建立一個文件物件並打開輸入的 PDF 文件。
  2. 取得要新增影像的頁面。
  3. 將影像添加到頁面的資源集合中。
  4. 使用 GSave 運算子保存當前圖形狀態。
  5. 使用串聯矩陣運算子指定要放置影像的位置。
  6. 使用 Do 運算子在頁面上繪製圖像。
  7. 使用 GRestore 運算子保存更新的圖形狀態。
  8. 保存 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);