protected static void ClearBetweenElements(OpenXmlElement start, OpenXmlElement end)
 {
     while (start.NextSibling() != end && start.NextSibling() != end)
     {
         start.NextSibling().Remove();
     }
 }
        /// <summary>
        /// Traversing siblings of the specified element using PreviousSibling, PreviousSibling &lt T &gt
        /// NextSibling, NextSibling&ltT&gt, 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 is not null && walker.NextSibling() is not null)
            {
                Xwalker = Xwalker.ElementsAfterSelf().First();
                walker  = walker.NextSibling();

                VerifyEqual(Xwalker, walker, part);
            }

            if (Xwalker.NextNode is null && walker.NextSibling() is 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");
            }
Example #3
0
        /// <summary>
        /// Convert File Stream to Range Object
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static ICollection <Range> ConvertStreamToRange(Stream stream)
        {
            using (var wordDoc = WordprocessingDocument.Open(stream, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                var document = mainPart.Document;
                var comments = mainPart.WordprocessingCommentsPart.Comments.ChildElements;
                foreach (Comment comment in comments)
                {
                    CommentRange commentRange = new CommentRange();
                    commentRange.Id       = int.Parse(comment.Id);
                    commentRange.Initials = comment.Initials;
                    commentRange.Date     = comment.Date;
                    commentRange.Author   = comment.Author;
                    commentRange.Text     = comment.InnerText;
                    OpenXmlElement        rangeStart = document.Descendants <CommentRangeStart>().Where(c => c.Id.Value == comment.Id.Value).FirstOrDefault();
                    List <OpenXmlElement> referenced = new List <OpenXmlElement>();
                    List <Range>          ranges     = new List <Range>();
                    rangeStart = rangeStart.NextSibling();

                    while (!(rangeStart is CommentRangeEnd))
                    {
                        referenced.Add(rangeStart);
                        rangeStart = rangeStart.NextSibling();
                        ranges.Add(new Range {
                            Text = rangeStart.InnerText
                        });
                    }
                }
                return(null);
            }
        }
Example #4
0
        internal static void RemoveAllChildren <T>(this OpenXmlElement value, string localName, string namespaceUri, string match) where T : OpenXmlElement
        {
            if (!value.HasChildren)
            {
                return;
            }

            OpenXmlElement element = value.FirstChild;
            OpenXmlElement next;

            while (element != null)
            {
                next = element.NextSibling();

                if (element is T)
                {
                    if (!element.HasAttributes)
                    {
                        continue;
                    }

                    var attribute = element.GetAttribute(localName, namespaceUri);

                    if (attribute.Value.Equals(match, StringComparison.OrdinalIgnoreCase))
                    {
                        value.RemoveChild(element);
                    }
                }

                element = next;
            }
        }
Example #5
0
        public static void ImagenMarcador(WordprocessingDocument pDocumento, BookmarkStart pMarcador, string pImagen)
        {
            // Eliminar todo dentro del marcador
            OpenXmlElement elem = pMarcador.NextSibling();

            while (elem != null && !(elem is BookmarkEnd))
            {
                OpenXmlElement nextElem = elem.NextSibling();
                elem.Remove();
                elem = nextElem;
            }

            var imagePart = AgregarImagePart(pDocumento.MainDocumentPart, pImagen);

            #region Dimensiones Imagen

            // Calcular el tamaño según las dimensiones del archivo
            var       img           = new BitmapImage(new Uri(pImagen, UriKind.RelativeOrAbsolute));
            var       anchoPx       = img.PixelWidth;
            var       altoPx        = img.PixelHeight;
            var       dpiHorizontal = img.DpiX;
            var       dpiVertical   = img.DpiY;
            const int emusPerInch   = 914400;

            var anchoEmus = (long)(anchoPx / dpiHorizontal * emusPerInch);
            var altoEmus  = (long)(altoPx / dpiVertical * emusPerInch);

            #endregion

            // Insertar imagen
            AgregarImagen(pDocumento.MainDocumentPart.GetIdOfPart(imagePart), pMarcador, anchoEmus, altoEmus);
        }
Example #6
0
        private static void AppendText(string textValue, BookmarkStart bookmark)
        {
            var idParagraph = bookmark.Parent;

            Text text = new Text();

            text.Text = textValue;

            List <OpenXmlElement> siblings = new List <OpenXmlElement>();
            OpenXmlElement        sibling  = bookmark.NextSibling();

            while (sibling != null && !(sibling is BookmarkEnd))
            {
                siblings.Add(sibling);
                sibling = sibling.NextSibling();
            }

            var runSibling    = bookmark.NextSibling <Run>();
            var runProperties = GetRunProperties(runSibling);

            foreach (var s in siblings)
            {
                idParagraph.RemoveChild(s);
            }

            var run = new Run();

            if (runProperties != null)
            {
                run.AppendChild(runProperties);
            }
            run.AppendChild(text);
            idParagraph.AppendChild(run);
        }
Example #7
0
        public static void RemoveTextAndElementsBetween(
            this ICollection <Paragraph> paragraphs,
            TokenPosition from,
            TokenPosition to)
        {
            if (from.ParagraphIndex == to.ParagraphIndex)
            {
                paragraphs.ElementAt(from.ParagraphIndex).RemoveText(from.TextIndex, to.TextIndex);
                return;
            }

            paragraphs.ElementAt(from.ParagraphIndex).RemoveText(from.TextIndex);
            paragraphs.ElementAt(to.ParagraphIndex).RemoveText(0, to.TextIndex);

            var toSkip = from.ParagraphIndex;

            if (!string.IsNullOrEmpty(paragraphs.ElementAt(from.ParagraphIndex).InnerText))
            {
                toSkip++;
            }

            OpenXmlElement e = paragraphs.Skip(toSkip).FirstOrDefault();
            OpenXmlElement l = paragraphs.ElementAt(to.ParagraphIndex);

            while (e != null && e != l)
            {
                var t = e;
                e = e.NextSibling();
                t.Remove();
            }
        }
Example #8
0
        /// <summary>
        /// Convert Stream to CommentRange
        /// </summary>
        /// <param name="stream"></param>
        /// <returns></returns>
        public static ICollection <CommentRange> ConvertStreamToCommentRange(Stream stream)
        {
            List <CommentRange> commentRanges = new List <CommentRange>();

            using (var wordDoc = WordprocessingDocument.Open(stream, true))
            {
                MainDocumentPart mainPart = wordDoc.MainDocumentPart;
                var document = mainPart.Document;
                if (mainPart.WordprocessingCommentsPart == null)
                {
                    return(commentRanges);
                }
                var comments = mainPart.WordprocessingCommentsPart.Comments.ChildElements;

                foreach (Comment comment in comments)
                {
                    CommentRange commentRange = new CommentRange();
                    commentRange.Id       = int.Parse(comment.Id); //comment id is started from 0
                    commentRange.Initials = comment.Initials;
                    commentRange.Date     = comment.Date;
                    commentRange.Author   = comment.Author;
                    commentRange.Text     = comment.InnerText;
                    OpenXmlElement rangeStart = document.Descendants <CommentRangeStart>().Where(c => c.Id.Value == comment.Id.Value).FirstOrDefault();
                    rangeStart = rangeStart.NextSibling();

                    List <OpenXmlElement> referenced = new List <OpenXmlElement>();
                    //append range text until the commentRangeEnd with the same comment id
                    while (!(rangeStart is CommentRangeEnd && ((CommentRangeEnd)rangeStart).Id.Value == comment.Id.Value))
                    {
                        referenced.Add(rangeStart);
                        rangeStart = rangeStart.NextSibling();
                    }

                    foreach (var ele in referenced)
                    {
                        if (!string.IsNullOrWhiteSpace(ele.InnerText))
                        {
                            commentRange.CommentedText += ele.InnerText;
                        }
                    }
                    commentRanges.Add(commentRange);
                }
                return(commentRanges);
            }
        }
Example #9
0
        ///<summary>
        /// Removes all content from tag specified by <paramref name="tagName"/>
        ///</summary>
        ///<param name="tagName">Tag name</param>
        public void CleanContent(string tagName)
        {
            OpenXmlElement startTag = GetParagraph(GetOpenTagName(tagName));

            if (startTag == null)
            {
                return;
            }

            OpenXmlElement openXmlElement = startTag.NextSibling();

            while (openXmlElement.InnerText != GetCloseTagName(tagName))
            {
                openXmlElement.Remove();
                openXmlElement = startTag.NextSibling();
            }
            _wordDocument.MainDocumentPart.Document.Save();
        }
Example #10
0
            public bool MoveNext()
            {
                Current = null;

                while (_child != null)
                {
                    if (_child.GetType() == typeof(TElement))
                    {
                        Current = (TElement)_child;
                        _child  = _child.NextSibling();
                        return(true);
                    }

                    _child = _child.NextSibling();
                }

                return(false);
            }
        public RecordsList GetCommentsWithText()
        {
            RecordsList records = new RecordsList();

            WordprocessingCommentsPart commentsPart = wordDocument.MainDocumentPart.WordprocessingCommentsPart;

            if (commentsPart != null && commentsPart.Comments != null)
            {
                foreach (Comment comment in commentsPart.Comments.Elements <Comment>())
                {
                    OpenXmlElement rangeStart = wordDocument.MainDocumentPart.Document.Descendants <CommentRangeStart>().Where(c => c.Id == comment.Id).FirstOrDefault();
                    //bool breakLoop = false;
                    //rangeStart = rangeStart.Parent;
                    rangeStart = rangeStart.NextSibling();
                    string commentText = "";
                    while (!(rangeStart is CommentRangeEnd))
                    {
                        try
                        {
                            if (!string.IsNullOrWhiteSpace(rangeStart.InnerText))
                            {
                                commentText += rangeStart.InnerText;
                            }
                            rangeStart = rangeStart.NextSibling();
                        }
                        catch (NullReferenceException ex)
                        {
                            Console.WriteLine(ex.Message);
                            Console.WriteLine("NullReference Exception on " + comment.InnerText + " with highlited text: " + commentText);
                            commentText += " !!!ERROR WHILE EXTRACTING THIS TEXT!!!";
                            break;
                        }
                    }
                    Record record = new Record(comment.Id, comment.InnerText, commentText);
                    records.Add(record);
                }
            }
            else
            {
                return(records);
            }
            return(records);
        }
Example #12
0
        public void ReplaceInBookmark(BookmarkStart bookmarkStart, string text)
        {
            OpenXmlElement elem = bookmarkStart.NextSibling();

            while (elem != null && !(elem is BookmarkEnd))
            {
                OpenXmlElement nextElem = elem.NextSibling();
                elem.Remove();
                elem = nextElem;
            }
            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(text)), bookmarkStart);
        }
