C#/VB.NET: Align Text in Word

2022-04-14 06:38:00 Written by  Administrator
Rate this item
(0 votes)

Text alignment is a paragraph formatting attribute that determines the appearance of the text in a whole paragraph. There are four types of text alignments available in Microsoft Word: left-aligned, center-aligned, right-aligned, and justified. In this article, you will learn how to programmatically set different text alignments for paragraphs 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.Doc

Align Text in Word

The detailed steps are as follows:

  • Create a Document instance.
  • Load a sample Word document using Document.LoadFromFile() method.
  • Get a specified section using Document.Sections[] property.
  • Get a specified paragraph using Section.Paragraphs[] property.
  • Get the paragraph format using Paragraph.Format property
  • Set text alignment for the specified paragraph using ParagraphFormat.HorizontalAlignment property.
  • Save the document to another file using Document.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Doc;
using Spire.Doc.Documents;

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

            //Load a sample Word document
            doc.LoadFromFile(@"D:\Files\sample.docx");

            //Get the first section
            Section section = doc.Sections[0];

            //Get the first paragraph and make it center-aligned
            Paragraph p = section.Paragraphs[0];
            p.Format.HorizontalAlignment = HorizontalAlignment.Center;

            //Get the second paragraph and make it left-aligned
            Paragraph p1 = section.Paragraphs[1];
            p1.Format.HorizontalAlignment = HorizontalAlignment.Left;

            //Get the third paragraph and make it right-aligned
            Paragraph p2 = section.Paragraphs[2];
            p2.Format.HorizontalAlignment = HorizontalAlignment.Right;

            //Get the fourth paragraph and make it justified
            Paragraph p3 = section.Paragraphs[3];
            p3.Format.HorizontalAlignment = HorizontalAlignment.Justify;

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

C#/VB.NET: Align 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.

Additional Info

  • tutorial_title:
Last modified on Wednesday, 31 May 2023 09:03