internal static void ApplyFontStyle(string style, OpenXmlElement styleElement) { if (string.Compare(italic, style, StringComparison.InvariantCultureIgnoreCase) == 0) { styleElement.Append(new Italic()); } }
private void SetMarginBottom(OpenXmlElement parent) { Paragraph para = parent.AppendChild(new Paragraph()); para.ParagraphProperties = new ParagraphProperties(); DocxMargin.SetBottomMargin(defaultDLMargin, para.ParagraphProperties); }
public override void AppendTo(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { _mainDocumentPart = mainDocumentPart; var imagePart = CreateImagePart(); openXmlNode.Append(CreateImageElement(mainDocumentPart.GetIdOfPart(imagePart), Path.GetFileName(_content))); }
/// <summary> /// Gets XmlPath information of the specified OpenXmlElement. /// </summary> /// <param name="element">The OpenXmlElement.</param> /// <returns>XmlPath to this element from root element.</returns> internal static XmlPath GetXPath(OpenXmlElement element) { if (element == null) { return null; // throw new ArgumentNullException("element"); } XmlPath xmlPath = new XmlPath(); xmlPath.PartUri = element.GetPartUri(); Dictionary<string, string> namespaces = new Dictionary<string, string>(); StringBuilder xpath = new StringBuilder(""); BuildXPath(element, xpath, namespaces); xmlPath.XPath = xpath.ToString(); StringBuilder nsString; foreach (var ns in namespaces) { nsString = new StringBuilder(""); nsString.Append("xmlns:"); nsString.Append(ns.Key); nsString.Append("=\""); nsString.Append(ns.Value); nsString.Append("\""); xmlPath.NamespacesDefinitions.Add(nsString.ToString()); } return xmlPath; }
public override void InsertAfter(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { _mainDocumentPart = mainDocumentPart; var imagePart = CreateImagePart(); openXmlNode.InsertAfterSelf(CreateImageElement(mainDocumentPart.GetIdOfPart(imagePart), Path.GetFileName(_content))); }
private Paragraph CreateParagraph(DocxNode node, OpenXmlElement parent) { Paragraph para = parent.AppendChild(new Paragraph()); OnParagraphCreated(node, para); OnOLParagraphCreated(this, new ParagraphEventArgs(para)); return para; }
public override void AppendTo(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { var paragraphs = ConvertContentToParagraphs(mainDocumentPart); foreach (var paragraph in paragraphs) { openXmlNode.Append(paragraph); } }
internal static void ApplyFontWeight(string style, OpenXmlElement styleElement) { if (string.Compare(bold, style, StringComparison.InvariantCultureIgnoreCase) == 0 || string.Compare(bolder, style, StringComparison.InvariantCultureIgnoreCase) == 0) { styleElement.Append(new Bold()); } }
public override void AppendTo(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { var text = _newParagraph ? (OpenXmlElement)new Paragraph(new Run(new Text(_content))) : (OpenXmlElement)new Run(new Text(_content)); openXmlNode.Append(text); }
internal static void ApplyTextAlign(string style, OpenXmlElement styleElement) { JustificationValues alignment; if (GetJustificationValue(style, out alignment)) { styleElement.Append(new Justification() { Val = alignment }); } }
public override void InsertAfter(OpenXmlElement openXmlNode, MainDocumentPart mainDocumentPart) { var paragraphs = ConvertContentToParagraphs(mainDocumentPart); var insertPoint = openXmlNode; foreach (var paragraph in paragraphs) { insertPoint.InsertAfterSelf(paragraph); insertPoint = paragraph; } }
/// <summary> /// Initializes a new instance of the OpenXmlDomReader class using the supplied OpenXmlElement and Boolean values. /// </summary> /// <param name="openXmlElement">The OpenXmlElement to read.</param> /// <param name="readMiscNodes">Specify false to indicate to the reader to skip all miscellaneous nodes. The default value is false.</param> public OpenXmlDomReader(OpenXmlElement openXmlElement, bool readMiscNodes) : this(readMiscNodes) { if (openXmlElement == null) { throw new ArgumentNullException("openXmlElement"); } this.Init(openXmlElement); }
/// <summary> /// Initializes a new instance of the OpenXmlDomReader class. /// </summary> /// <param name="openXmlElement">The OpenXmlElement to read.</param> public OpenXmlDomReader(OpenXmlElement openXmlElement) : this() { if (openXmlElement == null) { throw new ArgumentNullException("openXmlElement"); } this.Init(openXmlElement); }
internal static void ApplyTextDecoration(string style, OpenXmlElement styleElement) { if (string.Compare(style, underLine, StringComparison.InvariantCultureIgnoreCase) == 0) { styleElement.Append(new Underline() { Val = UnderlineValues.Single }); } else if (string.Compare(style, lineThrough, StringComparison.InvariantCultureIgnoreCase) == 0) { styleElement.Append(new Strike()); } }
public static IEnumerable<MergeField> GetMergeRuns(OpenXmlElement element) { // Gets each element under the element with text representing a merge field. foreach (var run in element.Descendants<Run>()) { if (run.InnerText.StartsWith(MergeField.StartMergeField.ToString()) && run.InnerText.EndsWith(MergeField.EndMergeField.ToString())) { yield return ConvertRunToMergeField(run); } } }
private List<OpenXmlElement> InitializeRoot(OpenXmlElement root, bool removeOldOnes = true) { var initialElements = root.ChildElements; if (removeOldOnes) { if (initialElements == null || initialElements.Count <= 0) return new List<OpenXmlElement>(); List<OpenXmlElement> elements = initialElements.Select(initialElement => (OpenXmlElement) initialElement.Clone()).ToList(); root.RemoveAllChildren(); return elements; } return initialElements.ToList(); }
public void AddCallBackMethod(OpenXmlElement element, CallBackMethod method) { if (!_callBackMethods.Keys.Contains(element.ElementTypeId)) { _callBackMethods.Add(element.ElementTypeId, new List<CallBackMethod>()); } // _callBackMethods[element.ElementTypeId] is a List. Let's check if the method obj is already added to the list. if (!_callBackMethods[element.ElementTypeId].Contains(method)) { _callBackMethods[element.ElementTypeId].Add(method); } }
public ValidationInfo(OpenXmlPowerToolsDocument doc, ValidationErrorInfo err) { Document = doc; FileName = doc.FileName; Description = err.Description; ErrorType = err.ErrorType; Id = err.Id; Node = err.Node; Part = err.Part; XPath = err.Path.XPath; RelatedNode = err.RelatedNode; RelatedPart = err.RelatedPart; }
public static XQueryNodeIterator QueryNodes(this OpenXmlPart part, OpenXmlElement contextNode, string xquery, XmlNamespaceManager nsmgr) { NameTable nameTable = new NameTable(); OpenXmlDocument doc = new OpenXmlDocument(part, nameTable); OpenXmlNavigator node = new OpenXmlNavigator(new ElementAdapter(contextNode, new RootAdapter(doc.Part.RootElement, doc))); OpenXmlQueryCommand command = new OpenXmlQueryCommand(nameTable); if (nsmgr != null) command.Context.CopyNamespaces(nsmgr); command.ContextItem = node; command.CommandText = xquery; return command.Execute().Preload(); // Load all nodes for preventing to close container before finish query }
internal override void Process(DocxNode node, ref Paragraph paragraph) { body = context.Document.AppendChild(new Body()); //If the node is body tag, find the first children to process if (CanConvert(node)) { if (!node.HasChildren) { //Nothing to process. Just return from here. return; } node = node.Children.ElementAt(0); } ProcessBody(node, ref paragraph); }
/// <summary> /// Validate the DOM tree under the specified OpenXmlElement. /// </summary> /// <param name="schemaValidator">The schemaValidator.</param> /// <param name="openxmlElement">The root of the sub tree.</param> /// <returns>Returns the validation result in ValidationResult.</returns> /// <remarks> /// Only schema validating. /// </remarks> internal static ValidationResult Validate(this SchemaValidator schemaValidator, OpenXmlElement openxmlElement) { Debug.Assert(openxmlElement != null); var validationResult = new ValidationResult(); Debug.Assert(!(openxmlElement is OpenXmlUnknownElement || openxmlElement is OpenXmlMiscNode)); // Can not just validate AlternateContent / Choice / Fallback // Debug.Assert(!(openxmlElement is AlternateContent)) Debug.Assert(!(openxmlElement is AlternateContentChoice || openxmlElement is AlternateContentFallback)); var validationContext = new ValidationContext(); validationContext.ValidationErrorEventHandler += validationResult.OnValidationError; validationContext.Element = openxmlElement; schemaValidator.Validate(validationContext); return validationResult; }
private string GetPlainText(OpenXmlElement element) { StringBuilder PlainTextInWord = new StringBuilder(); foreach (OpenXmlElement section in element.Elements()) { switch (section.LocalName) { // Text case "t": PlainTextInWord.Append(section.InnerText); break; case "cr": // Carriage return case "br": // Page break PlainTextInWord.Append(Environment.NewLine); break; // Tab case "tab": PlainTextInWord.Append("\t"); break; // Paragraph case "p": PlainTextInWord.Append(GetPlainText(section)); PlainTextInWord.AppendLine(Environment.NewLine); break; default: PlainTextInWord.Append(GetPlainText(section)); break; } } return PlainTextInWord.ToString(); }
public string GetText(OpenXmlElement run) { return(run is S.Run r ? r.ChildElements.OfType <S.Text>().SingleOrDefault()?.Text ?? "" : run is S.Text s ? s.Text ?? "" : ""); }
/// <summary> /// Validates the specified element. /// </summary> /// <param name="openXmlElement">The target OpenXmlElement.</param> /// <returns>A set of validation erros.</returns> /// <exception cref="ArgumentNullException">Thrown when the "openXmlElement" parameter is null.</exception> /// <exception cref="ArgumentOutOfRangeException">Thrown when the "openXmlElement" is type of OpenXmlUnknownElement, OpenXmlMiscNode, AlternateContent, AlternateContentChoice or AlternateContentFallback.</exception> /// <exception cref="InvalidOperationException">Thrown when the "openXmlElement" is not defined in the specified FileFormat.</exception> public IEnumerable <ValidationErrorInfo> Validate(OpenXmlElement openXmlElement) { if (openXmlElement == null) { throw new ArgumentNullException("openXmlElement"); } if (openXmlElement is OpenXmlUnknownElement) { throw new ArgumentOutOfRangeException("openXmlElement", ExceptionMessages.CannotValidateUnknownElement); } if (openXmlElement is OpenXmlMiscNode) { throw new ArgumentOutOfRangeException("openXmlElement", ExceptionMessages.CannotValidateMiscNode); } if (openXmlElement is AlternateContent || openXmlElement is AlternateContentChoice || openXmlElement is AlternateContentFallback) { throw new ArgumentOutOfRangeException("openXmlElement", ExceptionMessages.CannotValidateAcbElement); } if (!openXmlElement.IsInVersion(this.FileFormat)) { switch (this.FileFormat) { case FileFormatVersions.Office2007: throw new InvalidOperationException(ExceptionMessages.ElementIsNotInOffice2007); case FileFormatVersions.Office2010: throw new InvalidOperationException(ExceptionMessages.ElementIsNotInOffice2010); case FileFormatVersions.Office2013: throw new InvalidOperationException(ExceptionMessages.ElementIsNotInOffice2013); case FileFormatVersions.Office2016: throw new InvalidOperationException(ExceptionMessages.ElementIsNotInOffice2016); } } // TODO: if the FileFormat is Office2007, and the element is only in Office2010 and O15. // then this method should throw exceptions. var validationResult = new ValidationResult(); validationResult.Valid = true; validationResult.MaxNumberOfErrors = this._settings.MaxNumberOfErrors; validationResult.MaxNumberOfErrorsEventHandler += this.SchemaValidator.OnCancel; var validationContext = new ValidationContext(); // this.ValidationContext.Settings = new ValidationSettings(this.FileFormat, this.SchemaOnly); validationContext.FileFormat = this.FileFormat; validationContext.ValidationErrorEventHandler += validationResult.OnValidationError; validationContext.Element = openXmlElement; // Do NOT use "yield return" in this method, as "yield return" are deferred executed. // Otherwise, the null check is not performed when the method is called, but rather, when the returned enumerator is moved for the first time. // That means that the exception isn't thrown until possibly far, far away from the actual site of the error, which is potentially confusing. this.SchemaValidator.Validate(validationContext); validationContext.Element = openXmlElement; this.FullSemanticValidator.Validate(validationContext); return(this.YieldResult(validationResult)); }
/// <summary> /// Traversing down the specified element using HasChildren, FirstChild, LastChild, ChildElements(), Descendants(), Elements() /// GetFirstChildOfType, and GetEnumerator methods /// </summary> /// <typeparam name="U">The specified child type need to be traversed</typeparam> /// <param name="part">the OpenXmlPart in which the element exists</param> /// <param name="root">the OpenXmlElement need to be traversed</param> private void TestTraverseDown <U>(OpenXmlPart part, OpenXmlElement root) where U : OpenXmlElement { string UTagName = (Activator.CreateInstance(typeof(U)) as OpenXmlElement).LocalName; XElement Xroot = ConvertToXElement(part, root); Log.Comment(" ****** test HasChildren ******"); Log.Comment("check if the hasChildren is correct"); Log.VerifyTrue(Xroot.HasElements == root.HasChildren, "hasChildren is not correct"); if (root.HasChildren) { OpenXmlElement firstChild = root.FirstChild; XElement XfirstChild = Xroot.Elements().ElementAt(0); Log.Comment(" ****** test FirstChild ******"); Log.Comment("check if the first child retrieved is correct"); VerifyEqual(XfirstChild, ConvertToXElement(part, firstChild), null); Log.Comment(" ****** test LastChild ******"); Log.Comment("check if the last child retrieved is correct"); VerifyEqual(Xroot.Elements().Last(), ConvertToXElement(part, root.LastChild), null); Log.Comment(" ****** test ChildElements ******"); Log.Comment("check if the children is returned correct"); VerifyEqual(Xroot.Elements(), root.ChildElements, part); Log.Comment(" ****** test Descendants ******"); Log.Comment("check if the descendants if the first child returned are correct"); VerifyEqual(Xroot.Descendants(), root.Descendants(), part); Log.Comment(" ******test Elements<T> ******"); Log.Comment("check if the Element<OpenXmlElement> returned are correct"); VerifyEqual(Xroot.Elements(), root.Elements <OpenXmlElement>(), part); Log.Comment("check if the Element<{0}> returned are correct", typeof(U).Name); VerifyEqual(Xroot.Elements().Where(x => x.Name.LocalName == UTagName), root.Elements <U>(), part); Log.Comment(" ****** test Descendants<T> ******"); Log.Comment("check if the Descendants<OpenXmlElement> of the first child are returned correctly"); VerifyEqual(Xroot.Descendants(), root.Descendants <OpenXmlElement>(), part); Log.Comment("check if the Descendants<{0}> returned are correct", typeof(U).Name); VerifyEqual(Xroot.Descendants().Where(x => x.Name.LocalName == UTagName), root.Descendants <U>(), part); Log.Comment(" ****** test GetFirstChildOfType<T> ******"); Log.Comment("check if the GetFirstChild<OpenXmlElement> returns the first child element"); VerifyEqual(Xroot.Elements().First(), ConvertToXElement(part, root.GetFirstChild <OpenXmlElement>()), null); Log.Comment("check if the GetFirstChild<{0}> returns the correct result", typeof(U).Name); VerifyEqual(Xroot.Elements().Where(x => x.Name.LocalName == UTagName).First(), ConvertToXElement(part, root.GetFirstChild <U>()), null); Log.Comment(" ****** test GetEnumerator() ******"); Log.Comment("check if the GetEnumerator returns the correct result"); VerifyEqual(Xroot.Elements(), root, part); Log.Comment("***** test IsBefore() ******"); foreach (var element in root.Descendants()) { if (root.FirstChild == element) { Log.VerifyFalse(root.FirstChild.IsBefore(element), "Expect: False <> Actual: True"); Log.VerifyFalse(root.FirstChild.IsAfter(element), "Expect: False <> Actual: True"); } else { Log.VerifyTrue(root.FirstChild.IsBefore(element), "Expect: True <> Actual: False"); Log.VerifyFalse(root.FirstChild.IsAfter(element), "Expect: False <> Actual: True"); } } Log.Comment("****** test IsAfter() ******"); foreach (var element in root.Elements()) { if (element == root.LastChild) { Log.VerifyFalse(root.LastChild.IsAfter(element), "Expect: False <> Actual: True"); Log.VerifyFalse(root.LastChild.IsBefore(element), "Expect: False <> Actual: True"); } else { Log.VerifyTrue(root.LastChild.IsAfter(element), "Expect: True <> Actual: False"); Log.VerifyFalse(root.LastChild.IsBefore(element), "Expect: False <> Actual: True"); } } } else { Log.Warning("No Children exists"); } }
internal static OpenXmlElement GetFirstChildMc(this OpenXmlElement parent, MCContext mcContext, FileFormatVersions format) { var child = parent.GetFirstNonMiscElementChild(); return(parent.GetChildMc(child, mcContext, format)); }
/// <summary> /// Sets the element's first child of a given type, either replacing an existing /// one or appending the first one. /// </summary> /// <typeparam name="T">A subclass of OpenXmlElement</typeparam> /// <param name="element">The element</param> /// <param name="newChild">The new child</param> /// <returns>The new child</returns> public static T SetFirstChild <T>(this OpenXmlElement element, T newChild) where T : OpenXmlElement { var oldChild = element.GetFirstChild <T>(); return(oldChild != null?element.ReplaceChild(newChild, oldChild) : element.AppendChild(newChild)); }
private void UpdateElements(OpenXmlElement root, List<OpenXmlElement> elements, IEnumerable<ProjectFile> projectFiles, Customer customer, User user) { foreach (var projectFile in projectFiles) { UpdateSingleFile(root, elements, new List<TokensProvider>() {customer, user, projectFile}); #region empty lines var emptyLineParagraph = new Paragraph() { RsidParagraphAddition = "0077013B", RsidRunAdditionDefault = "00684C81", ParagraphId = "5E06053C", TextId = "77777777" }; var emptyLineRun = new Run(); var emptyLineText = new Text() { Text = String.Empty }; emptyLineRun.Append(emptyLineText); emptyLineParagraph.Append(emptyLineRun); root.Append(emptyLineParagraph); root.Append((OpenXmlElement)emptyLineParagraph.Clone()); #endregion } }
public OpenXmlBarChartSeries(OpenXmlElement series) : base(series) { }
public OpenXmlCompositeElement CastRun(OpenXmlElement element) { return((D.Run)element); }
public OpenXmlCompositeElement WrapInRun(OpenXmlElement text) { throw new NotImplementedException(); }
public bool IsRunProperties(OpenXmlElement element) { return(element is W.RunProperties); }
public bool IsParagraph(OpenXmlElement element) { return(element is W.Paragraph); }
public bool IsText(OpenXmlElement a) { return(a is W.Text); }
public bool IsRun(OpenXmlElement a) { return(a is W.Run); }
public static bool IsImportant(OpenXmlElement c) { if (c is Paragraph) return true; if (c is Run) { var text = c.ChildElements.Where(a => !(a is RunProperties)).Only() as Text; if (text != null && string.IsNullOrWhiteSpace(text.Text)) return false; return true; } if (c is BaseNode) return true; return false; }
/// <summary> /// Retrieve built-in OpenXmlAttributes of the type of pass-in OpenXmlElement /// </summary> /// <param name="e">OpenXmlElement or derived classes that has properties with SchemaAttrAttribute</param> /// <returns>IEnumerable<OpenXmlAttribute> for fixed attributes of type of pass-in OpenXmlElement</returns> public static IEnumerable <OpenXmlAttribute> GetFixedAttributes(this OpenXmlElement e) => e?.Attributes;
public NavigatorAdapter(OpenXmlElement elem) { _elem = elem; }
/// <summary> /// Traversing siblings of the specified element using PreviousSibling, PreviousSibling < T > /// NextSibling, NextSibling<T>, ElementsBefore, ElementsAfter, IsBefore, IsAfter"/> /// </summary> /// <typeparam name="U">Type of the sibling used by generic traversing method</typeparam> /// <param name="part">the OpenXmlPart in which the element exists</param> /// <param name="Element">the OpenXmlElement need to be traversed</param> private void TestTraverseSibling <U>(OpenXmlPart part, OpenXmlElement Element) where U : OpenXmlElement { string UTagName = (Activator.CreateInstance(typeof(U)) as OpenXmlElement).LocalName; OpenXmlElement walker = Element; XElement Xele = ConvertToXElement(part, Element); XElement Xwalker = Xele; Log.Comment("****** test ElementsAfter ******"); VerifyEqual(Xwalker.ElementsAfterSelf(), walker.ElementsAfter(), part); Log.Comment("****** test NextSibling ******"); Log.Comment("check if the nextSibling returns correctly"); while (Xwalker.NextNode != null && walker.NextSibling() != null) { Xwalker = Xwalker.ElementsAfterSelf().First(); walker = walker.NextSibling(); VerifyEqual(Xwalker, walker, part); } if (Xwalker.NextNode == null && walker.NextSibling() == null) { Log.Comment("check if the current element is the last sibling of the original element"); VerifyEqual(Xele.Parent.Elements().Last(), walker, part); Log.Pass("All next siblings have been retrieved correctly"); } else { Log.Fail("nextSibling doesn't return correctly"); } Log.Comment("****** test ElementsBefore ******"); VerifyEqual(Xwalker.ElementsBeforeSelf(), walker.ElementsBefore(), part); Log.Comment("****** test PreviousSibling ******"); while (Xwalker.PreviousNode != null && walker.PreviousSibling() != null) { Xwalker = Xwalker.ElementsBeforeSelf().Last(); walker = walker.PreviousSibling(); VerifyEqual(Xwalker, walker, part); } if (Xwalker.PreviousNode == null && walker.PreviousSibling() == null) { Log.Comment("check if the current element is the first sibling of the original element"); VerifyEqual(Xele.Parent.Elements().First(), walker, part); Log.Pass("All Previous siblings have been retrieved correctly"); } else { Log.Fail("PreviousSibling doesn't return correctly"); } Log.Comment("****** test NextSibling<OpenXmlElement> ******"); while (Xwalker.NextNode != null && walker.NextSibling() != null) { Xwalker = Xwalker.ElementsAfterSelf().First(); walker = walker.NextSibling <OpenXmlElement>(); VerifyEqual(Xwalker, walker, part); } if (Xwalker.NextNode == null && walker.NextSibling() == null) { Log.Comment("check if the current element is the last sibling of the original element"); VerifyEqual(Xele.Parent.Elements().Last(), walker, part); Log.Pass("All next siblings have been retrieved correctly"); } else { Log.Fail("nextSibling doesn't return correctly"); } Log.Comment("****** test PreviousSibling<OpenXmlElement>() ******"); while (Xwalker.PreviousNode != null && walker.PreviousSibling <OpenXmlElement>() != null) { Xwalker = Xwalker.ElementsBeforeSelf().Last(); walker = walker.PreviousSibling <OpenXmlElement>(); VerifyEqual(Xwalker, walker, part); } if (Xwalker.PreviousNode == null && walker.PreviousSibling <OpenXmlElement>() == null) { Log.Comment("check if the current element is the first sibling of the original element"); VerifyEqual(Xele.Parent.Elements().First(), walker, part); Log.Pass("All Previous siblings have been retrieved correctly"); } else { Log.Fail("PreviousSibling doesn't return correctly"); } Log.Comment("****** test NextSibling<{0}> ******", typeof(U).Name); while (Xwalker.ElementsAfterSelf().Where(x => x.Name.LocalName == UTagName).Any() && walker.NextSibling <U>() != null) { Xwalker = Xwalker.ElementsAfterSelf().Where(x => x.Name.LocalName == UTagName).First(); walker = walker.NextSibling <U>(); VerifyEqual(Xwalker, walker, part); } Log.Comment("****** test PreviousSibling<{0}>() ******", typeof(U).Name); while (Xwalker.ElementsBeforeSelf().Where(x => x.Name.LocalName == UTagName).Any() && walker.PreviousSibling <U>() != null) { Xwalker = Xwalker.ElementsBeforeSelf().Where(x => x.Name.LocalName == UTagName).Last(); walker = walker.PreviousSibling <U>(); VerifyEqual(Xwalker, walker, part); } }
internal static OpenXmlElement GetNextChildMc(this OpenXmlElement parent, OpenXmlElement child, MCContext mcContext, FileFormatVersions format) { var next = child.GetNextNonMiscElementSibling(); var mcTier = child.Parent; if (next == null && mcTier != parent) { // the child must be under element in ProcessContent or ACB if (mcTier is AlternateContentChoice || mcTier is AlternateContentFallback) { mcTier = mcTier.Parent; } Debug.Assert(mcTier != null); // there is no more next sibling in this level, then try to find the next siblig of the up level. return parent.GetNextChildMc(mcTier, mcContext, format); } return parent.GetChildMc(next, mcContext, format); }
public static OpenXmlElement Render(this Paragraph paragraph, OpenXmlElement parent, ContextModel context, IFormatProvider formatProvider) { context.ReplaceItem(paragraph, formatProvider); var openXmlPar = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(); openXmlPar.ParagraphProperties = new DocumentFormat.OpenXml.Wordprocessing.ParagraphProperties() { Shading = new DocumentFormat.OpenXml.Wordprocessing.Shading() { Fill = paragraph.Shading }, Justification = new DocumentFormat.OpenXml.Wordprocessing.Justification() { Val = paragraph.Justification.ToOOxml() }, SpacingBetweenLines = new DocumentFormat.OpenXml.Wordprocessing.SpacingBetweenLines() }; if (paragraph.SpacingBefore.HasValue) { openXmlPar.ParagraphProperties.SpacingBetweenLines.Before = paragraph.SpacingBefore.ToString(); } if (paragraph.SpacingAfter.HasValue) { openXmlPar.ParagraphProperties.SpacingBetweenLines.After = paragraph.SpacingAfter.ToString(); } if (paragraph.SpacingBetweenLines.HasValue) { openXmlPar.ParagraphProperties.SpacingBetweenLines.Line = paragraph.SpacingBetweenLines.ToString(); } if (!string.IsNullOrWhiteSpace(paragraph.ParagraphStyleId)) { openXmlPar.ParagraphProperties.ParagraphStyleId = new DocumentFormat.OpenXml.Wordprocessing.ParagraphStyleId() { Val = paragraph.ParagraphStyleId } } ; if (paragraph.Borders != null) { openXmlPar.ParagraphProperties.AppendChild(paragraph.Borders.RenderParagraphBorder()); } if (paragraph.Keeplines) { openXmlPar.ParagraphProperties.KeepLines = new DocumentFormat.OpenXml.Wordprocessing.KeepLines(); } if (paragraph.KeepNext) { openXmlPar.ParagraphProperties.KeepNext = new DocumentFormat.OpenXml.Wordprocessing.KeepNext(); } if (paragraph.PageBreakBefore) { openXmlPar.ParagraphProperties.PageBreakBefore = new DocumentFormat.OpenXml.Wordprocessing.PageBreakBefore(); } // Indents : if (paragraph.Indentation != null) { openXmlPar.ParagraphProperties.Indentation = paragraph.Indentation.ToOpenXmlElement(); } parent.Append(openXmlPar); return(openXmlPar); }
public OpenXmlCompositeElement WrapInRun(OpenXmlElement text) { return(new S.Run(text)); }
public void ReplaceString(OpenXmlElement element, string val) { var text = element.Descendants <Word.Text>().FirstOrDefault(); var run = text == null?element.Descendants <Word.Run>().FirstOrDefault() : FindParent <Word.Run>(text); var runp = (OpenXmlElement)null; if (run == null) { runp = element; run = new Word.Run(); runp.Append(run); } else { runp = run.Parent; } var paragraph = FindParent <Word.Paragraph>(runp); run.RsidRunProperties = null; run.RemoveAllChildren <Word.Text>(); run.RemoveAllChildren <Word.RunProperties>(); runp.RemoveAllChildren <Word.Run>(); runp.RemoveAllChildren <Word.Break>(); if (paragraph.ParagraphProperties?.ParagraphMarkRunProperties != null) { run.RunProperties = new Word.RunProperties(); foreach (var item in paragraph.ParagraphProperties.ParagraphMarkRunProperties) { run.RunProperties.AppendChild(item.CloneNode(true)); } } if (text == null) { text = new Word.Text(); } else if (text.Parent != null) { text.Remove(); } string[] pagesplit = val.TrimEnd("\r\n".ToCharArray()).Split("\f".ToCharArray(), StringSplitOptions.RemoveEmptyEntries); for (int p = 0; p < pagesplit.Length; p++) { var lineSpit = pagesplit[p].Split(new string[] { "\r\n", "\n" }, StringSplitOptions.None); if (lineSpit.Length > 0) { for (int i = 0; i < lineSpit.Length; i++) { if (p == 0 && i == 0) { text.Text = lineSpit[0]; text.Space = SpaceProcessingModeValues.Preserve; run.Append(text); runp.Append(run); continue; } Word.Run r = run.Clone() as Word.Run; r.RemoveAllChildren <Word.Text>(); r.Append(new Word.Text(lineSpit[i]) { Space = SpaceProcessingModeValues.Preserve }); Word.Paragraph pr = (Word.Paragraph)paragraph.Clone(); pr.RemoveAllChildren <Word.Run>(); pr.RemoveAllChildren <Word.Break>(); pr.RemoveAllChildren <Word.SdtBlock>(); pr.RemoveAllChildren <Word.SdtRun>(); pr.Append(r); paragraph.Parent.InsertAfter <Word.Paragraph>(pr, paragraph); paragraph = pr; } } if (p < pagesplit.Length - 1) { var bp = new Word.Break() { Type = Word.BreakValues.Page }; paragraph.AppendChild(bp); } } }
protected static XmlQualifiedName GetAttributeQualifiedName(OpenXmlElement element, byte attributeID) { return(new XmlQualifiedName(element.AttributeTagNames[attributeID], NamespaceIdMap.GetNamespaceUri(element.AttributeNamespaceIds[attributeID]))); }
public bool IsParagraph(OpenXmlElement element) { return(false); }
public ActionResult PrictDoc(string doctext) { List <TemplateSectionVo> Grid = JsonConvert.DeserializeObject <List <TemplateSectionVo> >(doctext); //htmlString = "<h1 style='text-align: center;'><strong>Report</strong></h1>" + "<br>"; string sourceFile = Server.MapPath(Path.Combine("/", "Themes/Template/PSURTemplate.dotx")); var filename = Path.GetFileNameWithoutExtension(sourceFile); destinationFile = Server.MapPath(Path.Combine("/", "Themes/DownloadDocs/" + "PBRER" + DateTime.Now.ToString("dd_MM_yyyy_HH_mm_ss") + ".docx")); try { // Create a copy of the template file and open the copy System.IO.File.Copy(sourceFile, destinationFile, true); WordprocessingDocument wordDoc = WordprocessingDocument.Open(destinationFile, true); wordDoc.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document); //marker for main document part var mainDocPart = wordDoc.MainDocumentPart; //Iterate through the paragraphs to find the bookmarks inside //load bookmarks var bookmarks = mainDocPart.Document.Body.Descendants <BookmarkStart>(); for (int i = 0; i < Grid.Count; i++) { //find our bookmark string bookmarkname1 = Regex.Match(Grid[i].Section, @"(\d+.\d+.\d+.|\d+.\d+.|\d+.)").Value; string bookmarkname = bookmarkname1.Replace(".", "_"); //get to first element if (bookmarkname1 == null || bookmarkname1 == "") { bookmarkname = Regex.Replace(Grid[i].Section, @"[\d+|.|\s]", ""); } var bookmark = from bookmarkIndex in bookmarks where bookmarkIndex.Name == "BK_" + bookmarkname select bookmarkIndex; if (bookmark.Count() > 0) { htmlString = ""; if (Grid[i].Template_Content != null) { htmlString = "<html>" + Grid[i].Template_Content.Replace("<table>", "<table border='1' style=' border-collapse: collapse; border: 1px solid black;width:100%;'>"); } string UrlLink = new Uri(Request.Url, Url.Content("~")).AbsoluteUri + "ImageBrowser/Image"; string source = "/ImageBrowser/Image"; string CON = htmlString; htmlString = CON.Replace(source, UrlLink); OpenXmlElement elem = bookmark.First().Parent; String cid = "chunkid_" + i; MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(htmlString)); AlternativeFormatImportPart formatImportPart = wordDoc.MainDocumentPart.AddAlternativeFormatImportPart(AlternativeFormatImportPartType.Html, cid); formatImportPart.FeedData(ms); AltChunk altChunk = new AltChunk(); altChunk.Id = cid; elem.InsertAfterSelf <AltChunk>(altChunk); elem.Remove(); } } DocumentSettingsPart settingsPart = mainDocPart.Document.MainDocumentPart.GetPartsOfType <DocumentSettingsPart>().First(); // Create object to update fields on open UpdateFieldsOnOpen updateFields = new UpdateFieldsOnOpen(); updateFields.Val = new DocumentFormat.OpenXml.OnOffValue(true); // Insert object into settings part. settingsPart.Settings.PrependChild <UpdateFieldsOnOpen>(updateFields); settingsPart.Settings.Save(); wordDoc.Close(); return(Json("Sucess")); } catch (Exception ex) { //string ErrorData = "Please Close the Word and try again"; return(Json(ex.Message)); } return(Json("Sucess")); }
/// <summary> /// Sets the SDT content keeping permission elements. /// </summary> /// <param name="openXmlCompositeElement">The open XML composite element.</param> /// <param name="newChild">The new child.</param> private void SetSdtContentKeepingPermissionElements(OpenXmlCompositeElement openXmlCompositeElement, OpenXmlElement newChild) { PermStart start = openXmlCompositeElement.Descendants <PermStart>().FirstOrDefault(); PermEnd end = openXmlCompositeElement.Descendants <PermEnd>().FirstOrDefault(); openXmlCompositeElement.RemoveAllChildren(); if (start != null) { openXmlCompositeElement.AppendChild(start); } openXmlCompositeElement.AppendChild(newChild); if (end != null) { openXmlCompositeElement.AppendChild(end); } }
/// <summary> /// Возвращает предкорневой элемент документа /// </summary> /// <param name="element"></param> /// <returns></returns> private OpenXmlElement GetParentToPasteSchedule(OpenXmlElement element) { return((element.Parent is Body) ? element : GetParentToPasteSchedule(element.Parent)); }
/// <summary> /// Validate the DOM tree under the specified OpenXmlElement. /// </summary> /// <param name="schemaValidator">The schemaValidator.</param> /// <param name="openXmlElement">The root of the sub tree.</param> /// <returns>Returns the validation result in ValidationResult.</returns> /// <remarks> /// Only schema validating. /// </remarks> public static List <ValidationErrorInfo> Validate(this SchemaValidator schemaValidator, OpenXmlElement openXmlElement) { Debug.Assert(openXmlElement != null); Debug.Assert(!(openXmlElement is OpenXmlUnknownElement || openXmlElement is OpenXmlMiscNode)); // Can not just validate AlternateContent / Choice / Fallback Debug.Assert(!(openXmlElement is AlternateContentChoice || openXmlElement is AlternateContentFallback)); var validationContext = new ValidationContext(); validationContext.Stack.Push(element: openXmlElement); schemaValidator.Validate(validationContext); return(validationContext.Errors); }
private void InsertImage(WordprocessingDocument wpd, OpenXmlElement parent, string filepath) { string relationId = AddGraph(wpd, filepath); if (!string.IsNullOrEmpty(relationId)) { Size size = new Size(800, 600); Int64Value width = size.Width * 9525; Int64Value height = size.Height * 9525; var draw = new Drawing( new DW.Inline( new DW.Extent() { Cx = width, Cy = height }, new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new DW.DocProperties() { Id = (UInt32Value)1U, Name = "Its me" }, new DW.NonVisualGraphicFrameDrawingProperties(new A.GraphicFrameLocks() { NoChangeAspect = true }), new A.Graphic( new A.GraphicData( new PIC.Picture( new PIC.NonVisualPictureProperties( new PIC.NonVisualDrawingProperties() { Id = (UInt32Value)0U, Name = relationId }, new PIC.NonVisualPictureDrawingProperties()), new PIC.BlipFill( new A.Blip( new A.BlipExtensionList( new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }) ) { Embed = relationId, CompressionState = A.BlipCompressionValues.Print }, new A.Stretch( new A.FillRectangle())), new PIC.ShapeProperties( new A.Transform2D( new A.Offset() { X = 0L, Y = 0L }, new A.Extents() { Cx = width, Cy = height }), new A.PresetGeometry(new A.AdjustValueList()) { Preset = A.ShapeTypeValues.Rectangle }))) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U, EditId = "50D07946" }); parent.Append(draw); } }
private void UpdateElementsForRoot(Customer customer, User user, OpenXmlElement root) { List <OpenXmlElement> elements = InitializeRoot(root, false); UpdateElements(root, elements, customer, user); }
public string GetText(OpenXmlElement run) { return(run.ChildElements.OfType <W.Text>().SingleOrDefault()?.Text ?? ""); }
private void AssertNotImportant(List<OpenXmlElement> chain, OpenXmlElement openXmlElement, MatchNode errorHintParent, MatchNode errorHint1, MatchNode errorHint2) { var index = chain.IndexOf(openXmlElement); for (int i = index; i < chain.Count; i++) { var current = chain[i]; var next = i == chain.Count - 1 ? null : chain[i + 1]; var important = current.ChildElements.Where(c => c != next && IsImportant(c)); if (important.Any()) throw new InvalidOperationException("Node {0} is not at the same level than {1}{2}. Important nodes could be removed close to {0}:\r\n{3}".FormatWith( errorHint1.Match, errorHint2.Match, errorHintParent != errorHint1 && errorHintParent != errorHint2 ? " in " + errorHintParent.Match : "", current.NiceToString())); } }
private void UpdateElementsForRoot(IEnumerable <ProjectFile> projectFiles, Customer customer, User user, OpenXmlElement root) { List <OpenXmlElement> elements = InitializeRoot(root); UpdateElements(root, elements, projectFiles, customer, user); }
public static void ReplaceBy(this OpenXmlElement element, OpenXmlElement replacement) { element.Parent.ReplaceChild(replacement, element); }
/// <summary> /// 複製してTに変換します。 /// </summary> /// <typeparam name="T">変換する型</typeparam> /// <param name="value">複数元</param> /// <returns>複製したオブジェクト</returns> public static T CloneElement <T>(this OpenXmlElement value) where T : OpenXmlElement { return(value.CloneNode(true) as T); }
/// <summary> /// Validate attributes on AlternateContent, Choice and Fallback element. /// </summary> /// <param name="validationContext"></param> /// <param name="acElement">The element to be validated.</param> private static void ValidateMcAttributesOnAcb(ValidationContext validationContext, OpenXmlElement acElement) { ValidationErrorInfo errorInfo; // AlternateContent elements might include the attributes Ignorable, MustUnderstand, ProcessContent, PreserveElements, and PreserveAttributes // These attributes’ qualified names shall be prefixed when associated with an AlternateContent / Choice / Fallback element. // A markup consumer shall generate an error if it encounters an unprefixed attribute name associated with an AlternateContent element. if (acElement.ExtendedAttributes != null) { foreach (var exAttribute in acElement.ExtendedAttributes) { if (string.IsNullOrEmpty(exAttribute.Prefix)) { // error on any unprefixed attributes errorInfo = validationContext.ComposeMcValidationError(acElement, ValidationResources.MC_ErrorOnUnprefixedAttributeName, exAttribute.XmlQualifiedName.ToString()); validationContext.EmitError(errorInfo); } // Markup consumers shall generate an error if they encounter the xml:lang or xml:space attributes on an AlternateContent element. // Markup consumers shall generate an error if they encounter the xml:lang or xml:space attributes on a Choice element, regardless of whether the element is preceded by a selected Choice element. // Markup consumers shall generate an error if they encounter the xml:lang or xml:space attributes on a Fallback element, regardless of whether the element is preceded by a selected Choice element. if (IsXmlSpaceOrXmlLangAttribue(exAttribute)) { // report error. errorInfo = validationContext.ComposeMcValidationError(acElement, "MC_InvalidXmlAttribute", acElement.LocalName); validationContext.EmitError(errorInfo); } } } // validate MC attribues (Ignorable, PreserveElements, etc.) of this element. CompatibilityRuleAttributesValidator.ValidateMcAttributes(validationContext); AlternateContentChoice choice = acElement as AlternateContentChoice; if (choice != null) { // All Choice elements shall have a Requires attribute whose value contains a whitespace-delimited list of namespace prefixes if (choice.Requires == null) { // report error errorInfo = validationContext.ComposeMcValidationError(acElement, "MC_MissedRequiresAttribute"); validationContext.EmitError(errorInfo); } else { var prefixes = new ListValue<StringValue>(); prefixes.InnerText = choice.Requires; foreach (var prefix in prefixes.Items) { var ignorableNamespace = choice.LookupNamespace(prefix); if (string.IsNullOrEmpty(ignorableNamespace)) { // report error, the prefix is not defined. errorInfo = validationContext.ComposeMcValidationError(choice, "MC_InvalidRequiresAttribute", choice.Requires); validationContext.EmitError(errorInfo); } } } } }
public TextPart(int startIndex, int length, OpenXmlElement element) { _startIndex = startIndex; _length = length; _element = element; }
private static OpenXmlElement GetChildMc(this OpenXmlElement parent, OpenXmlElement child, MCContext mcContext, FileFormatVersions format) { // Use stack to cache the next siblings in different levels. Stack<OpenXmlElement> nextSiblings = new Stack<OpenXmlElement>(); while (child != null) { var acb = child as AlternateContent; if (acb == null && child.IsInVersion(format)) { return child; } else { mcContext.PushMCAttributes2(child.MCAttributes, child.LookupNamespace); if (acb != null) { nextSiblings.Push(child.GetNextNonMiscElementSibling()); var select = mcContext.GetContentFromACBlock(acb, format); if (select != null) { child = select.GetFirstNonMiscElementChild(); } else { // The ACB has no children elements. // case like: <acb/> <acb><choice/><fallback/></acb> child = null; } } else { // Ignorable element, skip it if (mcContext.IsIgnorableNs(child.NamespaceUri)) { // Any element marked with ProcessContent should be an Ignorable Element if (mcContext.IsProcessContent(child)) { nextSiblings.Push(child.GetNextNonMiscElementSibling()); // child = child.GetFirstNonMiscElementChild(); } else { child = child.GetNextNonMiscElementSibling(); } } else { mcContext.PopMCAttributes2(); return child; } } mcContext.PopMCAttributes2(); } while (child == null && nextSiblings.Count > 0) { child = nextSiblings.Pop(); } } // child is null. return child; }
public Token(OpenXmlElement specialContent, TokenType type) { Type = type; SpecialContent = specialContent; }