示例#1
0
        public void LoadProcessContent()
        {
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.MCExecl))
                using (var doc = SpreadsheetDocument.Open(stream, false, settings))
                {
                    OpenXmlPart            target = doc.WorkbookPart.SharedStringTablePart;
                    OpenXmlPartRootElement root   = target.RootElement;
                    var si = root.FirstChild;
                    Assert.Empty(si.ExtendedAttributes);

                    Assert.Equal(3, si.ChildElements.Count);

                    var t    = si.FirstChild;
                    var attr = t.GetAttribute("a", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                    Assert.Equal("a", attr.Value);
                    attr = t.GetAttribute("b", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                    Assert.Equal("b", attr.Value);

                    Assert.Equal(2, t.ExtendedAttributes.Count());
                }
        }
示例#2
0
        public void LoadIgnorable()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.mcdoc, file);

            OpenXmlElement p1       = null;
            OpenSettings   settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;

                p1 = root.FirstChild.FirstChild;
                root.Save();
            }
            //should throw exception
            Assert.Throws <KeyNotFoundException>(() =>
            {
                p1.GetAttribute("editId", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
            });
            System.IO.File.Delete(file);
        }
示例#3
0
        public void LoadPreserveAttr()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.mcdoc, file);
            OpenSettings settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;
                var ppr = root.FirstChild.FirstChild.FirstChild;

                var attr = ppr.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("myattr", attr.Value);

                var space = ppr.FirstChild;
                attr = space.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("myattr", attr.Value);

                Assert.Equal(1, space.ExtendedAttributes.Count());

                var r = ppr.NextSibling();
                attr = r.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("myattr", attr.Value);
                Assert.Equal(1, r.ExtendedAttributes.Count());

                var rpr = r.FirstChild;
                attr = rpr.GetAttribute("myanotherAttr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                Assert.Equal("anotherattr", attr.Value);
                Assert.Equal(1, r.ExtendedAttributes.Count());
            }
            System.IO.File.Delete(file);
        }
示例#4
0
        /// <summary>
        /// Returns all block contained into the container given in argument.
        /// </summary>
        /// <param name="container">Container where the block items will be found.</param>
        /// <returns>All block contained into the container given in argument.</returns>
        protected override List <BlockItem> GetBlocks(OpenXmlPartContainer container)
        {
            OpenXmlPartRootElement rootContainer = GetRootContainer(container);
            var blocks = rootContainer.Descendants <SdtElement>()
                         .Select(_ => new BlockItem
            {
                OxpBlock  = _,
                XBlock    = XElement.Parse(_.OuterXml),
                Container = container
            })
                         .ToList();
            var addblocks = rootContainer.Descendants <DocProperties>()
                            .Where(_ => null != _.Description &&
                                   _.Description.HasValue &&
                                   !string.IsNullOrWhiteSpace(_.Description.Value) &&
                                   (_.Parent.Parent is Drawing || _.Parent.Parent is Table))
                            .Select(_ => new BlockItem
            {
                OxpBlock  = _.Parent.Parent,
                XBlock    = XElement.Parse(_.Parent.Parent.OuterXml),
                Container = container
            })
                            .ToList();;

            blocks.AddRange(addblocks);
            return(blocks);
        }
示例#5
0
        public void MCSave()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.mcdoc, file);

            //didn't process whole package ,should not process style part
            OpenSettings settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;
            }

            //open in full mode, style part still has MC
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;
                OpenXmlElement         p1     = null;
                p1 = root.FirstChild.FirstChild;
                //should throw exception
                var attrs = p1.GetAttributes();
                Assert.Equal(3, attrs.Count);

                target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                root   = target.RootElement;
                var rprDefault = root.FirstChild.FirstChild;
                Assert.Equal(2, rprDefault.GetAttributes().Count);
            }


            //process whole package ,should process style part

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;
            }

            //open in full mode, style part has no MC
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;

                OpenXmlElement p1 = null;
                p1 = root.FirstChild.FirstChild;
                Assert.Equal(3, p1.GetAttributes().Count);

                target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                root   = target.RootElement;
                var rprDefault = root.FirstChild.FirstChild;
                Assert.Equal(1, rprDefault.GetAttributes().Count);
            }
            System.IO.File.Delete(file);
        }