Example #13
0
        /// <summary>
        /// 在指定书签处插入文本
        /// </summary>
        /// <param name="bookmarkStart"></param>
        /// <param name="value"></param>
        private static void InsertIntoBookmark(BookmarkStart bookmarkStart, string value)
        {
            OpenXmlElement xmlElement = bookmarkStart.NextSibling();

            while (xmlElement != null && !(xmlElement is BookmarkEnd))
            {
                OpenXmlElement element = xmlElement.NextSibling();
                xmlElement.Remove();
                xmlElement = element;
            }
            bookmarkStart.Parent.InsertAfter <DocumentFormat.OpenXml.Wordprocessing.Run>
                (new Run(new DocumentFormat.OpenXml.Wordprocessing.Text(value)), bookmarkStart);
        }
Example #14
0
        private OpenXmlElement GetNextElement(List <OpenXmlElement> childNodes, OpenXmlElement node)
        {
            if (node.Parent != null)
            {
                return(node.NextSibling());
            }
            var index = childNodes.IndexOf(node);

            if (index == -1 || ++index >= childNodes.Count)
            {
                return(null);
            }
            return(childNodes[index]);
        }
Example #15
0
        // SetProperties (to enforce XSD Schema compliance)

        #region SetProperties

        /// <summary>
        /// Insert a style element inside a RunProperties, taking care of the correct sequence order as defined in the ECMA Standard.
        /// </summary>
        /// <param name="containerProperties">A RunProperties or ParagraphProperties wherein the tag will be inserted.</param>
        /// <param name="tag">The style to apply to the run.</param>
        protected void SetProperties(OpenXmlCompositeElement containerProperties, OpenXmlElement tag)
        {
            // This implementation is largely inspired by DocumentFormat.OpenXml.OpenXmlCompositeElement.SetElement which is internal.

            int tagOrder = GetTagOrder(tag);

            OpenXmlElement firstChild     = containerProperties.FirstChild;
            OpenXmlElement openXmlElement = null;
            Type           type           = tag.GetType();

            while (firstChild != null)
            {
                bool isKnownElement = (!(firstChild is OpenXmlUnknownElement) && !(firstChild is OpenXmlMiscNode));
                if (isKnownElement)
                {
                    int num = GetTagOrder(firstChild);

                    if (num != tagOrder)
                    {
                        if (num > tagOrder)
                        {
                            break;
                        }
                        openXmlElement = firstChild;
                    }
#if FEATURE_REFLECTION
                    else if (!type.IsInstanceOfType(tag))
#else
                    else if (!type.GetTypeInfo().IsAssignableFrom(tag.GetType().GetTypeInfo()))
#endif
                    {
                        openXmlElement = firstChild;
                    }
                    else
                    {
                        openXmlElement = firstChild.PreviousSibling();
                        containerProperties.RemoveChild <OpenXmlElement>(firstChild);
                        break;
                    }
                }

                firstChild = firstChild.NextSibling();
            }

            if (tag != null)
            {
                containerProperties.InsertAfter(tag, openXmlElement);
            }
        }
