// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Linq; using System.Xml; using System.Xml.Linq; using DocumentFormat.OpenXml.Packaging; using DocumentFormat.OpenXml.Wordprocessing; using DocumentFormat.OpenXml.Validation; using OpenXmlPowerTools; using System.Text; using DocumentFormat.OpenXml; using System.Drawing.Imaging; namespace OpenXmlPowerTools { public static class AddDocxTextHelper { public static WmlDocument AppendParagraphToDocument( WmlDocument wmlDoc, string strParagraph, bool isBold, bool isItalic, bool isUnderline, string foreColor, string backColor, string styleName) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wmlDoc)) { using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument()) { StyleDefinitionsPart part = wDoc.MainDocumentPart.StyleDefinitionsPart; Body body = wDoc.MainDocumentPart.Document.Body; SectionProperties sectionProperties = body.Elements().FirstOrDefault(); Paragraph paragraph = new Paragraph(); Run run = paragraph.AppendChild(new Run()); RunProperties runProperties = new RunProperties(); if (isBold) runProperties.AppendChild(new Bold()); if (isItalic) runProperties.AppendChild(new Italic()); if (!string.IsNullOrEmpty(foreColor)) { int colorValue = ColorParser.FromName(foreColor).ToArgb(); if (colorValue == 0) throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified color {0} is unsupported, Please specify the valid color. Ex, Red, Green", foreColor)); string ColorHex = string.Format("{0:x6}", colorValue); runProperties.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Color() { Val = ColorHex.Substring(2) }); } if (isUnderline) runProperties.AppendChild(new Underline() { Val = UnderlineValues.Single }); if (!string.IsNullOrEmpty(backColor)) { int colorShade = ColorParser.FromName(backColor).ToArgb(); if (colorShade == 0) throw new OpenXmlPowerToolsException(String.Format("Add-DocxText: The specified color {0} is unsupported, Please specify the valid color. Ex, Red, Green", foreColor)); string ColorShadeHex = string.Format("{0:x6}", colorShade); runProperties.AppendChild(new Shading() { Fill = ColorShadeHex.Substring(2), Val = ShadingPatternValues.Clear }); } if (!string.IsNullOrEmpty(styleName)) { Style style = part.Styles.Elements