示例#6
0
        public void LoadProcessContent()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.MCExecl, file);
            OpenSettings settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (SpreadsheetDocument doc = SpreadsheetDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = doc.WorkbookPart.SharedStringTablePart;
                OpenXmlPartRootElement root   = target.RootElement;
                var si = root.FirstChild;
                Assert.Equal(0, si.ExtendedAttributes.Count());

                Assert.Equal(3, si.ChildElements.Count);

                var t    = si.FirstChild;
                var attr = t.GetAttribute("a", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("a", attr.Value);
                attr = t.GetAttribute("b", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("b", attr.Value);

                Assert.Equal(2, t.ExtendedAttributes.Count());
            }
            System.IO.File.Delete(file);
        }
示例#7
0
        public void GenerateAndAppendTemplate(MemoryStream template, IDictionary <string, string> values, int idx)
        {
            try
            {
                Logger.Info($"Filling template for row {idx}.");
                using (WordprocessingDocument templateDoc = WordprocessingDocument.Open(template, true))
                {
                    OpenXmlPartRootElement root = templateDoc.MainDocumentPart.RootElement;

                    // TODO: Set text here as well so Update Fields doesn't need to be run.
                    foreach (SimpleField field in root.Descendants <SimpleField>())
                    {
                        Logger.Info($"Handling SimpleField of instruction: {field.Instruction.Value}.");
                        var(newInstruction, oldKey, newPropName) = TransformFieldProperty(field.Instruction.Value, idx);
                        field.Instruction.Value = newInstruction;

                        string value = null;
                        if (!values.TryGetValue(oldKey, out value))
                        {
                            throw new DocumentWriterException($"No key found for {oldKey}");
                        }

                        if (string.IsNullOrWhiteSpace(value))
                        {
                            Logger.Warn($"An entry exists for key {oldKey}, but the resulting value is blank");
                        }

                        AddCustomProperty(newPropName, value);
                    }

                    // TODO: Make more robust... FieldCodes are far more complex than this.
                    // See the ECMA standard for 2.16.18.
                    foreach (FieldCode field in root.Descendants <FieldCode>())
                    {
                        Logger.Info($"Handling FieldCode of text: {field.Text}.");
                        var(newInstruction, oldKey, newPropName) = TransformFieldProperty(field.Text, idx);
                        field.Text = newInstruction;

                        if (!values.TryGetValue(oldKey, out string value))
                        {
                            throw new DocumentWriterException($"No key found for {oldKey}");
                        }

                        if (string.IsNullOrWhiteSpace(value))
                        {
                            Logger.Warn($"An entry exists for key {oldKey}, but the resulting value is blank.");
                        }

                        AddCustomProperty(newPropName, value);
                    }
                }

                sources.Add(new Source(new WmlDocument(template.Length.ToString(), template), true));
            }
            catch (Exception ex)
            {
                Logger.Fatal(ex, "An error occurred while filling template.");
                throw ex;
            }
        }
示例#8
0
        public void LoadPreserveAttr()
        {
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.Mcdoc))
                using (var testDocument = WordprocessingDocument.Open(stream, false, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                    var ppr = root.FirstChild.FirstChild.FirstChild;

                    var attr = ppr.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                    Assert.Equal("myattr", attr.Value);

                    var space = ppr.FirstChild;
                    attr = space.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                    Assert.Equal("myattr", attr.Value);

                    Assert.Single(space.ExtendedAttributes);

                    var r = ppr.NextSibling();
                    attr = r.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                    Assert.Equal("myattr", attr.Value);
                    Assert.Single(r.ExtendedAttributes);

                    var rpr = r.FirstChild;
                    attr = rpr.GetAttribute("myanotherAttr", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
                    Assert.Equal("anotherattr", attr.Value);
                    Assert.Single(r.ExtendedAttributes);
                }
        }
示例#9
0
        public void MCMustUnderstand()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.mcdoc, file);
            OpenSettings settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;
                root.FirstChild.MCAttributes = new MarkupCompatibilityAttributes();
                root.FirstChild.MCAttributes.MustUnderstand = "w14";
                var run       = root.FirstChild.FirstChild.FirstChild.NextSibling();
                var secondele = run.FirstChild.NextSibling();
                Assert.True(secondele is DocumentFormat.OpenXml.Wordprocessing.Picture);
            }

            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart target = testDocument.MainDocumentPart;
                //should throw exception here
                Assert.Throws <NamespaceNotUnderstandException>(() =>
                {
                    OpenXmlPartRootElement root = target.RootElement;
                });
            }
            System.IO.File.Delete(file);
        }
