News Category

Text

Text (24)

By using Spire.Doc, developers can find and highlight the text, extract the text in word document. This article will show you how to get the height and width of text in a word document in C# with the help of Spire.Doc.

Firstly, Download and install Spire.Doc for .NET and then add Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll". Here comes to the details of how to get the height and width of text in a word document in C#.

Check the original word document at first:

How to get the height and width of text in word document in C#

Step 1: Create a new document and load from file.

Document doc = new Document();
doc.LoadFromFile("Word.doc");

Step 2: Define the text string that we need to get the height and width.

string text = "Microsoft Word is a word processor designed by Microsoft.";

Step 3: Get the text string and measure the string.

//finds and returns the string with formatting
TextSelection selection = doc.FindString(text, true, true);
//get the font
Font font = selection.GetAsOneRange().CharacterFormat.Font;
//initialize graphics object
Image fakeImage = new Bitmap(1, 1);
Graphics graphics = Graphics.FromImage(fakeImage);
//measure string
SizeF size = graphics.MeasureString(text, font);

Step 4: Get the text height and width and read it.

Console.WriteLine("text height:{0}",size.Height);
Console.WriteLine("text width:{0}", size.Width);
Console.ReadLine();

Effective screenshot:

How to get the height and width of text in word document in C#

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using System;
using System.Drawing;
namespace GetHeightandWidth
{

    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile("Word.doc");
            string text = "Microsoft Word is a word processor designed by Microsoft.";

            TextSelection selection = doc.FindString(text, true, true);
            Font font = selection.GetAsOneRange().CharacterFormat.Font;
            Image fakeImage = new Bitmap(1, 1);
            Graphics graphics = Graphics.FromImage(fakeImage);
            SizeF size = graphics.MeasureString(text, font);

            Console.WriteLine("text height:{0}", size.Height);
            Console.WriteLine("text width:{0}", size.Width);
            Console.ReadLine();
        }
    }
}

One of our customers has a requirement to insert text to a Word document in an exact location (horizontal and vertical coordinates). Generally, people position text in a Word document by using other tools such as tables and text boxes, since the positioning of tables and text boxes is much easier to control. In this article, we'll introduce how to position text in Word through text box in C#, VB.NET.

Firstly download Spire.Doc for .NET and reference the dll file to your project. Before we start to code, we also need following namespaces to be extra added.

using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;

Code Snippet:

Step 1: Create a new Word document, add a section for it, and then add a paragraph on the section.

Document doc = new Document();
Section sec = doc.AddSection();
Paragraph par = sec.AddParagraph();

Step 2: Append a new text box to the paragraph. Here we logically set VerticalOrigin and HorizontalOrigin as Margin because horizontal and vertical coordinate is a relative value to his reference object. By giving the variable VerticalPosition and HorizontalPosition a certain value, the text box will be fixed at the position.

TextBox textBox = par.AppendTextBox(180, 30);
textBox.Format.VerticalOrigin = VerticalOrigin.Margin;
textBox.Format.VerticalPosition = 100;
textBox.Format.HorizontalOrigin = HorizontalOrigin.Margin;
textBox.Format.HorizontalPosition = 50;
textBox.Format.NoLine = true;

Step 3: Define a new format style.

CharacterFormat format = new CharacterFormat(doc);
format.FontName = "Calibri";
format.FontSize = 15;
format.Bold = true;

Step 4: Add text to text box, and apply the preset format to the text.

Paragraph par1 = textBox.Body.AddParagraph();
par1.AppendText("This is my new string").ApplyCharacterFormat(format);

Step 5: Save the file.

doc.SaveToFile("result.docx", FileFormat.Docx);

Result:

The border line of text box has been set as invisible, therefore we only see the text being added at the specified horizontal and vertical coordinates.

How to Insert Text to Word at Exact Position in C#, VB.NET

Full Code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using Spire.Doc.Formatting;
using System.Collections.Generic;
namespace InsertText
{

    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            Section sec = doc.AddSection();
            Paragraph par = sec.AddParagraph();

            TextBox textBox = par.AppendTextBox(180, 30);
            textBox.Format.VerticalOrigin = VerticalOrigin.Margin;
            textBox.Format.VerticalPosition = 100;
            textBox.Format.HorizontalOrigin = HorizontalOrigin.Margin;
            textBox.Format.HorizontalPosition = 50;
            textBox.Format.NoLine = true;

            CharacterFormat format = new CharacterFormat(doc);
            format.FontName = "Calibri";
            format.FontSize = 15;
            format.Bold = true;

