How to find and replace any text content in the document using C# and .NET


Here we'll show you how to using the find and replace methods.

Our task is find the word - "Bean" and change it on - "Joker". We will use regular expressions (Regex).

A few steps:

  1. Notice you are importing the SautinSoft.Document namespace.
    using SautinSoft.Document;
  2. First of all, create a DocumentCore object with name dc.
    
    DocumentCore dc = new DocumentCore();
    
    DocumentCore is root class, it represents a document itself.
  3. Using regular expressions, we'll find - "Bean" (bean, BEAN, bEan, etc) and replace to - "Joker".
    
                Regex regex = new Regex(@"bean", RegexOptions.IgnoreCase);
    
                //Find "Bean" and Replace everywhere to "Joker"
                foreach (ContentRange item in dc.Content.Find(regex))
                {
                    item.Replace("Joker");
                }
    
    
  4. Save our document into PDF format.
    
                string savePath = Path.ChangeExtension(loadPath, ".replaced.pdf");
                dc.Save(savePath, new PdfSaveOptions());
                System.Diagnostics.Process.Start(savePath);
    
    Download the result PDF document: Replaced.pdf
 

Complete code

using System.IO;
using SautinSoft.Document;
using SautinSoft.Document.Drawing;
using System.Linq;
using System.Text.RegularExpressions;

namespace Sample
{
    class Sample
    {

        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            FindTextAndReplaceImage();
        }

        /// <summary>
        /// Find Text and replace it with a Picture using ContentRange.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/find-replace-content-net-csharp-vb.php
        /// </remarks>
        public static void FindTextAndReplaceImage()
        {
            // Path to a loadable document.
            string loadPath = @"..\..\..\Critique_signature.docx";
            string pictPath = @"..\..\..\Smile.png";

            // Load a document intoDocumentCore.
            DocumentCore dc = DocumentCore.Load(loadPath);

            //Find "<signature>" Text and Replace everywhere with the "Smile.png"
            // Please note, Reverse() makes sure that action replace not affects to Find().
            Regex regex = new Regex(@"<signature>", RegexOptions.IgnoreCase);
            Picture picture = new Picture(dc, InlineLayout.Inline(new Size(50, 50)), pictPath);
            foreach (ContentRange item in dc.Content.Find(regex).Reverse())
            {
                item.Replace(picture.Content);
            }

            // Save our document into PDF format.
            string savePath = @"..\..\Replaced_signature.pdf";
            dc.Save(savePath, new PdfSaveOptions());

            // 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.IO
Imports SautinSoft.Document
Imports SautinSoft.Document.Drawing
Imports System.Linq
Imports System.Text.RegularExpressions

Namespace Sample
	Friend Class Sample

		Shared Sub Main(ByVal args() As String)
			FindTextAndReplaceImage()
		End Sub
                ''' Get your free 30-day key here:   
                ''' https://sautinsoft.com/start-for-free/

        ''' <summary>
        ''' Find Text and replace it with a Picture using ContentRange.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/find-text-replace-image-content-net-csharp-vb.php
        ''' </remarks>
        Public Shared Sub FindTextAndReplaceImage()
			' Path to a loadable document.
			Dim loadPath As String = "..\..\..\Critique_signature.docx"
			Dim pictPath As String = "..\..\..\Smile.png"

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

			'Find "<signature>" Text and Replace everywhere with the "Smile.png"
			' Please note, Reverse() makes sure that action replace not affects to Find().
			Dim regex As New Regex("<signature>", RegexOptions.IgnoreCase)
			Dim picture As New Picture(dc, InlineLayout.Inline(New Size(50, 50)), pictPath)
			For Each item As ContentRange In dc.Content.Find(regex).Reverse()
				item.Replace(picture.Content)
			Next item

			' Save our document into PDF format.
			Dim savePath As String = "..\..\..\Replaced_signature.pdf"
			dc.Save(savePath, New PdfSaveOptions())

			' 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.