Пример #1
0
        public void CanRemoveGoBackBookmarks()
        {
            XDocument partDocument = XDocument.Parse(GoBackBookmarkDocumentXmlString);

            Assert.Contains(partDocument
                            .Descendants(W.bookmarkStart)
                            , e => e.Attribute(W.name).Value == "_GoBack" && e.Attribute(W.id).Value == "0");
            Assert.Contains(partDocument
                            .Descendants(W.bookmarkEnd)
                            , e => e.Attribute(W.id).Value == "0");

            using (var stream = new MemoryStream())
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, DocumentType))
                {
                    MainDocumentPart part = wordDocument.AddMainDocumentPart();
                    part.PutXDocument(partDocument);

                    var settings = new SimplifyMarkupSettings {
                        RemoveGoBackBookmark = true
                    };
                    MarkupSimplifier.SimplifyMarkup(wordDocument, settings);

                    partDocument = part.GetXDocument();
                    Assert.False(partDocument.Descendants(W.bookmarkStart).Any());
                    Assert.False(partDocument.Descendants(W.bookmarkEnd).Any());
                }
        }
Пример #2
0
        public static void SetContent(WordprocessingDocument document, IEnumerable <XElement> contents)
        {
            MainDocumentPart mainDocumentPart = document.MainDocumentPart;

            if (mainDocumentPart == null)
            {
                mainDocumentPart = document.AddMainDocumentPart();
            }
            XDocument mainDocumentPartContentToInsert = new XDocument(
                new XElement(W.document,
                             new XAttribute(XNamespace.Xmlns + "w", W.w),
                             new XAttribute(XNamespace.Xmlns + "r", R.r),
                             new XElement(W.body, contents)));
            XDocument mainDocumentPartContent = mainDocumentPart.GetXDocument();

            if (mainDocumentPartContent.Root == null)
            {
                mainDocumentPartContent.Add(mainDocumentPartContentToInsert.Root);
            }
            else
            {
                mainDocumentPartContent.Root.ReplaceWith(mainDocumentPartContentToInsert.Root);
            }
            mainDocumentPart.PutXDocument();
        }
Пример #3
0
        public void CanRemoveContentControls()
        {
            XDocument partDocument = XDocument.Parse(SdtDocumentXmlString);

            Assert.True(partDocument.Descendants(W.sdt).Any());

            using (var stream = new MemoryStream())
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, DocumentType))
                {
                    MainDocumentPart part = wordDocument.AddMainDocumentPart();
                    part.PutXDocument(partDocument);

                    var settings = new SimplifyMarkupSettings {
                        RemoveContentControls = true
                    };
                    MarkupSimplifier.SimplifyMarkup(wordDocument, settings);

                    partDocument = part.GetXDocument();
                    XElement element = partDocument
                                       .Descendants(W.body)
                                       .Descendants()
                                       .First();

                    Assert.False(partDocument.Descendants(W.sdt).Any());
                    Assert.Equal(W.p, element.Name);
                }
        }
Пример #4
0
        public DocX AddToC(string title = null)
        {
            var tableOfContents = new TableOfContents(document);

            var lastParagraph = MainDocumentPart
                                .GetXDocument()
                                .Descendants(W.p)
                                .LastOrDefault();

            if (lastParagraph == null)
            {
                var xdoc = MainDocumentPart.GetXDocument();

                xdoc.Add(XElement.Parse(Body.OuterXml));
                MainDocumentPart.PutXDocument();

                lastParagraph = MainDocumentPart
                                .GetXDocument()
                                .Descendants(W.p)
                                .LastOrDefault();
            }

            tableOfContents.AddToc(lastParagraph, @"TOC \o '1-3' \h \z \u", title, null);

            return(this);
        }