Example #16
0
        private void BookmarkReplace(WordprocessingDocument document, string bookmarkname, string value)
        {
            var bookmarkStartList = document.MainDocumentPart.Document.Descendants <BookmarkStart>();
            var bookmarkEndList   = document.MainDocumentPart.Document.Descendants <BookmarkEnd>();

            BookmarkStart bookmarkStart = null;
            BookmarkEnd   bookmarkEnd   = null;

            foreach (BookmarkStart temp in bookmarkStartList)//нужно переписать под Linq, но пока и так все работает
            {
                if (temp.Name == bookmarkname)
                {
                    bookmarkStart = temp;
                    break;
                }
            }

            if (bookmarkStart == null)
            {
                return;
            }

            foreach (BookmarkEnd temp in bookmarkEndList)
            {
                if (temp.Id.Value == bookmarkStart.Id.Value)
                {
                    bookmarkEnd = temp;
                    break;
                }
            }

            if (bookmarkEnd == null)
            {
                return;
            }

            OpenXmlElement elem = bookmarkStart.NextSibling();

            while (elem != null && !((elem is BookmarkEnd) && ((BookmarkEnd)elem == bookmarkEnd)))
            {
                OpenXmlElement nextElem = elem.NextSibling();
                elem.Remove();
                elem = nextElem;
            }

            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(value)), bookmarkStart);
        }