示例#10
0
        public void ParticalProperty()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.simpleSdt, file);
            OpenSettings settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;
                var           sdt             = root.FirstChild.FirstChild as SdtBlock;
                SdtProperties sdtpr           = sdt.SdtProperties;

                var alias = sdt.SdtProperties.FirstChild as SdtAlias;
                Assert.Equal("SDT1", alias.Val.Value);
                alias.Val.Value = "newsdt";
            }

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;
                var           sdt             = root.FirstChild.FirstChild as SdtBlock;
                SdtProperties sdtpr           = sdt.SdtProperties;

                var alias = sdt.SdtProperties.FirstChild as SdtAlias;
                Assert.Equal("newsdt", alias.Val.Value);
            }
            System.IO.File.Delete(file);
        }
示例#11
0
        /// <summary>
        /// Set the RootElement to be the given partRootElement.
        /// Only used for generated part classes which derive from this OpenXmlBasePart.
        /// </summary>
        /// <param name="partRootElement">The given partRootElement. Can be null.</param>
        /// <remarks>
        /// </remarks>
        /// <exception cref="ArgumentException">Thrown when the part's root element has already be associated with another OpenXmlPart.</exception>
        internal void SetDomTree(OpenXmlPartRootElement partRootElement)
        {
            Debug.Assert(partRootElement != null);

            //if (partRootElement == null)
            //{
            //    if (this.RootElement != null)
            //    {
            //        // clear the association from the previous root element.
            //        this.RootElement.OpenXmlPart = null;
            //    }

            //    this.RootElement = null;

            //    return;
            //}

            if (partRootElement.OpenXmlPart != null)
            {
                throw new ArgumentException(ExceptionMessages.PartRootAlreadyHasAssociation, "partRootElement");
            }

            partRootElement.OpenXmlPart = this;

            if (this._rootElement != null)
            {
                // clear the association from the previous root element.
                this._rootElement.OpenXmlPart = null;
            }

            this._rootElement = partRootElement;

            return;
        }
示例#12
0
        public void LoadIgnorable()
        {
            string file = "mcdoc.docx";

            CopyFileStream(TestFileStreams.mcdoc, file);

            //using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, false, DocumentFormat.OpenXml.MCMode.Full, false))
            //using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, false))
            //{
            //    OpenXmlPart target = testDocument.MainDocumentPart;
            //    OpenXmlPartRootElement root = target.RootElement;
            //    OpenXmlElement p = root.FirstChild.FirstChild;
            //    var attr = p.GetAttribute("editId", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
            //    Assert.Equal("w14", attr.Prefix);
            //}

            OpenXmlElement p1       = null;
            OpenSettings   settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;

                p1 = root.FirstChild.FirstChild;
                root.Save();
            }
            //should throw exception
            Assert.Throws <KeyNotFoundException>(() =>
            {
                p1.GetAttribute("editId", "http://schemas.microsoft.com/office/word/2008/9/12/wordml");
            });
            System.IO.File.Delete(file);
        }
示例#13
0
 public static void AddStylesNamespaceDeclarations(OpenXmlPartRootElement element)
 {
     element.AddNamespaceDeclaration("mc", mc);
     element.AddNamespaceDeclaration("r", r);
     element.AddNamespaceDeclaration("w", w);
     element.AddNamespaceDeclaration("w14", w14);
     element.AddNamespaceDeclaration("w15", w15);
     element.AddNamespaceDeclaration("w16se", w16se);
 }
示例#14
0
        static string ProcessDocxPart(OpenXmlPartRootElement part)
        {
            string s = "";

            foreach (var p in part.Descendants <Paragraph>())
            {
                s += p.InnerText + "\n";
            }
            return(s);
        }
示例#15
0
文件: OXmlDoc.cs 项目: 24/source_04
 private static void AddHeaderFooterNamespaceDeclaration(OpenXmlPartRootElement headerFooter)
 {
     headerFooter.AddNamespaceDeclaration("wpc", "http://schemas.microsoft.com/office/word/2010/wordprocessingCanvas");
     headerFooter.AddNamespaceDeclaration("mc", "http://schemas.openxmlformats.org/markup-compatibility/2006");
     headerFooter.AddNamespaceDeclaration("o", "urn:schemas-microsoft-com:office:office");
     headerFooter.AddNamespaceDeclaration("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");
     headerFooter.AddNamespaceDeclaration("m", "http://schemas.openxmlformats.org/officeDocument/2006/math");
     headerFooter.AddNamespaceDeclaration("v", "urn:schemas-microsoft-com:vml");
     headerFooter.AddNamespaceDeclaration("wp14", "http://schemas.microsoft.com/office/word/2010/wordprocessingDrawing");
     headerFooter.AddNamespaceDeclaration("wp", "http://schemas.openxmlformats.org/drawingml/2006/wordprocessingDrawing");
     headerFooter.AddNamespaceDeclaration("w10", "urn:schemas-microsoft-com:office:word");
     headerFooter.AddNamespaceDeclaration("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");
     headerFooter.AddNamespaceDeclaration("w14", "http://schemas.microsoft.com/office/word/2010/wordml");
     headerFooter.AddNamespaceDeclaration("wpg", "http://schemas.microsoft.com/office/word/2010/wordprocessingGroup");
     headerFooter.AddNamespaceDeclaration("wpi", "http://schemas.microsoft.com/office/word/2010/wordprocessingInk");
     headerFooter.AddNamespaceDeclaration("wne", "http://schemas.microsoft.com/office/word/2006/wordml");
     headerFooter.AddNamespaceDeclaration("wps", "http://schemas.microsoft.com/office/word/2010/wordprocessingShape");
 }
示例#16
0
        public void ExceptionForDuplicatedNsDeclarionWhenClosePackage()
        {
            var file = CopyTestFiles(@"ForTestCase", true, "Bug571679_Brownbag.pptx", f => f.IsPresentationFile())
                       .FirstOrDefault();

            Log.Comment("Opening file that contains duplicated namespace declarations...");
            Log.Comment("Part that contains duplciated namespace declarations /ppt/diagrams/data3.xml.");

            var result = file.CopyTo(Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".pptx"));

            using (var package = result.OpenPackage(true, true))
            {
                foreach (var part in package.DescendantParts().Where(p => p.IsReflectable()))
                {
                    OpenXmlPartRootElement dom = part.RootElement;
                }
            }
            Log.Pass("No exception thrown out during loading and saving this file.");
        }
示例#17
0
 public static void AddNamespaceDeclarations(OpenXmlPartRootElement element)
 {
     element.AddNamespaceDeclaration("m", m);
     element.AddNamespaceDeclaration("mc", mc);
     element.AddNamespaceDeclaration("o", o);
     element.AddNamespaceDeclaration("r", r);
     element.AddNamespaceDeclaration("v", v);
     element.AddNamespaceDeclaration("w", w);
     element.AddNamespaceDeclaration("w10", w10);
     element.AddNamespaceDeclaration("w14", w14);
     element.AddNamespaceDeclaration("w15", w15);
     element.AddNamespaceDeclaration("w16se", w16se);
     element.AddNamespaceDeclaration("wne", wne);
     element.AddNamespaceDeclaration("wp", wp);
     element.AddNamespaceDeclaration("wp14", wp14);
     element.AddNamespaceDeclaration("wpc", wpc);
     element.AddNamespaceDeclaration("wpg", wpg);
     element.AddNamespaceDeclaration("wpi", wpi);
     element.AddNamespaceDeclaration("wps", wps);
 }
示例#18
0
        public void LoadACB2()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.mcppt, file);
            OpenSettings settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (PresentationDocument doc = PresentationDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = doc.PresentationPart.TableStylesPart;
                OpenXmlPartRootElement root   = target.RootElement;

                var ele = root.FirstChild;
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);
                var attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("1", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele  = ele.NextSibling();
                attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("2", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele  = ele.NextSibling();
                attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("3", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele  = ele.NextSibling();
                attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                Assert.Equal("4", attr.Value);
                Assert.True(ele is DocumentFormat.OpenXml.Drawing.TableStyleEntry);

                ele = ele.NextSibling();
                Assert.Equal(null, ele);

                root.Save();
            }
            System.IO.File.Delete(file);
        }
示例#19
0
        public void LoadACB()
        {
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.Mcdoc, true))
                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;

                    var run       = root.FirstChild.FirstChild.FirstChild.NextSibling();
                    var secondele = run.FirstChild.NextSibling();

                    root.Save();

                    Assert.IsType <Picture>(secondele);
                }
        }
