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


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

Наша задача - найти это слово - "signature " и измените его вместе с картинкой - "smile.png". Мы будем использовать обычные выражения (Regex).

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

  1. Обратите внимание, что Вы импортируете пространство имен SautinSoft.Document.
    с помощью SautinSoft.Document;
  2. Прежде всего, создайте DocumentCore объект с именем dc.
    
    DocumentCore dc = new DocumentCore();
    
    DocumentCore является корневым классом, он представляет сам документ.
  3. Используя регулярные выражения, мы найдем - "<signature>" (Signature,SIGNATURE, SiGnAtUrE, etc) и замените на Picture-.
    
                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);
                }
    
    
  4. Сохраните наш документ в формате PDF.
    
                // Save our document into PDF format.
                string savePath = @"..\..\Replaced_signature.pdf";
                dc.Save(savePath, new PdfSaveOptions());
    
    Загрузите полученный PDF-документ: Replaced_signature.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)
        {
            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-text-replace-image-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 });
        }
    }
}

Скачать

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

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

Скачать


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



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

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