Example #17
0
        public static void InsertImageIntoBookmark(WordprocessingDocument doc, BookmarkStart bookmarkStart, string imageFilename)
        {
            // Remove anything present inside the bookmark
            OpenXmlElement elem = bookmarkStart.NextSibling();

            while (elem != null && !(elem is BookmarkEnd))
            {
                OpenXmlElement nextElem = elem.NextSibling();
                elem.Remove();
                elem = nextElem;
            }

            // Create an imagepart
            var imagePart = AddImagePart(doc.MainDocumentPart, imageFilename);

            // insert the image part after the bookmark start
            AddImageToBody(doc.MainDocumentPart.GetIdOfPart(imagePart), bookmarkStart);
        }
Example #18
0
        private static bool deleteElement(OpenXmlElement parentElement, OpenXmlElement elem, string id, bool seekParent)
        {
            bool found = false;

            //Loop until I find BookmarkEnd or null element
            while (!found && elem != null && (!(elem is BookmarkEnd) || (((BookmarkEnd)elem).Id.Value != id)))
            {
                if (elem.ChildElements != null && elem.ChildElements.Count > 0)
                {
                    found = deleteElement(elem, elem.FirstChild, id, false);
                }

                if (!found)
                {
                    OpenXmlElement nextElem = elem.NextSibling();
                    elem.Remove();
                    elem = nextElem;
                }
            }

            if (!found)
            {
                if (elem == null)
                {
                    if (!(parentElement is Body) && seekParent)
                    {
                        //Try to find bookmarkEnd in Sibling nodes
                        found = deleteElement(parentElement.Parent, parentElement.NextSibling(), id, true);
                    }
                }
                else
                {
                    if (elem is BookmarkEnd && ((BookmarkEnd)elem).Id.Value == id)
                    {
                        found = true;
                    }
                }
            }

            return(found);
        }