示例#20
0
        /// <summary>
        /// Set the RootElement to be the given partRootElement.
        /// Only used for generated part classes which derive from this OpenXmlBasePart.
        /// </summary>
        /// <param name="partRootElement">The given partRootElement. Can be null.</param>
        /// <remarks>
        /// </remarks>
        /// <exception cref="ArgumentException">Thrown when the part's root element has already be associated with another OpenXmlPart.</exception>
        internal void SetDomTree(OpenXmlPartRootElement partRootElement)
        {
            Debug.Assert(partRootElement != null);

            if (partRootElement.OpenXmlPart != null)
            {
                throw new ArgumentException(ExceptionMessages.PartRootAlreadyHasAssociation, nameof(partRootElement));
            }

            partRootElement.OpenXmlPart = this;

            if (InternalRootElement != null)
            {
                // clear the association from the previous root element.
                InternalRootElement.OpenXmlPart = null;
            }

            InternalRootElement = partRootElement;

            return;
        }
示例#21
0
        public void ParseDocxPart(OpenXmlPartRootElement doc, ExecuteArgs param)
        {
            var list = new List <Word.SdtElement>();

            Find <Word.SdtElement>(doc, list);
            foreach (var item in list)
            {
                OpenXmlElement stdContent = FindChildByName(item, "sdtContent");
                var            element    = stdContent.FirstChild;
                var            prop       = item.Descendants <Word.SdtProperties>().FirstOrDefault();
                var            temp       = prop.Descendants <Word.TemporarySdt>().FirstOrDefault();
                var            tag        = prop.Descendants <Word.Tag>().FirstOrDefault();
                if (tag == null)
                {
                    tag = stdContent.Descendants <Word.Tag>().FirstOrDefault();
                }

                if (tag != null)
                {
                    object val = ParseString(param, tag.Val.ToString());
                    if (val != null)
                    {
                        if (temp != null)
                        {
                            element.Remove();
                            item.Parent.ReplaceChild(element, item);
                        }
                        if (val is QResult)
                        {
                            FillTable(item, (QResult)val);
                        }
                        else
                        {
                            ReplaceString(element, val.ToString());
                        }
                    }
                }
            }
            doc.Save();
        }
示例#22
0
        public void LoadACB2()
        {
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.Mcppt))
                using (var doc = PresentationDocument.Open(stream, false, settings))
                {
                    OpenXmlPart            target = doc.PresentationPart.TableStylesPart;
                    OpenXmlPartRootElement root   = target.RootElement;

                    var ele = root.FirstChild;
                    Assert.IsType <Drawing.TableStyleEntry>(ele);
                    var attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                    Assert.Equal("1", attr.Value);
                    Assert.IsType <Drawing.TableStyleEntry>(ele);

                    ele  = ele.NextSibling();
                    attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                    Assert.Equal("2", attr.Value);
                    Assert.IsType <Drawing.TableStyleEntry>(ele);

                    ele  = ele.NextSibling();
                    attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                    Assert.Equal("3", attr.Value);
                    Assert.IsType <Drawing.TableStyleEntry>(ele);

                    ele  = ele.NextSibling();
                    attr = ele.GetAttribute("myattr", "http://schemas.microsoft.com/office/word/2008/9/16/wordprocessingDrawing");
                    Assert.Equal("4", attr.Value);
                    Assert.IsType <Drawing.TableStyleEntry>(ele);

                    ele = ele.NextSibling();
                    Assert.Null(ele);
                }
        }
