How to add line numbers in C#

Line numbers is used to display the number of lines counted automatically by Word next to each line of text. It's very useful when we need to refer to specific lines in a document such as contract or legal papers. Line numbers function in word allows us to set the start value, the number interval, the distance from text and the numbering mode of line numbers. Using Spire.Doc, we could achieve all of features mentioned above. This article is going to introduce how to add line numbers in C# using Spire.Doc.

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.

Step 1: Load the sample document which only has text.

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

Step 2: Set the start value of the line numbers.

document.Sections[0].PageSetup.LineNumberingStartValue = 1;

Step 3: Set the interval between displayed numbers.

document.Sections[0].PageSetup.LineNumberingStep = 6;

Step 4: Set the distance between line numbers and text.

document.Sections[0].PageSetup.LineNumberingDistanceFromText = 40f;

Step 5: Set the numbering mode of line numbers. Here we have four choices: None, Continuous, RestartPage and RestartSection.

document.Sections[0].PageSetup.LineNumberingRestartMode = LineNumberingRestartMode.Continuous;

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

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

Effects:

Single Page:

How to add line numbers in C#

Continuous Page:

How to add line numbers in C#

Full Codes:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Doc;

namespace How_to_add_line_numbering
{
    class Program
    {
        static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("T.docx");

            document.Sections[0].PageSetup.LineNumberingStartValue = 1;
            document.Sections[0].PageSetup.LineNumberingStep = 6;
            document.Sections[0].PageSetup.LineNumberingDistanceFromText = 40f;
            document.Sections[0].PageSetup.LineNumberingRestartMode = LineNumberingRestartMode.Continuous;

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