Insert Header in Word Document – C#/VB.NET

Word header, which is often inserted on the top of one page, can display additional information of one document.  Generally speaking, header can be date, time, page number or document title. If the document is company materials, header may be company name.

In this post, I want to introduce a method about how to insert header in Word with C# /VB.NET.

In my example, I prepare a document which doesn’t have a header. I will add document title as header and use a border to separate header and contents.

*The .NET Word component, Spire.Doc for.NET is used to realize this function, so I add its dll file as reference in project at the beginning.

Detailed Step Shown as Following:

  1. Load document which I want to insert header from computer add and a section in document.
  2. Insert header in document. Firstly, declare header and add a header paragraph. Secondly, append text for header. The text is document title. Thirdly, set header format, including font type, size, color and alignment. Finally, add border under header. Set border type and distance between border and header text.
  3. Save and launch file.

Main Coding:

C#

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

using Spire.Doc.Fields;
namespace InsertHeader
{
    class header
    {
        static void Main(string[] args)
        {
            //Load Document
            Document document = new Document();
            document.LoadFromFile(@”D:\work\My Documents\Little Prince.docx”);
            Section section = document.AddSection();

            //Insert Header
            HeaderFooter header = section.HeadersFooters.Header;
            Paragraph headerParagraph = header.AddParagraph();
            TextRange text = headerParagraph.AppendText(“Little Prince”);
            text.CharacterFormat.FontName = “Calibri”;
            text.CharacterFormat.FontSize = 14;
            text.CharacterFormat.TextColor = Color.DarkSlateGray;
            headerParagraph.Format.HorizontalAlignment
                = Spire.Doc.Documents.HorizontalAlignment.Right;
            headerParagraph.Format.Borders.Bottom.BorderType
                = Spire.Doc.Documents.BorderStyle.Single;
            headerParagraph.Format.Borders.Bottom.Space = 0.1F;

            //Save and Launch
            document.SaveToFile(“Header.docx”, FileFormat.Docx);
            System.Diagnostics.Process.Start(“Header.docx”);
        }
    }
}

VB.NET

Imports System
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace InsertHeader
    Friend Class header
        Shared Sub Main(ByVal args() As String)
            ‘Load Document
            Dim document As New Document()
            document.LoadFromFile(“D:\work\My Documents\Little Prince.docx”)
            Dim section As Section = document.AddSection()

            ‘Insert Header
            Dim header As HeaderFooter = section.HeadersFooters.Header
            Dim headerParagraph As Paragraph = header.AddParagraph()
            Dim text As TextRange = headerParagraph.AppendText(“Little Prince”)
            text.CharacterFormat.FontName = “Calibri”
            text.CharacterFormat.FontSize = 14
            text.CharacterFormat.TextColor = Color.DarkSlateGray
            headerParagraph.Format.HorizontalAlignment = Spire.Doc.Documents.HorizontalAlignment.Right
            headerParagraph.Format.Borders.Bottom.BorderType = Spire.Doc.Documents.BorderStyle.Single
            headerParagraph.Format.Borders.Bottom.Space = 0.1F

            ‘Save and Launch
            document.SaveToFile(“Header.docx”, FileFormat.Docx)
            System.Diagnostics.Process.Start(“Header.docx”)
        End Sub
    End Class
End Namespace

Result Shown as Following:

Download Spire.Doc for .NET Here

Set Paragrah Indentation in Word Document – C#/VB.NET

Word indentation is used to adjust distance between text and page margin. It includes four types, first line, hanging, left and right. First line indentation can indent first line of whole paragraph, while hanging indents whole paragraph except first line. Left and right indentations are used to indent whole paragraph toward right or left.

Sometimes, we may set indentation for special paragraphs. For example, the paragraph shows something which we need pay attention or reference contents from books or article websites. Because of indentation, the paragraph becomes easily noticed by readers. Also, when we want to print one document, indentation will be set.

In this post, I want to show how to set indentation in Word by using C#, including first line, left and right indentation.

Note: this method is based on Spire.Doc. If you want to use the following code, please add its dll file as reference.

Detailed Step Shown as Following:

  1. Create a Word document and add section.
  2. Set style for paragraph, including font type, size and color.
  3. Add a new paragraph and append text as title. Set built-in style Title for this paragraph.
  4. Set first line indentation. Add a new paragraph. Append text about indentation style. Then assign value for paragraph.Foramt.FirstLineIndent. Finally, apply style which has been set in step 2.
  5. Set Left indentation. Also, add paragraph and append cue words. Assign value for paragraph.Format.LeftIndent. Apply style again.
  6. Set right indentation. Add paragraph and append cue words. Set alignment as right and assign value for paragraph.Format.RightIndent. Apply style.
  7. Save and launch file.

Main Coding:

C#

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

namespace Indentation
{
    class indentation
    {
        static void Main(string[] args)
        {

            //Create Document
            Document document = new Document();

            //Add Section
            Section section = document.AddSection();

            //Style
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = “Style”;
            style.CharacterFormat.FontName = “Calibri”;
            style.CharacterFormat.FontSize = 14;
            style.CharacterFormat.TextColor = Color.DarkOrange;
            document.Styles.Add(style);

            //Add Paragraph and Append Text
            Paragraph paragraph = section.AddParagraph();
            paragraph.AppendText(“Indent List”);
            paragraph.ApplyStyle(BuiltinStyle.Title);

            //First Line Indent
            paragraph = section.AddParagraph();
            paragraph.AppendText(“First Line Indent”);
            paragraph.Format.FirstLineIndent = 40;
            paragraph.ApplyStyle(style.Name);

            //Left Indent
            paragraph = section.AddParagraph();
            paragraph.AppendText(“Left Indent”);
            paragraph.Format.LeftIndent = 30;
            paragraph.ApplyStyle(style.Name);

            //Right Indent
            paragraph = section.AddParagraph();
            paragraph.AppendText(“Right Indent”);
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right;
            paragraph.Format.RightIndent = 40;

            paragraph.ApplyStyle(style.Name);

            //Save and Launch
            document.SaveToFile(“Sample.doc”, FileFormat.Doc);
            System.Diagnostics.Process.Start(“Sample.doc”);
        }
    }
}

VB.NET

Imports System
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace Indentation
    Friend Class indentation
        Shared Sub Main(ByVal args() As String)

            ‘Create Document
            Dim document As New Document()

            ‘Add Section
            Dim section As Section = document.AddSection()

            ‘Style
            Dim style As New ParagraphStyle(document)
            style.Name = “Style”
            style.CharacterFormat.FontName = “Calibri”
            style.CharacterFormat.FontSize = 14
            style.CharacterFormat.TextColor = Color.DarkOrange
            document.Styles.Add(style)

            ‘Add Paragraph and Append Text
            Dim paragraph As Paragraph = section.AddParagraph()
            paragraph.AppendText(“Indent List”)
            paragraph.ApplyStyle(BuiltinStyle.Title)

            ‘First Line Indent
            paragraph = section.AddParagraph()
            paragraph.AppendText(“First Line Indent”)
            paragraph.Format.FirstLineIndent = 40
            paragraph.ApplyStyle(style.Name)

            ‘Left Indent
            paragraph = section.AddParagraph()
            paragraph.AppendText(“Left Indent”)
            paragraph.Format.LeftIndent = 30
            paragraph.ApplyStyle(style.Name)

            ‘Right Indent
            paragraph = section.AddParagraph()
            paragraph.AppendText(“Right Indent”)
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Right
            paragraph.Format.RightIndent = 40
            paragraph.ApplyStyle(style.Name)

            ‘Save and Launch
            document.SaveToFile(“Sample.doc”, FileFormat.Doc)
            System.Diagnostics.Process.Start(“Sample.doc”)
        End Sub
    End Class
End Namespace

Result Shown as Following:

_____________________________________________________________________________________________

Click Here to Learn more about Spire.Doc

Click Here to Download Spire.Doc

Replace Word Text with Another One with C#/VB.NET

Why do we want to find a specified word in a document? One reason is to confirm its location or highlight it to tell readers that it is important. The other reason is that to replace it with other word.