示例#23
0
        public void MCMustUnderstand()
        {
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.Mcdoc, true))
            {
                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    var target = testDocument.MainDocumentPart;
                    var root   = target.RootElement;
                    root.FirstChild.MCAttributes = new MarkupCompatibilityAttributes
                    {
                        MustUnderstand = "w14",
                    };

                    var run       = root.FirstChild.FirstChild.FirstChild.NextSibling();
                    var secondele = run.FirstChild.NextSibling();

                    Assert.True(secondele is Picture);
                }

                stream.Position = 0;

                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart target = testDocument.MainDocumentPart;

                    // should throw exception here
                    Assert.Throws <NamespaceNotUnderstandException>(() =>
                    {
                        OpenXmlPartRootElement root = target.RootElement;
                    });
                }
            }
        }
示例#24
0
        public void LoadACB()
        {
            string file = System.IO.Path.Combine(TestUtil.TestResultsDirectory, Guid.NewGuid().ToString() + ".docx");

            CopyFileStream(TestFileStreams.mcdoc, file);

            OpenSettings settings = new OpenSettings();

            settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
            using (WordprocessingDocument testDocument = WordprocessingDocument.Open(file, true, settings))
            {
                OpenXmlPart            target = testDocument.MainDocumentPart;
                OpenXmlPartRootElement root   = target.RootElement;

                var run       = root.FirstChild.FirstChild.FirstChild.NextSibling();
                var secondele = run.FirstChild.NextSibling();

                root.Save();

                Assert.True(secondele is DocumentFormat.OpenXml.Wordprocessing.Picture);
            }
            System.IO.File.Delete(file);
        }
示例#25
0
        public void ParticalProperty()
        {
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.SimpleSdt, true))
            {
                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                    var           sdt             = root.FirstChild.FirstChild as SdtBlock;
                    SdtProperties sdtpr           = sdt.SdtProperties;

                    var alias = sdt.SdtProperties.FirstChild as SdtAlias;
                    Assert.Equal("SDT1", alias.Val.Value);
                    alias.Val.Value = "newsdt";
                }

                settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007);
                stream.Position = 0;

                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                    var           sdt             = root.FirstChild.FirstChild as SdtBlock;
                    SdtProperties sdtpr           = sdt.SdtProperties;

                    var alias = sdt.SdtProperties.FirstChild as SdtAlias;
                    Assert.Equal("newsdt", alias.Val.Value);
                }
            }
        }
        /// <summary>
        /// Bind the content controls (w:sdt elements) contained in the content part's XML document to the
        /// custom XML part identified by the given storeItemId.
        /// </summary>
        /// <param name="contentRootElement">The content part's <see cref="OpenXmlPartRootElement" />.</param>
        /// <param name="customXmlRootElement">The custom XML part's root <see cref="XElement" />.</param>
        /// <param name="storeItemId">The w:storeItemId to be used for data binding.</param>
        public static void BindContentControls(OpenXmlPartRootElement contentRootElement,
                                               XElement customXmlRootElement, string storeItemId)
        {
            if (contentRootElement == null)
            {
                throw new ArgumentNullException("contentRootElement");
            }
            if (customXmlRootElement == null)
            {
                throw new ArgumentNullException("customXmlRootElement");
            }
            if (storeItemId == null)
            {
                throw new ArgumentNullException("storeItemId");
            }

            // Get all w:sdt elements with matching tags.
            var tags = customXmlRootElement.Descendants()
                       .Where(e => !e.HasElements)
                       .Select(e => e.Name.LocalName);
            var sdts = contentRootElement.Descendants <SdtElement>()
                       .Where(sdt => sdt.SdtProperties.GetFirstChild <Tag>() != null &&
                              tags.Contains(sdt.SdtProperties.GetFirstChild <Tag>().Val.Value));

            foreach (var sdt in sdts)
            {
                // The tag value is supposed to point to a descendant element of the custom XML
                // part's root element.
                var childElementName = sdt.SdtProperties.GetFirstChild <Tag>().Val.Value;
                var leafElement      = customXmlRootElement.Descendants()
                                       .First(e => e.Name.LocalName == childElementName);

                // Define the list of path elements, using one of the following two options:
                // 1. The following statement is used as the basis for building the full path
                // expression (the same as built by Microsoft Word).
                var pathElements = leafElement.AncestorsAndSelf().Reverse().ToList();

                // 2. The following statement is used as the basis for building the short xPath
                // expression "//ns0:leafElement[1]".
                // List<XElement> pathElements = new List<XElement>() { leafElement };

                // Build list of namespace names for building the prefix mapping later on.
                var nsList = pathElements
                             .Where(e => e.Name.Namespace != XNamespace.None)
                             .Aggregate(new HashSet <string>(), (set, e) => set.Append(e.Name.NamespaceName))
                             .ToList();

                // Build mapping from local names to namespace indices.
                var nsDict = pathElements
                             .ToDictionary(e => e.Name.LocalName, e => nsList.IndexOf(e.Name.NamespaceName));

                // Build prefix mappings.
                var prefixMappings = nsList.Select((ns, index) => new { ns, index })
                                     .Aggregate(new StringBuilder(), (sb, t) =>
                                                sb.Append("xmlns:ns").Append(t.index).Append("='").Append(t.ns).Append("' "))
                                     .ToString().Trim();

                // Build xPath, assuming we will always take the first element and using one
                // of the following two options (see above):
                // 1. The following statement defines the prefix for building a full path
                // expression "/ns0:path[1]/ns0:to[1]/ns0:leafElement[1]".
                Func <string, string> prefix = localName =>
                                               nsDict[localName] >= 0 ? "/ns" + nsDict[localName] + ":" : "/";

                // 2. The following statement defines the prefix for building the short path
                // expression "//ns0:leafElement[1]".
                // Func<string, string> prefix = localName =>
                //     nsDict[localName] >= 0 ? "//ns" + nsDict[localName] + ":" : "//";

                var xPath = pathElements
                            .Select(e => prefix(e.Name.LocalName) + e.Name.LocalName + "[1]")
                            .Aggregate(new StringBuilder(), (sb, pc) => sb.Append(pc)).ToString();

                // Create and configure new data binding.
                var dataBinding = new DataBinding();
                if (!String.IsNullOrEmpty(prefixMappings))
                {
                    dataBinding.PrefixMappings = prefixMappings;
                }
                dataBinding.XPath       = xPath;
                dataBinding.StoreItemId = storeItemId;

                // Add or replace data binding.
                var currentDataBinding = sdt.SdtProperties.GetFirstChild <DataBinding>();
                if (currentDataBinding != null)
                {
                    sdt.SdtProperties.ReplaceChild(dataBinding, currentDataBinding);
                }
                else
                {
                    sdt.SdtProperties.Append(dataBinding);
                }
            }
        }
