How to insert a new paragraph to word document in C#

2015-08-05 08:01:24 Written by  support iceblue
Rate this item
(0 votes)

With the help of Spire.Doc, developers can easily merge multiple word documents into one word documents. After merged the documents, you may need to insert a note or new paragraph to add some description on it. This article explains and describes how to insert a new paragraph to the existing word document in C# by using Spire.Doc.

The following example shows how to insert a paragraph into the document.

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

Document document = new Document();
document.LoadFromFile("sample.docx", FileFormat.Docx);

Step 2: Append the text and set the formatting for the font.

Paragraph paraInserted = new Paragraph(document);
TextRange textRange1 = paraInserted.AppendText("This is a inserted paragraph, I want to insert this paragraph in the start of document.");
textRange1.CharacterFormat.TextColor = Color.Blue;
textRange1.CharacterFormat.FontSize = 15;
textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash;

Step 3: Insert the new paragraph.

document.Sections[0].Paragraphs.Insert(0, paraInserted);

Step 4: Save the document to file.

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

Effective screenshot:

How to insert a new paragraph to word document in C#

Full codes:

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
namespace InsertParagh
{
 class Program
    {
     
      static void Main(string[] args)
        {
            Document document = new Document();
            document.LoadFromFile("sample.docx", FileFormat.Docx);

            Paragraph paraInserted = document.Sections[0].AddParagraph();
            TextRange textRange1 = paraInserted.AppendText("This is a inserted paragraph, I want to insert this paragraph in the start of document.");
            textRange1.CharacterFormat.TextColor = Color.Blue;
            textRange1.CharacterFormat.FontSize = 15;
            textRange1.CharacterFormat.UnderlineStyle = UnderlineStyle.Dash;

            document.Sections[0].Paragraphs.Insert(0, document.Sections[0].Paragraphs[document.Sections[0].Paragraphs.Count - 1]);

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

Additional Info

  • tutorial_title: Insert a new paragraph to word document
Last modified on Friday, 03 September 2021 03:34