We will check our article or announcement several times after completing. Sometimes, we need to correct wrong spellings or use more appropriate words in one sentence. At that time, replace function can help us a lot to correct or replace words quickly.

In this post, I will introduce a method about how to replace words in MS Word with C#/VB.NET. And I use a .NET Word Component, Spire.Doc for .NET to help me realize this function more easily.

In my example, I will replace all the word “grown-ups” with “children” of this document.

Detailed Step Shown as Following:

  1. Load the document which I want to replace word from my computer.
  2. Replace word. document.Replace method is used. I pass four parameters to this method, word I want to replace, new word, bool value for case sensitive and bool value to confirm if replacement will be applied for whole word.
  3. Save and launch file.

Main Coding:

C#

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

namespace ReplaceWord
{
    class Replace
    {
        static void Main(string[] args)
        {
            //Load File
            Document document = new Document();
            document.LoadFromFile(@”D:\work\My Documents\Little Prince.docx”);

            //Replace
            document.Replace(“grown-ups”, “children”, true, true);

            //Save and Launch
            document.SaveToFile(“Replace.docx”, FileFormat.Docx);
            System.Diagnostics.Process.Start(“Replace.docx”);
        }
    }
}

VB.NET

Imports System
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace ReplaceWord
    Friend Class Replace
        Shared Sub Main(ByVal args() As String)
            ‘Load File
            Dim document As New Document()
            document.LoadFromFile(“D:\work\My Documents\Little Prince.docx”)

            ‘Replace
            document.Replace(“grown-ups”, “children”, True, True)

            ‘Save and Launch
            document.SaveToFile(“Replace.docx”, FileFormat.Docx)
            System.Diagnostics.Process.Start(“Replace.docx”)
        End Sub
    End Class
End Namespace

Result Shown as Following:

 

                            Original Document                                                                       Result Document

Download Spire.Doc for .NET Here

How to Find and Highlight Specified Text in Word with C#, VB.NET

In Word, find function is used to find a specified word or sentence from document with lots of contents quickly. In this post, I want to introduce a method about how to find text and highlight it with color by using C#/VB.NET.

Actually, find function is often used by us. We often find many labels at the end of the document to explain some words. If we want to know where the words are, we can use find function to get it. Also, we can use find function to get key words or notes and set colors or special effect to tell readers what they may need to pay attention.

In my example, I prepare a document and I will find word “Breathless” from it and add background color to highlight all “Breathless”.

*The .NET Word component, Spire.Doc is used for realizing this function.

Detailed Step Shown as Following:

  1. Load the document which I want to find specified word.
  2. Find word. Declare a TextSelection array which saves word I will find and assign value as document.FindAllString method. I need to send three parameters to this method, word I want to find, bool value for case sensitive, bool value for whole word applied.
  3. Highlight word. Because there are several same words in a document, I use foreach sentence to highlight all words with specified  color in TextSelection array.
  4. Save and launch file.

Main Coding:

C#

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

namespace FindWord
{
    class Find
    {
        static void Main(string[] args)
        {

            //Load Document
            Document document = new Document();
            document.LoadFromFile(@”D:\work\My Documents\Shayne Breathless.docx”, FileFormat.Docx);

            //Find Word
            TextSelection[] textSelections = document.FindAllString(“Breathless”, true, true);

            //Highlight Word
            foreach(TextSelection selection in textSelections)
            {
                selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Cyan;
            }

            //Save and Launch
            document.SaveToFile(“Find.docx”, FileFormat.Docx);
            System.Diagnostics.Process.Start(“Find.docx”);
        }
    }
}

VB.NET

Imports System
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace FindWord
    Friend Class Find
        Shared Sub Main(ByVal args() As String)

            ‘Load Document
            Dim document As New Document()
            document.LoadFromFile(“D:\work\My Documents\Shayne Breathless.docx”, FileFormat.Docx)

            ‘Find Word
            Dim textSelections() As TextSelection = document.FindAllString(“Breathless”, True, True)

            ‘Highlight Word
            For Each selection As TextSelection In textSelections
                selection.GetAsOneRange().CharacterFormat.HighlightColor = Color.Cyan
            Next selection

            ‘Save and Launch
            document.SaveToFile(“Find.docx”, FileFormat.Docx)
            System.Diagnostics.Process.Start(“Find.docx”)
        End Sub
    End Class
End Namespace

Result Shown as Following:

Download Spire.Doc for .NET Here

How to Set Word Built-in Style by Using C#/VB.NET

We often pay much attention on styles when writing papers in Word, such as title, heading, body settings and so on. Actually, Word provides users with various built-in styles. Users can use these styles directly or customize a new style according to their requirements. In this post, I will introduce a simple method to set Word style by using C#/VB.NET.

Style is used for paragraphs. Generally speaking, if one document has several parts, we may set a style for each part title, for example, heading 1 and set bodies as Normal style. Also, Word offers style for title and subtitle. In my example, I will show all the Word built-in Style in my document.

*The .NET Word Component, Spire.Doc for .NET is used in this method. If you want to use my code, please download it and add its dll file as reference in your project.

Detailed Step Shown as Following:

  1. Create a new Word document. Add section and add paragraph in this section.
  2. Add text in paragraph. The text is title to show what I will do next.
  3. Set font format for title, including font name, size, color and alignment.
  4. Set all the built-in styles. Because builtinStyle is enum type, so I use foreach sentence to show different styles in different paragraphs.
  5. Save and launch file.

Main Coding:

C#

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

namespace WordStyle
{
    class Style
    {
        static void Main(string[] args)
        {
            //Create Document
            Document document = new Document();

            //Add Section and Paragraph
            Section section = document.AddSection();
            Paragraph paragraph = section.AddParagraph();

            //Add Builtin Style
            paragraph.AppendText(“Built-In Style”);

            //Font Format
            ParagraphStyle style = new ParagraphStyle(document);
            style.Name = “Title”;
            style.CharacterFormat.FontName = “Calibri”;
            style.CharacterFormat.FontSize = 18;
            style.CharacterFormat.TextColor = Color.DarkOrange;
            document.Styles.Add(style);
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
            paragraph.ApplyStyle(style.Name);

            //Style
            foreach (BuiltinStyle builtinStyle in Enum.GetValues(typeof(BuiltinStyle)))
            {
                paragraph = section.AddParagraph();

                //Append Text
                paragraph.AppendText(builtinStyle.ToString());

                //Apply Style
                paragraph.ApplyStyle(builtinStyle);
            }

            //Save and Launch
            document.SaveToFile(“Style.docx”, FileFormat.Docx);
            System.Diagnostics.Process.Start(“Style.docx”);
        }
    }
}

VB.Net

Imports System
Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents

Namespace WordStyle
    Friend Class Style
        Shared Sub Main(ByVal args() As String)
            ‘Create Document
            Dim document As New Document()
            ‘Add Section and Paragraph
            Dim section As Section = document.AddSection()
            Dim paragraph As Paragraph = section.AddParagraph()

            ‘Add Builtin Style
            paragraph.AppendText(“Built-In Style”)

            ‘Font Format
            Dim style As New ParagraphStyle(document)
            style.Name = “Title”
            style.CharacterFormat.FontName = “Calibri”
            style.CharacterFormat.FontSize = 18
            style.CharacterFormat.TextColor = Color.DarkOrange
            document.Styles.Add(style)
            paragraph.Format.HorizontalAlignment = HorizontalAlignment.Center
            paragraph.ApplyStyle(style.Name)

            ‘Style
            For Each builtinStyle As BuiltinStyle In System.Enum.GetValues(GetType(BuiltinStyle))
                paragraph = section.AddParagraph()

                ‘Append Text
                paragraph.AppendText(builtinStyle.ToString())

                ‘Apply Style
                paragraph.ApplyStyle(builtinStyle)
            Next builtinStyle

            ‘Save and Launch
            document.SaveToFile(“Style.docx”, FileFormat.Docx)
            System.Diagnostics.Process.Start(“Style.docx”)
        End Sub
    End Class
End Namespace

Result Shown as Following:

 

Download Spire.Doc for .NET Here