Text

Text (22)

With Spire.Doc for .NET, we can easily insert new text to word document at exact position, it also supports to insert new text after the certain text strings at many places. This article will show you how to insert new text strings after the searched text string in word document.

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

namespace Word
{
    class Program
    {
        static void Main(string[] args)
        {
            //load the sample document
            Document doc = new Document();
            doc.LoadFromFile("Sample.docx", FileFormat.Docx2010);

            //find all the text string “New Zealand” from the sample document
            TextSelection[] selections = doc.FindAllString("New Zealand", true, true);
            int index = 0;

            //defines text range
            TextRange range = new TextRange(doc);


            //insert new text string (NY) after the searched text string
            foreach (TextSelection selection in selections)
            {
                range = selection.GetAsOneRange();
                TextRange newrange = new TextRange(doc);
                newrange.Text = ("(NY)");
                index = range.OwnerParagraph.ChildObjects.IndexOf(range);
                range.OwnerParagraph.ChildObjects.Insert(index + 1, newrange);

            }

            //find and highlight the newly added text string NY
            TextSelection[] text2 = doc.FindAllString("NY", false, true);
            foreach (TextSelection seletion in text2)
            {
                seletion.GetAsOneRange().CharacterFormat.HighlightColor = Color.Yellow;
            }

            //save the document 
            doc.SaveToFile("Result.docx", FileFormat.Docx2010);
        }
    }
}

Effective screenshot after adding the text strings to the searched text:

C# add new text strings after the searched text string in word document

Tuesday, 24 July 2018 07:10

Replace Text with a Word document in C#

Written by support iceblue

Spire.Doc provides several overloaded Replace methods to replace text in different scenarios. This article is going to show you how to replace a specified text in a template document with another document using Spire.Doc.

The template document:

Replace Text with a Word document in C#

The document to replace text:

Replace Text with a Word document in C#

Detail steps:

Step 1: Load a template document.

Document document = new Document("Template.docx");

Step 2: Load another document to replace text.

IDocument replaceDocument = new Document("Document1.docx");

Step 3: Replace specified text with the other document.

document.Replace("Document 1", replaceDocument, false, true);  

Step 4: Save the file.

document.SaveToFile("Output.docx", FileFormat.Docx2013);

Output:

Replace Text with a Word document in C#

Full code:

using Spire.Doc;
using Spire.Doc.Interface;

namespace Replace_Text_With_Document
{
    class Program
    {
        static void Main(string[] args)
        {
            //Load a template document 
            Document document = new Document("Template.docx");

            //Load another document to replace text
            IDocument replaceDocument = new Document("Document1.docx");

            //Replace specified text with the other document
            document.Replace("Document 1", replaceDocument, false, true);

            //Save the file
            document.SaveToFile("Output.docx", FileFormat.Docx2013);
        }
    }
}

Programmers may need to determine the style name of a section of text, or find the text in a document that appear in a specified style name, such as “Heading 1”. This article will show you how to retrieve style names that are applied in a Word document by using Spire.Doc with C# and VB.NET.

Step 1: Create a Document instance.

Document doc = new Document();

Step 2: Load a sample Word file.

doc.LoadFromFile("Sample.docx");

Step 3: Traverse all TextRanges in the document and get their style names through StyleName property.

foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        foreach (DocumentObject docObject in paragraph.ChildObjects)
        {
            if (docObject.DocumentObjectType == DocumentObjectType.TextRange)
            {
                TextRange text = docObject as TextRange;
                Console.WriteLine(text.StyleName);
            }                   
        }
    }                
}

Result:

Retrieve Style Names of all TextRanges in a Word Document in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
doc.LoadFromFile("Sample.docx");

foreach (Section section in doc.Sections)
{
    foreach (Paragraph paragraph in section.Paragraphs)
    {
        foreach (DocumentObject docObject in paragraph.ChildObjects)
        {
            if (docObject.DocumentObjectType == DocumentObjectType.TextRange)
            {
                TextRange text = docObject as TextRange;
                Console.WriteLine(text.StyleName);
            }                   
        }
        Console.WriteLine();
    }                
}
[VB.NET]
Document doc = New Document()
doc.LoadFromFile("Sample.docx")
 
Dim section As Section
For Each section In doc.Sections
    Dim paragraph As Paragraph
    For Each paragraph In section.Paragraphs
        Dim docObject As DocumentObject
        For Each docObject In paragraph.ChildObjects
            If docObject.DocumentObjectType = DocumentObjectType.TextRange Then
                Dim text As TextRange = docObject as TextRange
                Console.WriteLine(text.StyleName)
            End If
        Next
        Console.WriteLine()
    Next
