Skip to content

Instantly share code, notes, and snippets.

@openize-words-gists
Created May 22, 2024 12:35
Show Gist options
  • Save openize-words-gists/b768640e5de61db628150a8b5bf5e923 to your computer and use it in GitHub Desktop.
Save openize-words-gists/b768640e5de61db628150a8b5bf5e923 to your computer and use it in GitHub Desktop.
C# Create Word Document Paragraphs
//Prerequisite: Install <a href="https://www.nuget.org/packages/Openize.Words">Openize.Words</a>.
// Initialize a new word document with the default template
var doc = new Openize.Words.Document();
System.Console.WriteLine("Word Document with default template initialized");
// Initialize the body with the new document
var body = new Openize.Words.Body(doc);
System.Console.WriteLine("Body of the Word Document initialized");
// Get all paragraph styles
var paragraphStyles = doc.GetElementStyles().ParagraphStyles;
System.Console.WriteLine("Paragraph styles loaded");
// Get all fonts defined by FontTable and Theme
var fonts = doc.GetElementStyles().TableFonts;
var fontsTheme = doc.GetElementStyles().ThemeFonts;
System.Console.WriteLine("Fonts defined by FontsTable and Theme loaded");
// Merge all fonts
fonts.AddRange(fontsTheme);
System.Console.WriteLine("All Fonts merged");
// Create Headings Paragraph and append to the body.
foreach (var paragraphStyle in paragraphStyles.Where(style => !style.Contains("Normal")))
{
var paragraphWithStyle = new Openize.Words.IElements.Paragraph { Style = paragraphStyle };
paragraphWithStyle.AddRun(new Run {
Text = $"Paragraph with {paragraphStyle} Style"
});
System.Console.WriteLine($"Styled Paragraph with {paragraphStyle} Created");
body.AppendChild(paragraphWithStyle);
System.Console.WriteLine($"Styled Paragraph with {paragraphStyle} Appended to Word Document Body");
// Create Normal Paragraph and include text runs with various fonts as per the template.
var paragraphNormal = new Openize.Words.IElements.Paragraph();
System.Console.WriteLine("Normal Paragraph Created");
paragraphNormal.AddRun(new Openize.Words.IElements.Run
{
Text = $"Text in normal paragraph with default font and size but with bold " +
$"and underlined Gray Color ",
Color = Openize.Words.IElements.Colors.Gray,
Bold = true,
Underline = true
});
foreach (var font in fonts)
{
paragraphNormal.AddRun(new Run
{
Text = $"Text in normal paragraph with font {font} and size 10 but with default " +
$"color, bold, and underlines. ",
FontFamily = font,
FontSize = 10
});
}
System.Console.WriteLine("All Runs with all fonts Created for Normal Paragraph");
body.AppendChild(paragraphNormal);
System.Console.WriteLine($"Normal Paragraph Appended to Word Document Body");
}
// Save the newly created Word Document.
doc.Save($"WordPara.docx");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment