Work with Images in PDF using C#

Manipulate images in PDF document. Use Aspose.PDF for .NET to modify PDF documents programmatically

Most popular action with Images in C#

Add Image to PDF Document Using C# Library

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 in an Existing PDF File - C#

Example: C#

var inputFile = Path.Combine(dataDir, "add-image.pdf");
var outputFile = Path.Combine(dataDir, "add-image_out.pdf");
var imageFile = Path.Combine(dataDir, "aspose-logo.jpg");
var pdfDocument = new Aspose.Pdf.Document(inputFile);
int lowerLeftX = 100;
int lowerLeftY = 100;
int upperRightX = 200;
int upperRightY = 200;

var page = pdfDocument.Pages[1];
var imageStream = new FileStream(imageFile, FileMode.Open);
page.Resources.Images.Add(imageStream);
page.Contents.Add(new Aspose.Pdf.Operators.GSave());
var rectangle = new Aspose.Pdf.Rectangle(lowerLeftX, lowerLeftY, upperRightX, upperRightY);
var matrix = new Aspose.Pdf.Matrix([rectangle.URX - rectangle.LLX, 0, 0, rectangle.URY - rectangle.LLY, rectangle.LLX, rectangle.LLY]);
page.Contents.Add(new Aspose.Pdf.Operators.ConcatenateMatrix(matrix));
var 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());

pdfDocument.Save(outputFile);