Как найти и заменить любое текстовое содержимое в документе с помощью C# и .NET


Здесь мы покажем Вам, как использовать методы поиска и замены.

Наша задача - найти слово - "Bean" и изменить на - "Joker". Мы будем использовать обычные выражения (Regex).

Несколько шагов:

  1. Обратите внимание, что Вы импортируете пространство имен SautinSoft.Document.
    с помощью SautinSoft.Document;
  2. Прежде всего, создайте DocumentCore объект с именем dc.
    
    DocumentCore dc = new DocumentCore();
    
    DocumentCore является корневым классом, он представляет сам документ.
  3. Используя регулярные выражения, мы найдем - "Bean" (bean, BEAN, bEan, etc) и заменить на- "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. Сохраните наш документ в формате PDF.
    
                string savePath = Path.ChangeExtension(loadPath, ".replaced.pdf");
                dc.Save(savePath, new PdfSaveOptions());
                System.Diagnostics.Process.Start(savePath);
    
    Загрузите полученный PDF-документ: Replaced.pdf

Полный код

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


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.