Example #19
0
        private static void CleanContentBetweenBookmarks(BookmarksPair bookmarksPair)
        {
            List <OpenXmlElement> elements = new List <OpenXmlElement>();
            OpenXmlElement        element  = bookmarksPair.Start.NextSibling();

            while (element != null)
            {
                if (element == bookmarksPair.End)
                {
                    break;
                }

                elements.Add(element);

                element = element.NextSibling();
            }

            foreach (var item in elements)
            {
                item.Remove();
            }
        }
Example #20
0
        private void MoveUp()
        {
            int            up     = 0;
            OpenXmlElement parent = State.CurrentElement;
            OpenXmlElement next   = null;

            while (up < _depth - 1 && next == null)
            {
                up++;
                parent = parent.Parent;
                next   = parent?.NextSibling();
            }

            if (next == null)
            {
                _done = true;
                return;
            }

            _depth              -= up;
            State.Index          = _textIndex[parent];
            State.CurrentVNode   = _vNode[next.PreviousSibling()];
            State.CurrentElement = next;
        }
Example #21
0
        private static void ConvertToFields(Paragraph para)
        {
            for (OpenXmlElement element = para.FirstChild; element != null; element = element.NextSibling())
            {
                Run run = element as Run;
                if (run == null)
                {
                    continue;
                }
                Text text = run.GetFirstChild <Text>();
                if ((!text.Text.Contains("<<")) || (!text.Text.Contains(">>")))
                {
                    continue;
                }

                // we will create new runs and insert them, then at the end remove this run
                int offset = 0;
                while (true)
                {
                    int start = text.Text.IndexOf("<<", offset);
                    if (start == -1)
                    {
                        break;
                    }
                    int end = text.Text.IndexOf(">>", start);
                    if (end == -1)
                    {
                        break;
                    }
                    // do we have text to add?
                    if (start > offset)
                    {
                        Run runText = (Run)run.CloneNode(true);
                        runText.GetFirstChild <Text>().Text = text.Text.Substring(offset, start - offset);
                        para.InsertBefore(runText, run);
                    }

                    string    field = text.Text.Substring(start + 2, end - start - 2).Trim();
                    FieldInfo info  = Converter.Parse(field);

                    // if we can't handle it, leave it alone
                    if (info.DoNotProcess)
                    {
                        Trap.trap();
                        logFile.WriteLine($"Not converting field {field}");
                        Run runText = (Run)run.CloneNode(true);
                        runText.GetFirstChild <Text>().Text = text.Text.Substring(offset, end + 2 - offset);
                        para.InsertBefore(runText, run);
                        offset = end + 2;
                        continue;
                    }

                    logFile.WriteLine($"Converting field {field} to tag {info.FullTagText}");

                    // add the data
                    if (info.NodeName != null && info.NodeName.Length > 0)
                    {
                        XmlElement root = stack.Peek().NodeOn;
                        foreach (string nodeOn in info.NodeName)
                        {
                            XmlElement item = root.ChildNodes.OfType <XmlElement>().Where(e => e.LocalName == nodeOn).FirstOrDefault();
                            if (item != null)
                            {
                                root = item;
                            }
                            else
                            {
                                XmlElement data = xmlDoc.CreateElement(nodeOn);
                                root.AppendChild(data);
                                root = data;
                            }
                        }

                        // need to push/pop on the stack
                        if (info.Mode == FieldInfo.STACK_MODE.PUSH)
                        {
                            stack.Push(new DataInfo(root, info.NodeName[0], info.VarName));
                        }
                    }
                    if (info.Mode == FieldInfo.STACK_MODE.POP)
                    {
                        stack.Pop();
                    }

                    // now add the field
                    Run runFieldBegin = new Run();
                    runFieldBegin.AppendChild(new FieldChar()
                    {
                        FieldCharType = FieldCharValues.Begin
                    });
                    para.InsertBefore(runFieldBegin, run);

                    Run       runFieldInstr = new Run();
                    FieldCode fieldCode     = new FieldCode()
                    {
                        Space = SpaceProcessingModeValues.Preserve
                    };
                    fieldCode.Text = $" AUTOTEXTLIST   \\t \"{info.FullTagText}\"  \\* MERGEFORMAT ";
                    runFieldInstr.AppendChild(fieldCode);
                    para.InsertAfter(runFieldInstr, runFieldBegin);

                    Run runFieldSeparate = new Run();
                    runFieldSeparate.AppendChild(new FieldChar()
                    {
                        FieldCharType = FieldCharValues.Separate
                    });
                    para.InsertAfter(runFieldSeparate, runFieldInstr);

                    Run  runDisplay  = new Run();
                    Text textDisplay = new Text(info.DisplayName);
                    runDisplay.AppendChild(textDisplay);
                    para.InsertAfter(runDisplay, runFieldSeparate);

                    Run runFieldEnd = new Run();
                    runFieldEnd.AppendChild(new FieldChar()
                    {
                        FieldCharType = FieldCharValues.End
                    });
                    para.InsertAfter(runFieldEnd, runDisplay);

                    offset = end + 2;
                }

                // set to the previous one (and then it will next on it)
                element = run.PreviousSibling() ?? para.FirstChild;

                // if nothing left, remove the run. If something left, reduce it to that.
                if (offset >= text.Text.Length)
                {
                    element = run.PreviousSibling();
                    run.Remove();
                    if (element == null)
                    {
                        element = para.FirstChild;
                    }
                }
                else
                {
                    text.Text = text.Text.Substring(offset);
                }
            }
        }
        /// <summary>
        /// Traversing siblings of the specified element using PreviousSibling, PreviousSibling &lt T &gt
        /// NextSibling, NextSibling&ltT&gt, 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);
            }
        }
        public List <TravelOrderDocumentItem> GenerateDocumentsFromData()
        {
            List <TravelOrderDocumentItem> travelOrderDocumentItems = new List <TravelOrderDocumentItem>();

            using (var mainDoc = WordprocessingDocument.Open(_documentTemplatePath, false))
            {
                foreach (var travelOrderDataItem in _travelOrderDataItems)
                {
                    var newDocumentPath = Path.Combine(_generatedDocumentsPath, _listId.ToString(), travelOrderDataItem.FileName);
                    Directory.CreateDirectory(Path.GetDirectoryName(newDocumentPath));
                    using var generatedDocument = WordprocessingDocument.Create(newDocumentPath, WordprocessingDocumentType.Document);
                    // copy parts from source document to new document
                    foreach (var part in mainDoc.Parts)
                    {
                        generatedDocument.AddPart(part.OpenXmlPart, part.RelationshipId);
                    }

                    IDictionary <String, BookmarkStart> bookmarkMap = new Dictionary <String, BookmarkStart>();

                    foreach (BookmarkStart bookmarkStart in generatedDocument.MainDocumentPart.RootElement.Descendants <BookmarkStart>())
                    {
                        bookmarkMap[bookmarkStart.Name] = bookmarkStart;
                    }

                    foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)
                    {
                        OpenXmlElement elem = bookmarkStart.NextSibling();

                        while (elem != null && !(elem is BookmarkEnd))
                        {
                            OpenXmlElement nextElem = elem.NextSibling();
                            elem.Remove();
                            elem = nextElem;
                        }

                        switch (bookmarkStart.Name.Value)
                        {
                        case "Zaposleni":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.Employee)), bookmarkStart);
                            break;

                        case "Skracenica":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.InitialsShorthand)), bookmarkStart);
                            break;

                        case "RedniBroj":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.OrderNumber)), bookmarkStart);
                            break;

                        case "RadnoMesto":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.Role)), bookmarkStart);
                            break;

                        case "Mesto":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.City)), bookmarkStart);
                            break;

                        case "DateStart":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.DateStart)), bookmarkStart);
                            break;

                        case "DateEnd":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.DateEnd)), bookmarkStart);
                            break;

                        case "DatePaid":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.DatePaid)), bookmarkStart);
                            break;

                        case "NumberOfDays":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.NumberOfDays)), bookmarkStart);
                            break;

                        case "AmountPerDay":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.AmountPerDay)), bookmarkStart);
                            break;

                        case "AmountSumForDays":
                            bookmarkStart.Parent.InsertAfter <Run>(new Run(new Text(travelOrderDataItem.AmountSumForDays)), bookmarkStart);
                            break;
                        }
                    }

                    var travelOrderDocumentItem = new TravelOrderDocumentItem
                    {
                        ListId = _listId,
                        Name   = travelOrderDataItem.FileName,
                        Path   = newDocumentPath
                    };

                    travelOrderDocumentItems.Add(travelOrderDocumentItem);
                }
            }

            return(travelOrderDocumentItems);
        }
 protected static void ClearBetweenElements(OpenXmlElement start, OpenXmlElement end)
 {
     while (start.NextSibling() != end && start.NextSibling() != end)
         start.NextSibling().Remove();
 }
