Created
April 23, 2012 10:48
-
-
Save runegri/2470169 to your computer and use it in GitHub Desktop.
Part of a simple DSL for creating Word documents using the Open XML Sdk
This file contains hidden or 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
public static class OpenXmlExtensions | |
{ | |
public static Paragraph AppendTextParagraph(this OpenXmlCompositeElement element, string text) | |
{ | |
return AppendTextParagraph(element, text, false, kDefaultFontSize); | |
} | |
public static Paragraph AppendTextParagraph(this OpenXmlCompositeElement element, string text, bool bold) | |
{ | |
return AppendTextParagraph(element, text, bold, kDefaultFontSize); | |
} | |
public static Paragraph AppendTextParagraph(this OpenXmlCompositeElement element, string text, bool bold, int fontSize) | |
{ | |
var run = new Run(new Text(text)); | |
var runProperties = run.PrependChild(new RunProperties(new FontSize { Val = fontSize.ToString() })); | |
if (bold) | |
{ | |
runProperties.AppendChild(new Bold()); | |
} | |
var paragraph = new Paragraph(run); | |
return element.AppendChild(paragraph); | |
} | |
public static Paragraph Justify(this Paragraph paragraph, JustificationValues justificationValue) | |
{ | |
var properties = paragraph.GetOrAppend<ParagraphProperties>(); | |
properties.GetOrAppend<Justification>().Val = justificationValue; | |
return paragraph; | |
} | |
public static T GetOrAppend<T>(this OpenXmlCompositeElement element) where T : OpenXmlElement, new() | |
{ | |
var descendant = element.Descendants<T>().FirstOrDefault(); | |
if (descendant == null) | |
{ | |
descendant = element.AppendChild(new T()); | |
} | |
return descendant; | |
} | |
} | |
// Usage: | |
// First create a document | |
var dokument = WordprocessingDocument.Create(fileName, WordprocessingDocumentType.Document); | |
var mainPart = dokument.AddMainDocumentPart(); | |
var body = SetupStandardDocumentAndBody(mainPart); | |
// Then edit the body | |
body.AppentTextParagraph("Yay! I can edit a document").Justify(JustificationValues.Center); | |
body.AppendTextParagraph("I can even bold stuff", true); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment