How to replace the existing image on the PDF file in C#

Sometimes when we want to change the existing image on the PDF file with a new image, we will find it is not so easy to accomplish it. With the help of Spire.PDF, we can directly use the method of page.ReplaceImage to replace the existing image with the new image. This article will show you how to replace the image on the PDF file in C#.

Firstly, view the original PDF file that the image on it needs to be replaced.

How to replace the existing image on the PDF file in C#

Step 1: Create a new instance of PdfDocument and load a PDF document from file.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("Test.pdf");

Step 2: Get the first page of the loaded PDF file.

PdfPageBase page = doc.Pages[0];

Step 3: Load the new image that we want to replace the existing image.

PdfImage image = PdfImage.FromFile("image.png");

Step 4: Replace first image on the PDF file with the new loaded image.

page.ReplaceImage(0, image);

Step 5: Save the document to file.

doc.SaveToFile("result.pdf");

Effective screenshot:

How to replace the existing image on the PDF file in C#

Full codes:

static void Main(string[] args)
 {
     PdfDocument doc = new PdfDocument();
     doc.LoadFromFile("Test.pdf");
     PdfPageBase page = doc.Pages[0];
     PdfImage image = PdfImage.FromFile("image.png");
     page.ReplaceImage(0, image);
     doc.SaveToFile("result.pdf");
 }