Example #25
0
        public static bool deleteElement(OpenXmlElement parentElement, OpenXmlElement elem, string id, bool seekParent)
        {
            bool found = false;

            //Loop until I find BookmarkEnd or null element
            while (!found && elem != null && (!(elem is BookmarkEnd) || (((BookmarkEnd)elem).Id.Value != id)))
            {
                if (elem.ChildElements != null && elem.ChildElements.Count > 0)
                {
                    found = deleteElement(elem, elem.FirstChild, id, false);
                }

                if (!found)
                {
                    OpenXmlElement nextElem = elem.NextSibling();
                    elem.Remove();
                    elem = nextElem;
                }
            }

            if (!found)
            {
                if (elem == null)
                {
                    if (!(parentElement is Body) && seekParent)
                    {
                        //Try to find bookmarkEnd in Sibling nodes
                        found = deleteElement(parentElement.Parent, parentElement.NextSibling(), id, true);
                    }
                }
                else
                {
                    if (elem is BookmarkEnd && ((BookmarkEnd)elem).Id.Value == id)
                    {
                        found = true;
                    }
                }
            }

            return found;
        }
Example #26
0
        /// <summary>
        /// Coalesce to a single run per field. If << and >> are not in the same run after this, we ignore them.
        /// </summary>
        /// <param name="para">The para to coalesce</param>
        private static void CoalesceRuns(OpenXmlElement para)
        {
            Run runTextStart = null;

            for (OpenXmlElement element = para.FirstChild; element != null; element = element.NextSibling())
            {
                if (element is ProofError || element is BookmarkStart || element is BookmarkEnd)
                {
                    continue;
                }

                Run run = element as Run;
                if (run == null)
                {
                    Trap.trap(runTextStart == null && !(element is ParagraphProperties));
                    Trap.trap(runTextStart != null);
                    runTextStart = null;
                    continue;
                }

                Text text = run.GetFirstChild <Text>();
                if (text == null)
                {
                    Trap.trap();
                    continue;
                }

                // may be the start (or all) of one or more <<fields>>
                // may also be in runs outside of fields.
                if (runTextStart == null)
                {
                    runTextStart = GetTextStart(text);
                    continue;
                }

                // if at the end, we need to roll up to one
                int endField = text.Text.IndexOf(">>");
                if (endField == -1)
                {
                    continue;
                }

                StringBuilder  buf       = new StringBuilder();
                OpenXmlElement elemField = runTextStart;
                while (true)
                {
                    if (elemField is Run runOn)
                    {
                        buf.Append(runOn.GetFirstChild <Text>().Text);
                    }

                    bool           isFirst  = elemField == runTextStart;
                    bool           isLast   = elemField == element;
                    OpenXmlElement elemNext = elemField.NextSibling();
                    if (!isFirst)
                    {
                        elemField.Remove();
                    }
                    if (isLast)
                    {
                        break;
                    }
                    elemField = elemNext;
                }

                // the run we keep now has all the text that we combined
                Text textStart = runTextStart.GetFirstChild <Text>();
                textStart.Text = buf.ToString();

                // restart on this as it may be "<< ... >> ... <<"
                element      = runTextStart;
                runTextStart = GetTextStart(textStart);
                Trap.trap(runTextStart != null);
            }
        }