            Paragraph par1 = textBox.Body.AddParagraph();
            par1.AppendText("This is my new string").ApplyCharacterFormat(format);
            doc.SaveToFile("result.docx", FileFormat.Docx);
        }
    }
}
[VB.NET]
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields
Imports Spire.Doc.Formatting
Imports System.Collections.Generic
Namespace InsertText

	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New Document()
			Dim sec As Section = doc.AddSection()
			Dim par As Paragraph = sec.AddParagraph()

			Dim textBox As TextBox = par.AppendTextBox(180, 30)
			textBox.Format.VerticalOrigin = VerticalOrigin.Margin
			textBox.Format.VerticalPosition = 100
			textBox.Format.HorizontalOrigin = HorizontalOrigin.Margin
			textBox.Format.HorizontalPosition = 50
			textBox.Format.NoLine = True

			Dim format As New CharacterFormat(doc)
			format.FontName = "Calibri"
			format.FontSize = 15
			format.Bold = True

			Dim par1 As Paragraph = textBox.Body.AddParagraph()
			par1.AppendText("This is my new string").ApplyCharacterFormat(format)
			doc.SaveToFile("result.docx", FileFormat.Docx)
		End Sub
	End Class
End Namespace

Content controls provide a way for you to design documents. When you add a content control to a document, the control is identified by a border, a title, and temporary text that can provide instructions to the user. According to Microsoft, content controls mainly benefit from two features:

  • Prevent users from editing or deleting protected sections of a document.
  • Bind parts of a document or template to data. You can bind content controls to database fields, managed objects in the .NET Framework, XML elements that are stored in the document, and other data sources.

Therefore, it is necessary for developers to get the properties of content controls when dealing content controls at run time. This article illustrates how to get all controls and their properties including alias, id and tag via Spire.Doc.

Firstly, check the test file that contains six content controls distributed in lines and a table. By default, the border and the title of the control do not appear if we don't click the protected section.

Test File:

Get alias, tag and id of content controls in a Word document in C#

Main Steps:

Step 1: Create a new Word document and load the test file.

Step 2: Create two lists to store tags which are distributed in lines and a table separately. Here, each content control will be identified by tag.

Step 3: Use foreach sentence to get all tags in the Word document.

