Add Images to PDF document via C#

Insert images to PDF document programmatically using Aspose.PDF for .NET

Add Image to PDF Document Using C# Tool

In order to add Image in PDF, we’ll use Aspose.PDF for .NET API which is a feature-rich, powerful and easy to use document manipulation API for net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Package Manager Console

PM > Install-Package Aspose.PDF

Add Image to PDF using C#


You need Aspose.PDF for .NET to try the code in your environment.

  1. Create a Document object and open the input PDF document.
  2. Get the page you want to add an image.
  3. Add the image into the page’s Resources collection.
  4. Use the GSave operator to save the current graphical state.
  5. Use ConcatenateMatrix operator to specify where the image is to be placed.
  6. Use the Do operator to draw the image on the page.
  7. Use GRestore operator to save the updated graphical state.
  8. Save the PDF file.

Add Image to PDF document - C#

This sample code shows how to add Images into PDF page - 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);