How to replace images in PDF document using C# and .NET


This code example shows how to find all the images in a pdf document and replace them with the required one.

Source pdf document containing images: example.pdf

Download the resulting file: replaced.pdf

Complete code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using SautinSoft.Document.Tables;
using System.IO;
namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            ReplaceImagesInPdf();
        }

        /// <summary>
        /// How to replace images in PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/from-customers-replace-images-in-pdf-in-csharp-vb-net.php
        /// </remarks>
        static void ReplaceImagesInPdf()
        {

            // Path to a loadable document.
            string loadPath = @"..\..\..\example.pdf";
            string pictPath = @"..\..\..\replaceNA.jpg";

            // Load a document intoDocumentCore.
            DocumentCore dc = DocumentCore.Load(loadPath);
            
            // Load the Picture from a file.
            Picture picture = new Picture(dc, InlineLayout.Inline(new Size()), pictPath);
            
            // Find all pictures in the document.
            foreach (Element el in dc.GetChildElements(true, ElementType.Picture).Reverse())
            {
                if (el is Picture)
                {
                    // Ñopy all properties of the found picture and assign these properties to the new picture.
                    // If you do not do this, the picture may be inserted into an arbitrary place in the document. 
                    if (((Picture)el).Layout is FloatingLayout)
                    {
                        FloatingLayout old = (FloatingLayout )((Picture)el).Layout;
                        picture.Layout = FloatingLayout.Floating(old.HorizontalPosition, old.VerticalPosition, old.Size);
                    }

                    // Replace picture.
                    el.Content.Replace(picture.Content);
                }
            }

            // Save our document into PDF format.
            string savePath = @"replaced.pdf";
            dc.Save(savePath);

            // Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(loadPath) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(savePath) { UseShellExecute = true });
        }
    }
}

Download

Imports System
Imports System.Collections.Generic
Imports System.Linq
Imports System.Text
Imports System.Threading.Tasks
Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing
Imports SautinSoft.Document.Tables
Imports System.IO
Namespace Example
	Friend Class Program
		Shared Sub Main(ByVal args() As String)
			ReplaceImagesInPdf()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/
		''' <summary>
		''' How to replace images in PDF document.
		''' </summary>
		''' <remarks>
		''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/from-customers-replace-images-in-pdf-in-csharp-vb-net.php
		''' </remarks>
		Private Shared Sub ReplaceImagesInPdf()

			' Path to a loadable document.
			Dim loadPath As String = "..\..\..\example.pdf"
			Dim pictPath As String = "..\..\..\replaceNA.jpg"

			' Load a document intoDocumentCore.
			Dim dc As DocumentCore = DocumentCore.Load(loadPath)

			' Load the Picture from a file.
			Dim picture As New Picture(dc, InlineLayout.Inline(New Size()), pictPath)

			' Find all pictures in the document.
			For Each el As Element In dc.GetChildElements(True, ElementType.Picture).Reverse()
				If TypeOf el Is Picture Then
					' Сopy all properties of the found picture and assign these properties to the new picture.
					' If you do not do this, the picture may be inserted into an arbitrary place in the document. 
					If TypeOf (CType(el, Picture)).Layout Is FloatingLayout Then
						Dim old As FloatingLayout = CType(CType(el, Picture).Layout, FloatingLayout)
						picture.Layout = FloatingLayout.Floating(old.HorizontalPosition, old.VerticalPosition, old.Size)
					End If

					' Replace picture.
					el.Content.Replace(picture.Content)
				End If
			Next el

			' Save our document into PDF format.
			Dim savePath As String = "replaced.pdf"
			dc.Save(savePath)

			' Open the result for demonstration purposes.
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(loadPath) With {.UseShellExecute = True})
			System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(savePath) With {.UseShellExecute = True})
		End Sub
	End Class
End Namespace

Download


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.