示例#27
0
        private void ConvertToTransitional(string fileName, byte[] tempByteArray)
        {
            Type type;

            try
            {
                type = GetDocumentType(tempByteArray);
            }
            catch (FileFormatException)
            {
                throw new PowerToolsDocumentException("Not an Open XML document.");
            }

            using (var ms = new MemoryStream())
            {
                ms.Write(tempByteArray, 0, tempByteArray.Length);
                if (type == typeof(WordprocessingDocument))
                {
                    using (WordprocessingDocument sDoc = WordprocessingDocument.Open(ms, true))
                    {
                        // following code forces the SDK to serialize
                        foreach (IdPartPair part in sDoc.Parts)
                        {
                            try
                            {
                                OpenXmlPartRootElement unused = part.OpenXmlPart.RootElement;
                            }
                            catch (Exception)
                            {
                                // Ignore
                            }
                        }
                    }
                }
                else if (type == typeof(SpreadsheetDocument))
                {
                    using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(ms, true))
                    {
                        // following code forces the SDK to serialize
                        foreach (IdPartPair part in sDoc.Parts)
                        {
                            try
                            {
                                OpenXmlPartRootElement unused = part.OpenXmlPart.RootElement;
                            }
                            catch (Exception)
                            {
                                // Ignore
                            }
                        }
                    }
                }
                else if (type == typeof(PresentationDocument))
                {
                    using (PresentationDocument sDoc = PresentationDocument.Open(ms, true))
                    {
                        // following code forces the SDK to serialize
                        foreach (IdPartPair part in sDoc.Parts)
                        {
                            try
                            {
                                OpenXmlPartRootElement unused = part.OpenXmlPart.RootElement;
                            }
                            catch (Exception)
                            {
                                // Ignore
                            }
                        }
                    }
                }

                FileName          = fileName;
                DocumentByteArray = ms.ToArray();
            }
        }
