PDF format is widely adopted to automatically generate the documents such as invoices, reports, articles, etc. In certain cases, you have to replace the images in the PDF documents, such as to hide the confidential content. To accomplish that programmatically, this article covers how to replace images in PDF documents in C# .NET.
C# .NET API to Replace Images in PDF Files
To replace images in PDF files, we will use Aspose.PDF for .NET. The API is designed to perform PDF generation and manipulation from within the .NET applications. It allows you to create PDF documents of simple as well as complex layouts seamlessly. You can either download the API’s binaries or install it using NuGet.
PM> Install-Package Aspose.PDF
Replace Images in a PDF File in C#
In PDF documents, the images are kept in an image collection of each page. Thus, you can access any of the images from the collection using its index and manipulate it. The following are the steps to replace a particular image in a PDF in C#.
- Load the PDF file using Document class.
- Get reference of the desired page from the PDF using Document.Pages collection.
- Replace the image in the collection using Pages[index].Resources.Images.Replace(imageIndex, new FileStream(“lovely.jpg”, FileMode.Open)) method.
- Save the updated document using Document.Save(string) method.
The following code sample shows how to replace an image in a PDF using C# .NET.
Get a Free License
You can get a free temporary license in order to use Aspose.PDF for .NET without evaluation limitations.
Conclusion
In this article, you have learned how to replace images in PDF files using C#. You can simply integrate the provided code sample and replace PDF images from within your applications. Besides, you can explore more about the C# PDF API using the documentation. In case you would have any questions or queries, you can contact us via our forum.