Next

Spire.Doc provides the ability to find the words that match a specific regular expression in a Word document and replace the matched words with a new string. This following code snippets give an example.

Step 1: Create an object of Document and load a test document.

Document doc = new Document();
doc.LoadFromFile("example.docx");

Step 2: Define a regular expression for the words that start with #.

Regex regex = new Regex(@"\#\w+\b");

Step 3: Call Document.Repalce(Regex pattern, string replace) method to replace the matched text with a new string.

doc.Replace(regex, "Spire.Doc");

Step 4: Save the file.

doc.SaveToFile("output.docx", FileFormat.Docx2013);

Result:

How to Find and Replace Text by Regular Expressions in Word in C#, VB.NET

Full Code:

[C#]
Document doc = new Document();
doc.LoadFromFile("example.docx");
Regex regex = new Regex(@"\#\w+\b");
doc.Replace(regex, "Spire.Doc");
doc.SaveToFile("output.docx", FileFormat.Docx2013);
[VB.NET]
Dim doc As New Document()
doc.LoadFromFile("example.docx")
Dim regex As New Regex("\#\w+\b")
doc.Replace(regex, "Spire.Doc")
doc.SaveToFile("output.docx", FileFormat.Docx2013)
Tuesday, 08 November 2016 08:05

How to get text from word document in C#

Written by support iceblue

Sometimes we only need to get the text from the word document for other use when we deal with the word documents with large amount of information. With the help of Spire.Doc, we have already demonstrated how to extract the text from the word document by traverse every paragraph on the word document and then append the text accordingly. This article will show you how to use the method of doc.GetText() to extract the text directly from the word documents with texts, images and tables. It is more convenient for developers to extract the text from the word document from code.

Firstly, view the sample word document which will be extracted the text firstly:

How to get text from word document in C#

Step 1: Create a word instance and load the source word document from file.

Document doc = new Document();
doc.LoadFromFile("Sample.docx");

Step 2: Invoke the doc.GetText() method to get all the texts from the word document.

string s = doc.GetText();

Step 3: Create a New TEXT File to Save Extracted Text.

File.WriteAllText("Extract.txt", s.ToString());

Effective screenshot after get all the text from the word document:

How to get text from word document in C#

Full codes:

class WordText
 {
   public GetText()
   {
     Document doc = new Document();
     doc.LoadFromFile("Sample.docx");

     string s = doc.GetText();

     File.WriteAllText("Extract.txt", s.ToString());

    }
 }
Wednesday, 24 August 2016 08:23

How to set text direction in Word

Written by support iceblue

We can use the TextDirection enumeration in Spire.Doc.Documents namespace to set the direction of text in a word document. This enumeration contains six members: LeftToRight, TopToBottom, LeftToRightRotated, TopToBottomRotated, RightToLeft and RightToLeftRotated. The following example shows how to set text direction for all text and a part of text in a section.

Detail steps:

Step 1: Initialize a new instance of Document class and load the word document.

Document document = new Document();
document.LoadFromFile("Word.docx");

Step 2: Set text direction for all text in a section.

//Get the first section and set its text direction
Section section = document.Sections[0];
section.TextDirection = TextDirection.RightToLeftRotated;

To set text direction for a part of text, we can put the text in a table and then set text direction, as shown in the following step:

Step 3: Add a new section to the document and a table to the section, get the target table cell and set text direction for it, afterwards append text to the cell.

//Add a new section to the document
Section sec = document.AddSection();
//Add a table to the new section
Table table = sec.AddTable();
//Add one row and one column to the table
table.ResetCells(1, 1);
//Get the table cell
TableCell cell = table.Rows[0].Cells[0];
table.Rows[0].Height = 150;
table.Rows[0].Cells[0].Width = 10;
//Set text direction for the cell and append some text
cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
cell.AddParagraph().AppendText("Hello,world: vertical style");

Add a new paragraph to check if above settings will affect the text direction of other text in this section:

sec.AddParagraph().AppendText("New Paragraph");

Step 4: Save the document.

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

Result:

Set text direction for all text in a section:

How to set text direction in Word

Set text direction for a part of text:

How to set text direction in Word

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;

namespace Set_text_direction_in_Word
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("Word.docx");
            //Set text direction for all text in a section
            Section section = document.Sections[0];
            section.TextDirection = TextDirection.RightToLeftRotated;

            // Set text direction for a part of text
            Section sec = document.AddSection();
            Table table = sec.AddTable();
            table.ResetCells(1, 1);
            TableCell cell = table.Rows[0].Cells[0];
            table.Rows[0].Height = 150;
            table.Rows[0].Cells[0].Width = 10;
            cell.CellFormat.TextDirection = TextDirection.RightToLeftRotated;
            cell.AddParagraph().AppendText("Hello,world: vertical style");

            sec.AddParagraph().AppendText("New Paragraph");

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

We always need to set all the texts in capital letters when we operate the invoice, quotation and contract, etc. This article will demonstrates how to set all the text case in capital letters in C#. Spire.Doc offers a property of docObj.CharacterFormat to enable developers to set the text in AllCaps and IsSmallCaps.

Firstly, please view the original word document.

How to change text case to all Capital letters in C#

Here comes to the code snippet:

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

Document doc = new Document();
doc.LoadFromFile("sample.docx");

Step 2: Get the first paragraph and set its CharacterFormat to AllCaps.

Paragraph para1 = doc.Sections[0].Paragraphs[0];
ParagraphBase docObj = para1.ChildObjects[0] as ParagraphBase;
docObj.CharacterFormat.AllCaps = true;

Step 3: Get the third paragraph and set its CharacterFormat to IsSmallCaps.

Paragraph para2 = doc.Sections[0].Paragraphs[2];
ParagraphBase docObj2 = para2.ChildObjects[0] as ParagraphBase;
docObj2.CharacterFormat.IsSmallCaps= true;

Step 4: Save the document to file.

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

Effective screenshot:

How to change text case to all Capital letters in C#

Full codes:

static void Main(string[] args)
{
    Document doc = new Document();
    doc.LoadFromFile("sample.docx");

    Paragraph para1 = doc.Sections[0].Paragraphs[0];
    ParagraphBase docObj = para1.ChildObjects[0] as ParagraphBase;
    docObj.CharacterFormat.AllCaps = true;

    Paragraph para2 = doc.Sections[0].Paragraphs[2];
    ParagraphBase docObj2 = para2.ChildObjects[0] as ParagraphBase;
    docObj2.CharacterFormat.IsSmallCaps= true;

    doc.SaveToFile( "result.docx",FileFormat.Docx2013);     
}

A combo box is a commonly-used GUI widget. It is a combination of a drop-down list or list box and a single-line textbox, allowing the user either to type a value directly into the control or choose from the list of existing options. In this article, we'll introduce how to programmatically manage the item of combo box in Word file using Spire.Doc.

Here is a combo box in the sample Word document, which contains three items including A, B and C. In the following section, we'll add, select and remove an item in the combo box using code.

How to Add, Select and Remove an Item in Combo Box in C#, VB.NET

Code Snippet:

Step 1: Initialize a new instance of Document class and load the sample Word file.

Document document = new Document();
document.LoadFromFile( "test.docx");

Step 2: Get the combo box from the file.

foreach (Section section in document.Sections)
{
    foreach (Body body in section.ChildObjects)
    {
        foreach (DocumentObject bodyObj in body.ChildObjects)
        {
            if (bodyObj is StructureDocumentTag)
            { 
                if ((bodyObj as StructureDocumentTag).SDTProperties.SDTType == SdtType.ComboBox)
                {
                    SdtComboBox combo = (bodyObj as StructureDocumentTag).SDTProperties.ControlProperties as SdtComboBox;
                    
               }
            }
        }
    }

}

Step 3: Create a new item and set two parameters for it: display text and value. Call ListItems.Add() method to add the new item into combo box.

SdtListItem item = new SdtListItem("D","d");
combo.ListItems.Add(item);

Step 4: Call ListItems.RemoveAt() method to remove an item by its index.

combo.ListItems.RemoveAt(0);

Step 5: Call ListItems.SelectedValue() to choose an item from combo box.

combo.ListItems.SelectedValue = sdtItem;

Step 6: Save and launch the file.

document.SaveToFile("result.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("result.docx");

Output:

How to Add, Select and Remove an Item in Combo Box in C#, VB.NET

Entire Code:

[C#]
Document document = new Document();
document.LoadFromFile( "test.docx");
foreach (Section section in document.Sections)
{
    foreach (Body body in section.ChildObjects)
    {
        foreach (DocumentObject bodyObj in body.ChildObjects)
        {
            if (bodyObj is StructureDocumentTag)
            { 
                if ((bodyObj as StructureDocumentTag).SDTProperties.SDTType == SdtType.ComboBox)
                {
                    SdtComboBox combo = (bodyObj as StructureDocumentTag).SDTProperties.ControlProperties as SdtComboBox;
                    SdtListItem item = new SdtListItem("D","d");
                    combo.ListItems.Add(item);
                    foreach (SdtListItem sdtItem in combo.ListItems)
                    {
                        if (string.CompareOrdinal(sdtItem.Value, "d") == 0)
                        {
                            combo.ListItems.SelectedValue = sdtItem;
                        }
                    }
                    combo.ListItems.RemoveAt(1);                               
               }
            }
        }
    }

}
document.SaveToFile("result.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("result.docx");
[VB.NET]
Dim document As New Document()
document.LoadFromFile("test.docx")
For Each section As Section In document.Sections
	For Each body As Body In section.ChildObjects
		For Each bodyObj As DocumentObject In body.ChildObjects
			If TypeOf bodyObj Is StructureDocumentTag Then
				If TryCast(bodyObj, StructureDocumentTag).SDTProperties.SDTType = SdtType.ComboBox Then
					Dim combo As SdtComboBox = TryCast(TryCast(bodyObj, StructureDocumentTag).SDTProperties.ControlProperties, SdtComboBox)
					Dim item As New SdtListItem("D", "d")
					combo.ListItems.Add(item)
					For Each sdtItem As SdtListItem In combo.ListItems
						If String.CompareOrdinal(sdtItem.Value, "d") = 0 Then
							combo.ListItems.SelectedValue = sdtItem
						End If
					Next
					combo.ListItems.RemoveAt(1)
				End If
			End If
		Next

	Next
Next
document.SaveToFile("result.docx", FileFormat.Docx2013)
System.Diagnostics.Process.Start("result.docx")
Wednesday, 17 June 2015 08:15

How to replace text in Word with image

Written by support iceblue

In the tutorials part of Spire.Doc, we have introduced the simple and easy method to "Replace text in Word with Table in C#" and "Replace images in Word with Texts in C#". Sometimes, we need to replace text in Word with image. Spire.Doc also provides a quick and effective solution to achieve this function with a little bit different codes. This article is going to introduce the method to replace text in Word with image.

Note: Before start, please download the latest version of Spire.Doc and add Spire.Doc .dll in the bin folder as the reference of visual studio.

Sample document:

How to replace text in Word with image

Step 1: Load the sample Word document and the image used to replace the text.

Document document = new Document();
document.LoadFromFile("s.docx");
Image image = Image.FromFile("2.bmp");

Step 2: Find the string "E-iceblue" in the document.

TextSelection[] selections = document.FindAllString("E-iceblue", true, true);
int index = 0;
TextRange range = null;

Step 3: Remove the text and replace it with Image

foreach (TextSelection selection in selections)
            {
                DocPicture pic = new DocPicture(document);
                pic.LoadImage(image);

                range = selection.GetAsOneRange();
                index = range.OwnerParagraph.ChildObjects.IndexOf(range);
                range.OwnerParagraph.ChildObjects.Insert(index, pic);
                range.OwnerParagraph.ChildObjects.Remove(range);

            }

Step 4: Save and launch the document to see effects.

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

Effects:

How to replace text in Word with image

Full codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;

namespace Replace_Text_with_Image
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("s.docx");
            Image image = Image.FromFile("2.bmp");

            TextSelection[] selections = document.FindAllString("E-iceblue", true, true);
            int index = 0;
            TextRange range = null;

            foreach (TextSelection selection in selections)
            {
                DocPicture pic = new DocPicture(document);
                pic.LoadImage(image);

                range = selection.GetAsOneRange();
                index = range.OwnerParagraph.ChildObjects.IndexOf(range);
                range.OwnerParagraph.ChildObjects.Insert(index, pic);
                range.OwnerParagraph.ChildObjects.Remove(range);

            }
            
            document.SaveToFile("Sample.doc", FileFormat.Doc);
            System.Diagnostics.Process.Start("Sample.doc");

        }
    }
}

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, and can 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.

This article illustrates how to get all controls and their properties including alias, id and tag via Spire.Doc with new method and replace the Barcode with another image.

Refer this article to check old method: Get alias, tag and id of content controls in a Word document in C#

The following is test file new.docx.

New method get alias, tag and id of content controls in a Word document in C#

Here are the steps:

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

Document doc = new Document(@"new.docx");

Step 2: Create a list StructureDocument to store tags. Here, each content control will be identified by tag.

public class StructureTags
        {
            List m_structureDocumnt;
            public List StructureDocument
            {
                get
                {
                    if (m_structureDocumnt == null)
                        m_structureDocumnt = new List();

                    return m_structureDocumnt;
                }
            }

        }

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

foreach (Section section in doc.Sections)
            {
                foreach (Body body in section.ChildObjects)
                {
                    ModifyBody(body);
                }
            }

Step 4: Show the properties of all controls.

List tagInlines = structureTags.StructureDocument;
            Console.WriteLine("Part1");
            for (int i = 0; i < tagInlines.Count; i++)
            {
                string alias = tagInlines[i].SDTProperties.Alias;   // Can be null or empty
                decimal id = tagInlines[i].SDTProperties.Id;
                string tag = tagInlines[i].SDTProperties.Tag;
                string STDType = tagInlines[i].SDTProperties.SDTType.ToString();

                Console.WriteLine("{0,20},{1,15},{2, 10} - {3}", alias, id, STDType, tag);
                Console.ReadKey();
             }

Step 5: Replace image inside of Picture Content Control.

doc.SaveToFile("replace1.docx", FileFormat.Docx2013);
System.Diagnostics.Process.Start("replace1.docx");

Result Screenshot:

New method get alias, tag and id of content controls in a Word document in C#

New method get alias, tag and id of content controls in a Word document in C#

Full code:

static StructureTags structureTags = new StructureTags();
        static void Main(string[] args)
        {
            Document doc = new Document(@"new.docx");

            foreach (Section section in doc.Sections)
            {
                foreach (Body body in section.ChildObjects)
                {
                    ModifyBody(body);
                }
            }

            List tagInlines = structureTags.StructureDocument;
            Console.WriteLine("Part1");
            for (int i = 0; i < tagInlines.Count; i++)
            {
                string alias = tagInlines[i].SDTProperties.Alias;
                decimal id = tagInlines[i].SDTProperties.Id;
                string tag = tagInlines[i].SDTProperties.Tag;
                string STDType = tagInlines[i].SDTProperties.SDTType.ToString();

                Console.WriteLine("{0,20},{1,15},{2, 10} - {3}", alias, id, STDType, tag);
                Console.ReadKey();

                if (tagInlines[i].SDTProperties.SDTType == SdtType.Picture)
                {
                    DocPicture picture = tagInlines[i].ChildObjects.FirstItem as DocPicture;
                    if (picture == null)
                    {
                        picture = new DocPicture(doc);
                        picture.LoadImage(Image.FromFile(@"cat.jpg"));
                        tagInlines[i].ChildObjects.Add(picture);
                    }
                    else
                    {
                        picture.LoadImage(Image.FromFile(@"cat.jpg"));
                    }
                }
            }

            doc.SaveToFile("replace1.docx", FileFormat.Docx2013);
            System.Diagnostics.Process.Start("replace1.docx");
        }

        static void ModifyBody(Body body)
        {
            if (body == null)
                return;

            foreach (DocumentObject docObj in body.ChildObjects)
            {
                if (docObj is StructureDocumentTag)
                {
                    structureTags.StructureDocument.Add(docObj as StructureDocumentTag);

                }
                else if (docObj is Table)
                {
                    ModifyTable(docObj as Table);
                }
                else if (docObj is Paragraph)
                {
                    ModifyParagraph(docObj as Paragraph);
                }
            }
        }

        static void ModifyTable(Table table)
        {
            if (table == null)
                return;

            foreach (TableRow row in table.Rows)
            {
                foreach (TableCell cell in row.Cells)
                {
                    if (cell is StructureDocumentTagCell)
                    {
                        structureTags.StructureDocument.Add(cell as StructureDocumentTagCell);
                    }
                    else
                    {
                        ModifyBody(cell);
                    }
                }
            }
        }

        static void ModifyParagraph(Paragraph para)
        {
            if (para == null)
                return;

            foreach (DocumentObject docObj in para.ChildObjects)
            {
                if (docObj is StructureDocumentTagInline)
                {

                    structureTags.StructureDocument.Add(docObj as StructureDocumentTagInline);
                }
            }
        }

        public class StructureTags
        {
            List m_structureDocumnt;
            public List StructureDocument
            {
                get
                {
                    if (m_structureDocumnt == null)
                        m_structureDocumnt = new List();

                    return m_structureDocumnt;
                }
            }
        }
Page 1 of 2