示例#28
0
        public void MCSave()
        {
            // Didn't process whole package, should not process style part
            var settings = new OpenSettings
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessLoadedPartsOnly, FileFormatVersions.Office2007),
            };

            using (var stream = GetStream(TestFiles.Mcdoc, true))
            {
                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                }

                stream.Position = 0;

                // Open in full mode, style part still has MC
                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                    OpenXmlElement         p1     = null;
                    p1 = root.FirstChild.FirstChild;

                    // should throw exception
                    var attrs = p1.GetAttributes();
                    Assert.Equal(3, attrs.Count);

                    target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                    root   = target.RootElement;
                    var rprDefault = root.FirstChild.FirstChild;
                    Assert.Equal(2, rprDefault.GetAttributes().Count);
                }

                stream.Position = 0;

                // Process whole package, should process style part
                settings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2007);
                using (var testDocument = WordprocessingDocument.Open(stream, true, settings))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;
                }

                stream.Position = 0;

                // Open in full mode, style part has no MC
                using (var testDocument = WordprocessingDocument.Open(stream, true))
                {
                    OpenXmlPart            target = testDocument.MainDocumentPart;
                    OpenXmlPartRootElement root   = target.RootElement;

                    OpenXmlElement p1 = null;
                    p1 = root.FirstChild.FirstChild;
                    Assert.Equal(3, p1.GetAttributes().Count);

                    target = testDocument.MainDocumentPart.StyleDefinitionsPart;
                    root   = target.RootElement;
                    var rprDefault = root.FirstChild.FirstChild;
                    Assert.Equal(1, rprDefault.GetAttributes().Count);
                }
            }
        }
示例#29
0
        private static WmlDocument PreProcessMarkup(WmlDocument source, int startingIdForFootnotesEndnotes)
        {
            // open and close to get rid of MC content
            using (var ms = new MemoryStream())
            {
                ms.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
                var os = new OpenSettings
                {
                    MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
                        MarkupCompatibilityProcessMode.ProcessAllParts,
                        FileFormatVersions.Office2007)
                };

                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true, os))
                {
                    OpenXmlPartRootElement unused = wDoc.MainDocumentPart.RootElement;
                    if (wDoc.MainDocumentPart.FootnotesPart != null)
                    {
                        // contrary to what you might think, looking at the API, it is necessary to access the root element of each part to cause
                        // the SDK to process MC markup.
                        OpenXmlPartRootElement unused1 = wDoc.MainDocumentPart.FootnotesPart.RootElement;
                    }

                    if (wDoc.MainDocumentPart.EndnotesPart != null)
                    {
                        OpenXmlPartRootElement unused1 = wDoc.MainDocumentPart.EndnotesPart.RootElement;
                    }
                }

                source = new WmlDocument(source.FileName, ms.ToArray());
            }

            // open and close to get rid of MC content
            using (var ms = new MemoryStream())
            {
                ms.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
                var os = new OpenSettings
                {
                    MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
                        MarkupCompatibilityProcessMode.ProcessAllParts,
                        FileFormatVersions.Office2007)
                };

                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true, os))
                {
                    TestForInvalidContent(wDoc);
                    RemoveExistingPowerToolsMarkup(wDoc);

                    // Removing content controls, field codes, and bookmarks is a no-no for many use cases.
                    // We need content controls, e.g., on the title page. Field codes are required for
                    // automatic cross-references, which require bookmarks.
                    // TODO: Revisit
                    var msSettings = new SimplifyMarkupSettings
                    {
                        RemoveBookmarks = true,

                        AcceptRevisions = false,
                        RemoveComments  = true,

                        RemoveContentControls = true,
                        RemoveFieldCodes      = true,

                        RemoveGoBackBookmark        = true,
                        RemoveLastRenderedPageBreak = true,
                        RemovePermissions           = true,
                        RemoveProof       = true,
                        RemoveSmartTags   = true,
                        RemoveSoftHyphens = true,
                        RemoveHyperlinks  = true
                    };
                    MarkupSimplifier.SimplifyMarkup(wDoc, msSettings);
                    ChangeFootnoteEndnoteReferencesToUniqueRange(wDoc, startingIdForFootnotesEndnotes);
                    AddUnidsToMarkupInContentParts(wDoc);
                    AddFootnotesEndnotesParts(wDoc);
                    FillInEmptyFootnotesEndnotes(wDoc);
                }

                return(new WmlDocument(source.FileName, ms.ToArray()));
            }
        }