Пример #5
0
        private static void ChangeFootnoteEndnoteReferencesToUniqueRange(
            WordprocessingDocument wDoc,
            int startingIdForFootnotesEndnotes)
        {
            MainDocumentPart mainDocPart   = wDoc.MainDocumentPart;
            FootnotesPart    footnotesPart = wDoc.MainDocumentPart.FootnotesPart;
            EndnotesPart     endnotesPart  = wDoc.MainDocumentPart.EndnotesPart;

            XElement document =
                mainDocPart.GetXDocument().Root ?? throw new OpenXmlPowerToolsException("Invalid document.");

            XElement footnotes = footnotesPart?.GetXDocument().Root;
            XElement endnotes  = endnotesPart?.GetXDocument().Root;

            IEnumerable <XElement> references = document
                                                .Descendants()
                                                .Where(d => d.Name == W.footnoteReference || d.Name == W.endnoteReference);

            foreach (XElement r in references)
            {
                var    oldId = (string)r.Attribute(W.id);
                string newId = startingIdForFootnotesEndnotes.ToString();
                startingIdForFootnotesEndnotes++;
                r.SetAttributeValue(W.id, newId);
                if (r.Name == W.footnoteReference)
                {
                    XElement fn = footnotes?
                                  .Elements()
                                  .FirstOrDefault(e => (string)e.Attribute(W.id) == oldId);

                    if (fn == null)
                    {
                        throw new OpenXmlPowerToolsException("Invalid document");
                    }

                    fn.SetAttributeValue(W.id, newId);
                }
                else
                {
                    XElement en = endnotes?
                                  .Elements()
                                  .FirstOrDefault(e => (string)e.Attribute(W.id) == oldId);

                    if (en == null)
                    {
                        throw new OpenXmlPowerToolsException("Invalid document");
                    }

                    en.SetAttributeValue(W.id, newId);
                }
            }

            mainDocPart.PutXDocument();
            footnotesPart?.PutXDocument();
            endnotesPart?.PutXDocument();
        }
        public void CanUseStronglyTypedBlockToDemarcateApis()
        {
            using (var stream = new MemoryStream())
            {
                CreateEmptyWordprocessingDocument(stream);

                using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
                {
                    MainDocumentPart part = wordDocument.MainDocumentPart;

                    // Add a paragraph through the PowerTools.
                    XDocument content     = part.GetXDocument();
                    XElement  bodyElement = content.Descendants(W.body).First();
                    bodyElement.Add(new XElement(W.p, new XElement(W.r, new XElement(W.t, "Added through PowerTools"))));
                    part.PutXDocument();

                    // This demonstrates the use of the StronglyTypedBlock in a using statement to
                    // demarcate the intermittent use of the strongly typed classes.
                    using (new StronglyTypedBlock(wordDocument))
                    {
                        // Assert that we can see the paragraph added through the PowerTools.
                        Body             body       = part.Document.Body;
                        List <Paragraph> paragraphs = body.Elements <Paragraph>().ToList();
                        Assert.Single(paragraphs);
                        Assert.Equal("Added through PowerTools", paragraphs[0].InnerText);

                        // Add a paragraph through the SDK.
                        body.AppendChild(new Paragraph(new Run(new Text("Added through SDK"))));
                    }

                    // Assert that we can see the paragraphs added through the PowerTools and the SDK.
                    content = part.GetXDocument();
                    List <XElement> paragraphElements = content.Descendants(W.p).ToList();
                    Assert.Equal(2, paragraphElements.Count);
                    Assert.Equal("Added through PowerTools", paragraphElements[0].Value);
                    Assert.Equal("Added through SDK", paragraphElements[1].Value);
                }
            }
        }
Пример #7
0
        public void MustEndPowerToolsBlockToUseStronglyTypedClasses()
        {
            using (var stream = new MemoryStream())
            {
                CreateEmptyWordprocessingDocument(stream);

                using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true))
                {
                    MainDocumentPart part = wordDocument.MainDocumentPart;

                    // Add a paragraph through the SDK.
                    Body body = part.Document.Body;
                    body.AppendChild(new Paragraph(new Run(new Text("Added through SDK"))));

                    // Begin the PowerTools Block, which saves any changes made through the strongly
                    // typed SDK classes to the parts of the WordprocessingDocument.
                    // In this case, this could also be done by invoking the Save method on the
                    // WordprocessingDocument, which will save all parts that had changes, or by
                    // invoking part.RootElement.Save() for the one part that was changed.
                    wordDocument.BeginPowerToolsBlock();

                    // Add a paragraph through the PowerTools.
                    XDocument content     = part.GetXDocument();
                    XElement  bodyElement = content.Descendants(W.body).First();
                    bodyElement.Add(new XElement(W.p, new XElement(W.r, new XElement(W.t, "Added through PowerTools"))));
                    part.PutXDocument();

                    // Get the part's content through the SDK. However, we will only see what we
                    // added through the SDK, not what we added through the PowerTools functionality.
                    body = part.Document.Body;
                    List <Paragraph> paragraphs = body.Elements <Paragraph>().ToList();
                    Assert.Equal(1, paragraphs.Count);
                    Assert.Equal("Added through SDK", paragraphs[0].InnerText);

                    // Now, let's end the PowerTools Block, which reloads the root element of this
                    // one part. Reloading those root elements this way is fine if you know exactly
                    // which parts had their content changed by the Open XML PowerTools.
                    wordDocument.EndPowerToolsBlock();

                    // Get the part's content through the SDK. Having reloaded the root element,
                    // we should now see both paragraphs.
                    body       = part.Document.Body;
                    paragraphs = body.Elements <Paragraph>().ToList();
                    Assert.Equal(2, paragraphs.Count);
                    Assert.Equal("Added through SDK", paragraphs[0].InnerText);
                    Assert.Equal("Added through PowerTools", paragraphs[1].InnerText);
                }
            }
        }
Пример #8
0
        /// <summary>
        /// Creates the custom XML from the existing content controls.
        /// </summary>
        /// <param name="mainPart">The main document part.</param>
        /// <returns>The custom XML as a <see cref="XDocument" />.</returns>
        private static XDocument CreateCustomXml(this MainDocumentPart mainPart)
        {
            XElement customXml =
                new XElement("root",
                             mainPart
                             .GetXDocument()
                             .Descendants(w + "sdt")
                             .Select(sdt =>
                                     new XElement(
                                         sdt.Element(w + "sdtPr")
                                         .Element(w + "tag")
                                         .Attribute(w + "val").Value,
                                         GetTextFromContentControl(sdt).Trim())
                                     )
                             );

            return(new XDocument(customXml));
        }
Пример #9
0
        public List <StringBuilder> getBody(XWPFDocument Document)
        {
            var allParas = new List <StringBuilder>();
            var bos      = Document.Paragraphs;

            Debug.WriteLine(doc);

            MainDocumentPart mdp  = doc.MainDocumentPart;
            XDocument        xDoc = mdp.GetXDocument();

            var paragraphs = xDoc.Descendants(W.p);

            List <string> allListItems = new List <string>();

            foreach (var para in paragraphs)
            {
                string listItem = string.Empty;

                try
                {
                    string paraText = para.Descendants(W.t).Select(t => (string)t).StringConcatenate();
                    listItem = ListItemRetriever.RetrieveListItem(doc, para, null);

                    Debug.WriteLine(listItem.Length);
                    allListItems.Add(listItem);
                }
                catch (Exception e)
                {
                    Debug.WriteLine("Spaces");
                }
            }

            allParas = this.getHeadings(bos, allListItems);

            Debug.WriteLine(allParas.Count);
            return(allParas);
        }
Пример #10
0
        public void CanRemoveSmartTags()
        {
            XDocument partDocument = XDocument.Parse(SmartTagDocumentXmlString);

            Assert.True(partDocument.Descendants(W.smartTag).Any());

            using (var stream = new MemoryStream())
                using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(stream, DocumentType))
                {
                    MainDocumentPart part = wordDocument.AddMainDocumentPart();
                    part.PutXDocument(partDocument);

                    var settings = new SimplifyMarkupSettings {
                        RemoveSmartTags = true
                    };
                    MarkupSimplifier.SimplifyMarkup(wordDocument, settings);

                    partDocument = part.GetXDocument();
                    XElement t = partDocument.Descendants(W.t).First();

                    Assert.False(partDocument.Descendants(W.smartTag).Any());
                    Assert.Equal(SmartTagDocumentTextValue, t.Value);
                }
        }
Пример #11
0
        public void MustBeginPowerToolsBlockToUsePowerTools()
        {
            using var stream = new MemoryStream();
            CreateEmptyWordprocessingDocument(stream);

            using WordprocessingDocument wordDocument = WordprocessingDocument.Open(stream, true);
            MainDocumentPart part = wordDocument.MainDocumentPart ?? throw new InvalidOperationException();

            // Add a first paragraph through the SDK.
            Body body = part.Document.Body ?? throw new InvalidOperationException();

            body.AppendChild(new Paragraph(new Run(new Text("First"))));

            // This demonstrates the usage of the BeginPowerToolsBlock method to
            // demarcate blocks or regions of code where the PowerTools are used
            // in between usages of the strongly typed classes.
            wordDocument.BeginPowerToolsBlock();

            // Get content through the PowerTools. We will see the one paragraph added
            // by using the strongly typed SDK classes.
            XDocument       content           = part.GetXDocument();
            List <XElement> paragraphElements = content.Descendants(W.p).ToList();

            Assert.Single(paragraphElements);
            Assert.Equal("First", paragraphElements[0].Value);

            // This demonstrates the usage of the EndPowerToolsBlock method to
            // demarcate blocks or regions of code where the PowerTools are used
            // in between usages of the strongly typed classes.
            wordDocument.EndPowerToolsBlock();

            // Add a second paragraph through the SDK in the exact same way as above.
            body = part.Document.Body ?? throw new InvalidOperationException();
            body.AppendChild(new Paragraph(new Run(new Text("Second"))));
            part.Document.Save();

            // Get content through the PowerTools in the exact same way as above,
            // noting that we have not used the BeginPowerToolsBlock method to
            // mark the beginning of the next PowerTools Block.
            // What we will see in this case is that we still only get the first
            // paragraph. This is caused by the GetXDocument method using the cached
            // XDocument, i.e., the annotation, rather reading the part's stream again.
            content           = part.GetXDocument();
            paragraphElements = content.Descendants(W.p).ToList();
            Assert.Single(paragraphElements);
            Assert.Equal("First", paragraphElements[0].Value);

            // To make the GetXDocument read the parts' streams, we need to begin
            // the next PowerTools Block. This will remove the annotations from the
            // parts and make the PowerTools read the part's stream instead of
            // using the outdated annotation.
            wordDocument.BeginPowerToolsBlock();

            // Get content through the PowerTools in the exact same way as above.
            // We should now see both paragraphs.
            content           = part.GetXDocument();
            paragraphElements = content.Descendants(W.p).ToList();
            Assert.Equal(2, paragraphElements.Count);
            Assert.Equal("First", paragraphElements[0].Value);
            Assert.Equal("Second", paragraphElements[1].Value);
        }