Full Code:

       static void Main(string[] args)
        {
            using (Document document = new Document(@"..\..\TestData\test.docx"))
            {
                StructureTags structureTags = GetAllTags(document);
                List<StructureDocumentTagInline> tagInlines = structureTags.tagInlines;

                string alias = tagInlines[0].SDTProperties.Alias;
                decimal id = tagInlines[0].SDTProperties.Id;
                string tag = tagInlines[0].SDTProperties.Tag;

                List<StructureDocumentTag> tags = structureTags.tags;
                alias = tags[0].SDTProperties.Alias;
                id = tags[0].SDTProperties.Id;
                tag = tags[0].SDTProperties.Tag;

            }
        }
       static StructureTags GetAllTags(Document document)
        {
            StructureTags structureTags = new StructureTags();
            foreach (Section section in document.Sections)
            {
                foreach (DocumentObject obj in section.Body.ChildObjects)
                {
                    if (obj.DocumentObjectType == DocumentObjectType.Paragraph)
                    {
                        foreach (DocumentObject pobj in (obj as Paragraph).ChildObjects)
                        {
                            if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                            {
                                structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
                            }
                        }
                    }
                    else if (obj.DocumentObjectType == DocumentObjectType.Table)
                    {
                        foreach (TableRow row in (obj as Table).Rows)
                        {
                            foreach (TableCell cell in row.Cells)
                            {
                                foreach (DocumentObject cellChild in cell.ChildObjects)
                                {
                                    if (cellChild.DocumentObjectType == DocumentObjectType.StructureDocumentTag)
                                    {
                                        structureTags.tags.Add(cellChild as StructureDocumentTag);
                                    }
                                    else if (cellChild.DocumentObjectType == DocumentObjectType.Paragraph)
                                    {
                                        foreach (DocumentObject pobj in (cellChild as Paragraph).ChildObjects)
                                        {
                                            if (pobj.DocumentObjectType == DocumentObjectType.StructureDocumentTagInline)
                                            {
                                                structureTags.tagInlines.Add(pobj as StructureDocumentTagInline);
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            return structureTags;
        }
        public class StructureTags
        {
            List<StructureDocumentTagInline> m_tagInlines;
            public List tagInlines
            {
                get
                {
                    if (m_tagInlines == null)
                        m_tagInlines = new List();
                    return m_tagInlines;
                }
                set
                {
                    m_tagInlines = value;
                }
            }
            List<StructureDocumentTag> m_tags;
            public List tags
            {
                get
                {
                    if (m_tags == null)
                        m_tags = new List();
                    return m_tags;
                }
                set
                {
                    m_tags = value;
                }
            }
        }

Effect Screenshot:

Content controls in lines

Get alias, tag and id of content controls in a Word document in C#

Content controls in table

Get alias, tag and id of content controls in a Word document in C#

This topic is just another request from one of our users on Spire.Doc Forum. In order to let more people know about this function, we’re going to present the whole procedure through a sample demo in the article. Additionally, we would like to remind you that we offer free customized demo for both pay users and test users.

As a professional .NET Word component, Spire.Doc enables developers to replace specified paragraph with a newly created table or an existing table. In this example, the paragraph 3 in main body of the sample word file will be replaced by a newly-built table.

Test file:

Replace Text in Word with Table in C#

Code snippets for replacing text with table:

Step 1: Create a new word document and load the test file.

Document doc = new Document();
doc.LoadFromFile(@"..\..\test.docx");

Step 2: Return TextSection by finding the key text string "classical antiquity science".

Section section = doc.Sections[0];     
TextSelection selection = doc.FindString("classical antiquity science", true, true);

Step 3: Return TextRange from TextSection, then get OwnerParagraph through TextRange.

TextRange range = selection.GetAsOneRange();
Paragraph paragraph = range.OwnerParagraph;

Step 4: Return the zero-based index of the specified paragraph.

Body body = paragraph.OwnerTextBody;
int index = body.ChildObjects.IndexOf(paragraph);

Step 5: Create a new table.

Table table = section.AddTable(true);
table.ResetCells(3, 3);

Step 6: Remove the paragraph and insert table into the collection at the specified index.

body.ChildObjects.Remove(paragraph);
body.ChildObjects.Insert(index, table);

Step 7: Save and launch the file.

doc.SaveToFile("result.doc", FileFormat.Doc);
System.Diagnostics.Process.Start("result.doc");

Result:

Replace Text in Word with Table in C#

Full C# code:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
namespace ReplaceText
{

    class Program
    {
        static void Main(string[] args)
        {
            Document doc = new Document();
            doc.LoadFromFile(@"..\..\test.docx");
            Section section = doc.Sections[0];
            TextSelection selection = doc.FindString("classical antiquity science", true, true);
            TextRange range = selection.GetAsOneRange();
            Paragraph paragraph = range.OwnerParagraph;
            Body body = paragraph.OwnerTextBody;
            int index = body.ChildObjects.IndexOf(paragraph);

            Table table = section.AddTable(true);
            table.ResetCells(3, 3);
            body.ChildObjects.Remove(paragraph);
            body.ChildObjects.Insert(index, table);

            doc.SaveToFile("result.doc", FileFormat.Doc);
            System.Diagnostics.Process.Start("result.doc");

        }
    }
}

A text box's purpose is to allow the user to input text information to be used by the program. Also the existing text information can be extracted from the text box. The following guide focuses on introducing how to extract text from text box in a Word document in C# via Spire.Doc for .NET.

Firstly, check out the text box information in the word document.

extract text from textbox

Secondly, download Spire.Doc and install on your system. The Spire.Doc installation is clean, professional and wrapped up in a MSI installer.

Then adds Spire.Doc.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Doc\Bin\NET4.0\ Spire.Doc.dll".

Now it comes to the steps of how to extract text from text boxes.

Step 1: Load a word document from the file.

[C#]
Document document = new Document();
document.LoadFromFile(@"..\..\Test.docx");

Step 2: Check whether text box exists in the documents.

[C#]
//Verify whether the document contains a textbox or not
if (document.TextBoxes.Count > 0)

Step 3: Initialize a StreamWriter class for saving text which will be extracted next

[C#]
using (StreamWriter sw = File.CreateText("result.txt"))

Step 4: Extracted the text from text boxes.

[C#]
//Traverse the document
foreach (Section section in document.Sections)
{
 foreach (Paragraph p in section.Paragraphs)
{
foreach (DocumentObject obj in p.ChildObjects)

//Extract text from paragraph in TextBox
if (objt.DocumentObjectType == DocumentObjectType.Paragraph)
{
  sw.Write((objt as Paragraph).Text)
 }
//Extract text from Table in TextBox
if (objt.DocumentObjectType == DocumentObjectType.Table)
 {
  Table table = objt as Table;
  ExtractTextFromTables(table, sw);
}
//Extract text from Table 
static void ExtractTextFromTables(Table table, StreamWriter sw)
{
for (int i = 0; i < table.Rows.Count; i++)
            {
                TableRow row = table.Rows[i];
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        sw.Write(paragraph.Text);
                    }
                }
            }
}

After debugging, the following result will be presented:

extract text from textbox

The full code:

[C#]
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Fields;
using System.IO;
using Spire.Doc.Documents;
namespace ExtractTextFromTextBoxes
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile(@"..\..\Test.docx");

            //Verify whether the document contains a textbox or not
            if (document.TextBoxes.Count > 0)
            {
                using (StreamWriter sw = File.CreateText("result.txt"))
                {
                    foreach (Section section in document.Sections)
                    {
                        foreach (Paragraph p in section.Paragraphs)
                        {
                            foreach (DocumentObject obj in p.ChildObjects)
                            {
                                if (obj.DocumentObjectType == DocumentObjectType.TextBox)
                                {
                                    TextBox textbox = obj as TextBox;
                                    foreach (DocumentObject objt in textbox.ChildObjects)
                                    {
                                        if (objt.DocumentObjectType == DocumentObjectType.Paragraph)
                                        {
                                            sw.Write((objt as Paragraph).Text);
                                        }

                                        if (objt.DocumentObjectType == DocumentObjectType.Table)
                                        {
                                            Table table = objt as Table;
                                            ExtractTextFromTables(table, sw);
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
        }
        static void ExtractTextFromTables(Table table, StreamWriter sw)
        {
            for (int i = 0; i < table.Rows.Count; i++)
            {
                TableRow row = table.Rows[i];
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    foreach (Paragraph paragraph in cell.Paragraphs)
                    {
                        sw.Write(paragraph.Text);
                    }
                }
            }
        }
    }
}

Sometimes we need to insert a symbol or special character in the paragraph. The article is introducing the solution to insert a symbol in Word with c# code. We will use Ä and Ë as the symbol examples to complete the process, with the help of a Word .NET API called Spire.Doc.

First we need to complete the preparatory work:

  • Download the latest Spire.Doc and install it on your machine.
  • Add the Spire.Doc.dll files as reference.
  • Open bin folder and select the three dll files under .NET 4.0.
  • Right click property and select properties in its menu.
  • Set the target framework as .NET 4.
  • Add Spire.Doc as namespace.

Here comes to the explanation of the code.

Step 1: Create an instance of Spire.Doc.Document.

[C#]
Document document = new Document();

Step 2: Add a section.

[C#]
Section section = document.AddSection();

Step 3: Add a paragraph.

[C#]
Paragraph paragraph = section.AddParagraph();

Step 4: Use unicode characters to create symbol Ä.

[C#]
TextRange tr = paragraph.AppendText('\u00c4'.ToString());

In fact, the following step5 and step6 are just the option according to your requirement.

Step 5: Set the color of symbol Ä.

[C#]
tr.CharacterFormat.TextColor = Color.Red;

Step 6: Add symbol Ë.

[C#]
paragraph.AppendText('\u00cb'.ToString());

Step 7: Save to Word file.

[C#]
document.SaveToFile("sample.docx", FileFormat.Docx);

Here is the full code:

[C#]
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace InsertSymbol
{

    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();
            TextRange tr = paragraph.AppendText('\u00c4'.ToString());
            tr.CharacterFormat.TextColor = Color.Red;
            paragraph.AppendText('\u00cb'.ToString());
            document.SaveToFile("sample.docx", FileFormat.Docx);
        }

    }
}

Preview the effect screenshot:

insert symbol in word

Finding specific text or phrases in a long Word document can be a bit of a hassle. Fortunately, MS Word provides the "Find" function to locate specific content in a document quickly. You can also highlight the found content with a background color to ensure that they won't be overlooked by the readers. This article will demonstrate how to programmatically find and highlight text in a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Find and Highlight Text in a Word Document

The detailed steps are as follows.

  • Create a Document instance
  • Load a sample Word document using Document.LoadFromFile() method.
  • Find all matching text in the document using Document.FindAllString(string matchString, bool caseSensitive, bool wholeWord) method.
  • Loop through all matching text in the document.
  • Get the text range of a specific matching text using TextSelection.GetAsOneRange() method, and then set its highlight color using TextRange.CharacterFormat.HighlightColor property.
  • Save the result file using Document.SaveToFile() method.
  • C#
  • VB.NET
using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;

namespace FindHighlight
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

            //Load a sample Word document 
            document.LoadFromFile("input.docx");

            //Find all matching text in the document
            TextSelection[] text = document.FindAllString("transcendentalism", false, true);

            //Loop through all matching text and set highlight color for them
            foreach (TextSelection seletion in text)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            //Save the result file
            document.SaveToFile("FindHighlight.docx", FileFormat.Docx);
        }
    }
}

C#/VB.NET: Find and Highlight Text in Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

When receiving or downloading a Word document from the Internet, you may sometimes need to extract content from the document for other purposes. In this article, you will learn how to programmatically extract text and images from a Word document using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for.NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Extract Text from a Word Document

Below are detailed steps on how to extract text from a Word document and save in a TXT file.

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Create a StringBuilder instance.
  • Get each paragraph of each section in the document.
  • Get the text of a specified paragraph using Paragraph.Text property, and then append the extracted text to the StringBuilder instance using StringBuilder.AppendLine() method.
  • Create a new txt file and write the extracted text to the file using File.WriteAllText() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using System.Text;
using System.IO;

namespace ExtractTextfromWord
{
    class ExtractText
    {
        static void Main(string[] args)
        {
            //Create a Document instance
            Document document = new Document();

            //Load a sample Word document 
            document.LoadFromFile("input.docx");

            //Create a StringBuilder instance
            StringBuilder sb = new StringBuilder();

            //Extract text from Word and save to StringBuilder instance
            foreach (Section section in document.Sections)
            {
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    sb.AppendLine(paragraph.Text);
                }
            }

            //Create a new txt file to save the extracted text
            File.WriteAllText("Extract.txt", sb.ToString());
        }
    }
}

C#/VB.NET: Extract Text and Images from Word

Extract Images from a Word Document

Below are detailed steps on how to extract all images from a Word document.

  • Create a Document instance and load a sample Word document.
  • Get each paragraph of each section in the document.
  • Get each document object of a specific paragraph.
  • Determine whether the document object type is picture. If yes, save the image out of the document using DocPicture.Image.Save(String, ImageFormat) method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System;

namespace ExtractImage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a Word document
            Document document = new Document("input.docx");
            int index = 0;

            //Get each section of document
            foreach (Section section in document.Sections)
            {
                //Get each paragraph of section
                foreach (Paragraph paragraph in section.Paragraphs)
                {
                    //Get each document object of a specific paragraph
                    foreach (DocumentObject docObject in paragraph.ChildObjects)
                    {
                        //If the DocumentObjectType is picture, save it out of the document
                        if (docObject.DocumentObjectType == DocumentObjectType.Picture)
                        {
                            DocPicture picture = docObject as DocPicture;
                            picture.Image.Save(string.Format("image_{0}.png", index), System.Drawing.Imaging.ImageFormat.Png);
                            index++;
                        }
                    }
                }
            }
        }
    }
}

C#/VB.NET: Extract Text and Images from Word

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Question:

I want to replace text in a word template with HTML. I know how to append HTML to last paragraph but this paragraph is in the middle of word document.

Answer:

Below is a VB project demo about text replacing with multiple paragraphs and html, hope it will help you.

TextReplaceWithMultipleParagraph2.zip

If this doesn't answer your question, please do not hesitate to add your question in our forum. Our technical support will answer soon (we promise response within 1 business day)!

When it comes to editing documents, making changes to the text is a common task. Microsoft Word provides a robust feature called "Find and Replace" that streamlines the text editing process. With this feature, you can effortlessly locate specific words, phrases, or characters within your document and replace them in one simple action. This eliminates the need for repetitive manual searching and time-consuming edits, saving you valuable time and effort, especially when you need to make widespread changes in lengthy documents. In this article, we will explain how to find and replace text in Word documents in C# using Spire.Doc for .NET.

Install Spire.Doc for .NET

To begin with, you need to add the DLL files included in the Spire.Doc for .NET package as references in your .NET project. The DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Find Text and Replace All Its Instances with New Text

Spire.Doc for .NET provides the Document.Replace() method that enables you to find and replace specific text in a Word document. With this method, you can seamlessly replace all instances of the target text with new content. Additionally, you have the flexibility to specify whether the search should be case-sensitive and whether whole-word matching should be considered. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Replace all instances of specific text with new text using Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ReplaceAllText
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Replace all instances of specific text with new text
            document.Replace("Spire.Doc", "Eiceblue", false, true);

            //Save the result document
            document.SaveToFile("ReplaceAllText.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

C#: Find and Replace Text in Word Documents

Find Text and Replace Its First Instance with New Text

To replace the first instance of a specific text in a Word document using Spire.Doc for .NET, you can utilize the Document.ReplaceFirst property. By setting this property to true before calling the Document.Replace() method, you can change the text replacement mode to exclusively replace the first instance. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Change the text replacement mode to replace the first instance only by setting the Document.ReplaceFirst property to true.
  • Call the Document.Replace(string matchString, string newValue, bool caseSensitive, bool wholeWord) method to replace text.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;

namespace ReplaceFirstText
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Change the text replacement mode to replace the first instance only
            document.ReplaceFirst = true;

            //Replace the first instance of specific text with new text
            document.Replace("Spire.Doc", "Eiceblue", false, true);

            //Save the result document
            document.SaveToFile("ReplaceFirstText.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Find and Replace Text with Image

Sometimes, you may need to replace text with images for visual representation or design purposes. In Spire.Doc for .NET, replacing text with image can be achieved by inserting the image at the position of the target text and then removing the text from the document. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Find specific text in the document using Document.FindAllString() method.
  • Loop through the matched text.
  • For each matched text, get the paragraph where it is located and get the position of the text in the paragraph.
  • Instantiate an object of the DocPicture class, and then load an image using DocPicture.LoadImage() method.
  • Insert the image into the paragraph at the position of the text and then remove the text from the paragraph.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace ReplaceTextWithImage
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Find specific text in the document
            TextSelection[] selections = document.FindAllString("Spire.Doc", true, true);

            int index = 0;
            Paragraph ownerParagraph = null;

            //Loop through the matched text
            foreach (TextSelection selection in selections)
            {
                //Get the paragraph where the text is located
                ownerParagraph = selection.GetAsOneRange().OwnerParagraph;

                //Get the index position of the text in the paragraph
                index = ownerParagraph.ChildObjects.IndexOf(selection.GetAsOneRange());

                //Load an image
                DocPicture pic = new DocPicture(document);
                pic.LoadImage("img.png");

                //Insert the image into the paragraph at the index position of the text
                ownerParagraph.ChildObjects.Insert(index, pic);

                //Remove the text from the paragraph
                ownerParagraph.ChildObjects.Remove(selection.GetAsOneRange());
            }

            //Save the result document
            document.SaveToFile("ReplaceTextWithImage.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

C#: Find and Replace Text in Word Documents

Find and Replace Text using Regular Expression

Regular expressions offer a robust toolset for performing complex search and replace operations within documents. The Document.Replace() method can leverage regular expressions to search for specific text, allowing you to perform advanced search and replace operations based on specific criteria. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Instantiate an object of the Regex class to match text based on specific criteria.
  • Replace the matched text with new text using Document.Replace(Regex pattern, string replace) method.
  • Save the resulting document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using System.Text.RegularExpressions;

namespace ReplaceTextWithRegex
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Sample.docx");

            //Create a regex to match the text that starts with #
            Regex regex = new Regex(@"\#\w+\b");

            //Replace the matched text with new text
            document.Replace(regex, "Spire.Doc");

            //Save the result document
            document.SaveToFile("ReplaceTextWithRegex.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Find and Replace Text with Content from Another Word Document

In addition to replacing text with new text or image, Spire.Doc for .NET also enables you to replace text with content from another Word document. This can be beneficial when you are working on a predefined Word template and need to incorporate contents from other Word documents into it. The detailed steps are as follows.

  • Instantiate an object of the Document class.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Load another Word document into an IDocument object.
  • Replace specific text in the sample document with content from another document using Document.Replace(string matchString, IDocument matchDoc, bool caseSensitive, bool wholeWord) method.
  • Save the result document using Document.SaveToFile() method.
  • C#
using Spire.Doc;
using Spire.Doc.Interface;

namespace ReplaceTextWithDocument
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Instantiate an object of the Document class
            Document document = new Document();
            //Load a sample Word document
            document.LoadFromFile("Template.docx");

            //Load another Word document
            IDocument document1 = new Document("Report.docx");

            //Replace specific text in the sample document with content from another document
            document.Replace("Annual Sales", document1, false, true);

            //Save the result document
            document.SaveToFile("ReplaceTextWithDocument.docx", FileFormat.Docx2016);
            document.Close();
        }
    }
}

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Page 2 of 2