Created
March 3, 2024 10:35
C# Modify Word Paragraph Indent
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Prerequisite: Install <a href="https://www.nuget.org/packages/FileFormat.Words">FileFormat.Words</a>. | |
// Load the Word Document | |
var doc = new FileFormat.Words.Document($"filename.docx"); | |
// Initialize the body with the document | |
var body = new FileFormat.Words.Body(doc); | |
foreach (FileFormat.Words.IElements.Paragraph paragraph in body.Paragraphs) | |
{ | |
switch (paragraph.Indentation) | |
{ | |
case var indent when indent.Left > 0: | |
paragraph.AddRun(new FileFormat.Words.IElements.Run | |
{ Text = " (left indent set to 0)", Italic = true }); | |
paragraph.Indentation.Left = 0; | |
break; | |
case var indent when indent.Right > 0: | |
paragraph.AddRun(new FileFormat.Words.IElements.Run | |
{ Text = " (right indent set to 0)", Italic = true }); | |
paragraph.Indentation.Right = 0; | |
break; | |
case var indent when indent.FirstLine > 0: | |
paragraph.AddRun(new FileFormat.Words.IElements.Run | |
{ Text = " (FirstLine indent set to 0)", Italic = true }); | |
paragraph.Indentation.FirstLine = 0; | |
break; | |
case var indent when indent.Hanging > 0: | |
paragraph.AddRun(new FileFormat.Words.IElements.Run | |
{ Text = " (hanging indent set to 0)", Italic = true }); | |
paragraph.Indentation.Hanging = 0; | |
break; | |
default: | |
paragraph.AddRun(new FileFormat.Words.IElements.Run | |
{ Text = " (No indent and no change)", Italic = true }); | |
break; | |
} | |
doc.Update(paragraph); | |
} | |
// Save the modified Word Document | |
doc.Save($"IndentModified.docx"); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment