Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save fileformat-words-gists/4cabcd2dd727ebb5dc1c27104b02b1bd to your computer and use it in GitHub Desktop.
Save fileformat-words-gists/4cabcd2dd727ebb5dc1c27104b02b1bd to your computer and use it in GitHub Desktop.
C# Create Word Paragraph Alignment
// Prerequisite: Install <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>.
// Initialize a new word document with the default template
var doc = new FileFormat.Words.Document();
System.Console.WriteLine("Word Document with default template initialized");
// Initialize the body with the new document
var body = new FileFormat.Words.Body(doc);
System.Console.WriteLine("Body of the Word Document initialized");
// Add paragraph with left alignment
FileFormat.Words.IElements.Paragraph para1 = new FileFormat.Words.IElements.Paragraph();
para1.AddRun(new FileFormat.Words.IElements.Run
{
Text = "First paragraph with left alignment"
});
// Setting the Paragraph Alignment to Center.
para1.Alignment = FileFormat.Words.IElements.ParagraphAlignment.Left; //"Left";
// Add paragraph with center alignment
FileFormat.Words.IElements.Paragraph para2 = new FileFormat.Words.IElements.Paragraph();
para2.AddRun(new FileFormat.Words.IElements.Run
{
Text = "Second paragraph with center alignment"
});
// Setting the Paragraph Alignment to Center.
para2.Alignment = FileFormat.Words.IElements.ParagraphAlignment.Center; //"Center";
// Add paragraph with right alignment
FileFormat.Words.IElements.Paragraph para3 = new FileFormat.Words.IElements.Paragraph();
para3.AddRun(new FileFormat.Words.IElements.Run
{
Text = "Third paragraph with right alignment"
});
// Setting the Paragraph Alignment to Center.
para3.Alignment = FileFormat.Words.IElements.ParagraphAlignment.Right; //"Right";
// Add paragraph with justify alignment
FileFormat.Words.IElements.Paragraph para4 = new FileFormat.Words.IElements.Paragraph();
para4.AddRun(new FileFormat.Words.IElements.Run
{
Text = "Fourth paragraph with justify alignment"
});
// Setting the Paragraph Alignment to Center.
para4.Alignment = FileFormat.Words.IElements.ParagraphAlignment.Justify; //"Justify";
// Append paragraphs to the document body
body.AppendChild(para1);
body.AppendChild(para2);
body.AppendChild(para3);
body.AppendChild(para4);
// Save the newly created Word Document.
doc.Save($"WordDocWithParaAligned.docx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment