Setting Word Paragraph Alignment Styles with C#
Paragraph alignment is a fundamental requirement for Word document formatting. Proper alignment styles enhance document readability and aesthetics. Free Spire.Doc for .NET is a free Word document processing component that enables convenient manipulation of Word documents via C# code in the .NET framework. This article will demonstrate how to set Word paragraph alignment styles using this component.
Installing Free Spire.Doc
Free Spire.Doc offers NuGet package installation, the most convenient integration method:
- Method 1: Search for "FreeSpire.Doc" in Visual Studio's "NuGet Package Manager" and install the appropriate version;
- Method 2: Execute the installation command in the Package Manager Console:
Install-Package FreeSpire.Doc
Core Knowledge: HorizontalAlignment Enumeration
Free Spire.Doc defines all Word paragraph alignment styles through the HorizontalAlignment enumeration. The core enumeration values and their corresponding meanings are as follows (fully consistent with native Word alignment styles):
| Enumeration Value | Alignment Style | Application Scenarios |
| Left | Left Alignment | Body text (default style) |
| Center | Center Alignment | Titles, subtitles, centered emphasis text |
| Right | Right Alignment | Page numbers, signatures, dates, etc. |
| Justify | Justified Alignment | Long body text (improves layout neatness) |
| Distribute | Distributed Alignment | Short text filling entire lines (Word support required) |
Setting Word Paragraph Alignment Styles: C# Code Examples
Example 1: Create a New Document and Set Different Paragraph Alignment Styles
This example demonstrates creating a blank Word document, adding multiple paragraphs, and setting different alignment styles for each:
using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
namespace SetWordParagraphAlignment
{
class Program
{
static void Main(string[] args)
{
// 1. Create a Document instance (represents the entire Word document)
Document doc = new Document();
// 2. Add a section (basic structural unit of a Word document; one document can contain multiple sections)
Section section = doc.AddSection();
// 3. Paragraph 1: Left alignment (default style; explicit setting for clarity)
Paragraph para1 = section.AddParagraph();
para1.AppendText("This is a left-aligned paragraph (default style). Left alignment is the most common alignment for document body text, conforming to most people's reading habits.");
para1.Format.HorizontalAlignment = HorizontalAlignment.Left; // Explicitly set left alignment
// 4. Paragraph 2: Center alignment
Paragraph para2 = section.AddParagraph();
para2.AppendText("This is a center-aligned paragraph");
para2.Format.HorizontalAlignment = HorizontalAlignment.Center; // Center alignment
// 5. Paragraph 3: Right alignment
Paragraph para3 = section.AddParagraph();
para3.AppendText("This is a right-aligned paragraph (suitable for page numbers, dates, etc.)");
para3.Format.HorizontalAlignment = HorizontalAlignment.Right; // Right alignment
// 6. Paragraph 4: Justified alignment
Paragraph para4 = section.AddParagraph();
para4.AppendText("This is a justified paragraph. Justified alignment aligns both left and right ends of the text to the page margins, eliminating irregular whitespace at the ends of text lines. It makes long text layouts neater and is a common style for formal document bodies.");
para4.Format.HorizontalAlignment = HorizontalAlignment.Justify; // Justified alignment
// 7. Save the document (supports Docx, Doc, PDF, etc.)
string outputPath = "NewDocument_ParagraphAlignment.docx";
doc.SaveToFile(outputPath, FileFormat.Docx2013);
// 8. Release resources (to avoid memory leaks)
doc.Dispose();
// Prompt for completion
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outputPath) { UseShellExecute = true });
}
}
}
Example 2: Modify Paragraph Alignment Styles in an Existing Word Document
This example demonstrates loading an existing Word document and modifying its paragraph alignment styles:
using Spire.Doc;
using Spire.Doc.Documents;
namespace ModifyExistingWordAlignment
{
class Program
{
static void Main(string[] args)
{
// 1. Load the existing Word document (replace with the actual file path)
string inputPath = "ExistingDocument.docx";
Document doc = new Document();
doc.LoadFromFile(inputPath);
// 2. Traverse all sections and paragraphs to modify alignment styles
foreach (Section section in doc.Sections)
{
foreach (Paragraph para in section.Paragraphs)
{
// 2.1 Batch modification: Set all paragraphs to justified alignment by default
para.Format.HorizontalAlignment = HorizontalAlignment.Justify;
// 2.2 Precise modification: Set paragraphs containing "Title" to center alignment
if (!string.IsNullOrEmpty(para.Text) && para.Text.Contains("Title"))
{
para.Format.HorizontalAlignment = HorizontalAlignment.Center;
}
// 2.3 Extension: Set paragraphs containing "Signature" to right alignment
if (!string.IsNullOrEmpty(para.Text) && para.Text.Contains("Signature"))
{
para.Format.HorizontalAlignment = HorizontalAlignment.Right;
}
}
}
// 3. Save the modified document (rename to avoid overwriting the original file)
string outputPath = "ModifiedDocument_ParagraphAlignment.docx";
doc.SaveToFile(outputPath, FileFormat.Docx2013);
// 4. Release resources
doc.Dispose();
// Open the modified document
System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outputPath) { UseShellExecute = true });
}
}
}
Notes
- Free Version Limitations: The free version of Free Spire.Doc has restrictions on document processing (maximum 500 paragraphs and 25 tables per document);
- Resource Release: Always call
doc.Dispose()to release theDocumentobject after operations to avoid memory leaks, especially when processing multiple documents in a loop; - Enumeration Compatibility:
Distribute(Distributed Alignment) is only supported in Word 2013 and above. Opening documents in older Word versions may cause display abnormalities; - Empty Paragraph Handling: When traversing paragraphs, it is recommended to check if
para.Textis empty to avoid invalid operations on empty paragraphs; - Format Overwriting: Modifying paragraph alignment styles will overwrite existing alignment settings. To retain some styles, add conditional judgments.
Summary
Free Spire.Doc for .NET provides a concise and intuitive API for setting Word paragraph alignment styles. Whether creating new documents or modifying existing ones, requirements can be fulfilled with minimal C# code. Its compatibility with multiple .NET framework versions allows it to adapt to different project environments.