예제 #1
0
        /// <summary>
        /// Nodes list with background elements
        /// </summary>
        private XElement BackgroundElement()
        {
            XDocument mainDocument = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            XElement  result       = mainDocument.Descendants(ns + "background").FirstOrDefault();

            return(result);
        }
예제 #2
0
 /// <summary>
 /// XDocument containing Xml content of the styles part
 /// </summary>
 public XDocument GetStylesDocument()
 {
     if (parentDocument.Document.MainDocumentPart.StyleDefinitionsPart != null)
     {
         return(parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart.StyleDefinitionsPart));
     }
     else
     {
         return(null);
     }
 }
예제 #3
0
        /// <summary>
        /// Searches for a custom Xml part with a given name
        /// </summary>
        /// <param name="xmlPartName">Name of custom Xml part</param>
        /// <returns>XDocument with customXml part loaded</returns>
        public XDocument Find(string xmlPartName)
        {
            string partName      = "/" + xmlPartName;
            var    customXmlPart =
                parentDocument.Document.MainDocumentPart.CustomXmlParts.Where(
                    t => t.Uri.OriginalString.EndsWith(partName, System.StringComparison.OrdinalIgnoreCase)
                    ).FirstOrDefault();

            if (customXmlPart == null)
            {
                throw new ArgumentException("Part name '" + xmlPartName + "' not found.");
            }
            return(parentDocument.GetXDocument(customXmlPart));
        }
예제 #4
0
        /// <summary>
        /// Elements tagged as section properties
        /// </summary>
        /// <returns>IEnumerable&lt;XElement&gt; containing all the section properties elements found it in the document</returns>
        private IEnumerable <XElement> SectionPropertiesElements()
        {
            XDocument mainDocument         = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            IEnumerable <XElement> results =
                mainDocument
                .Descendants(ns + "p")
                .Elements(ns + "pPr")
                .Elements(ns + "sectPr");

            if (results.Count() == 0)
            {
                results = mainDocument.Root.Elements(ns + "body").Elements(ns + "sectPr");
            }
            return(results);
        }
예제 #5
0
        /// <summary>
        /// Gets the document structure related to watermark description
        /// </summary>
        /// <returns>Document structure related to watermark description</returns>
        public IEnumerable <XElement> GetWatermark()
        {
            //  to get the watermark text, we have to look inside the document
            //  get the default header reference and get the header reference id part
            XElement defaultHeaderReference = parentDocument.Headers.GetHeaderReference(HeaderType.Default);

            if (defaultHeaderReference != null)
            {
                string      headerReferenceId = defaultHeaderReference.Attribute(relationshipsns + "id").Value;
                OpenXmlPart headerPart        = parentDocument.Document.MainDocumentPart.GetPartById(headerReferenceId);
                if (headerPart != null)
                {
                    XDocument headerPartXml = parentDocument.GetXDocument(headerPart);
                    return(headerPartXml.Descendants(ns + "pict"));
                }
                else
                {
                    return(null);
                }
            }
            else
            {
                return(null);
            }
        }
예제 #6
0
        private IEnumerable <XElement> IndexReferences()
        {
            XDocument mainDocument         = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            IEnumerable <XElement> results =
                mainDocument
                .Descendants(ns + "p")
                .Elements(ns + "r")
                .Where(
                    r =>
                    r.Elements(ns + "instrText").Count() > 0 &&
                    r.ElementsBeforeSelf().Last().Element(ns + "instrText") != null &&
                    r.ElementsBeforeSelf().Last().Element(ns + "instrText").Value.EndsWith("\"") &&
                    r.ElementsAfterSelf().First().Element(ns + "instrText") != null &&
                    r.ElementsAfterSelf().First().Element(ns + "instrText").Value.StartsWith("\"")
                    );

            return(results);
        }
예제 #7
0
        /// <summary>
        /// Returns all reference tags from inside the main part of a wordprocessing document
        /// </summary>
        private IEnumerable <XElement> CommentReferences()
        {
            XDocument mainDocument     = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            XName     run              = ns + "r";
            XName     startRange       = ns + "commentRangeStart";
            XName     endRange         = ns + "commentRangeEnd";
            XName     commentReference = ns + "commentReference";

            IEnumerable <XElement> results =
                mainDocument.Descendants().Where(
                    tag =>
                    tag.Name == startRange ||
                    tag.Name == endRange ||
                    (tag.Name == run && tag.Descendants(commentReference).Count() > 0)
                    );

            return(results);
        }
예제 #8
0
        private IEnumerable <XElement> FigureTitleParagraphsElements()
        {
            XDocument mainDocument         = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            IEnumerable <XElement> results =
                mainDocument.Descendants().Where
                (
                    tag =>
                    tag.Name == ns + "p" &&
                    tag.Elements().Where
                    (
                        tag2 =>
                        tag2.Name == ns + "fldSimple" &&
                        tag2.Attribute(ns + "instr").Value.StartsWith(" SEQ Figure")
                    ).Count() > 0
                );

            return(results);
        }
예제 #9
0
        private IEnumerable <XElement> TOAReferences()
        {
            XDocument mainDocument         = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            IEnumerable <XElement> results =
                mainDocument.Descendants().Where
                (
                    tag =>
                    tag.Name == ns + "p" &&
                    tag.Descendants().Where
                    (
                        tag2 =>
                        tag2.Name == ns + "instrText" &&
                        (
                            tag2.Value.StartsWith(TOAFieldPrefix)
                        )
                    ).Count() > 0
                );

            return(results);
        }
예제 #10
0
        private IEnumerable <XElement> TitleParagraphsElements()
        {
            XDocument mainDocument         = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            IEnumerable <XElement> results =
                mainDocument.Descendants().Where
                (
                    tag =>
                    tag.Name == ns + "p" &&
                    tag.Descendants(ns + "t").Count() > 0 &&
                    tag.Descendants().Where
                    (
                        tag2 =>
                        tag2.Name == ns + "pStyle" &&
                        (
                            tag2.Attribute(ns + "val").Value == "Heading1" ||
                            tag2.Attribute(ns + "val").Value == "Heading2" ||
                            tag2.Attribute(ns + "val").Value == "Heading3"
                        )
                    ).Count() > 0
                );

            return(results);
        }
예제 #11
0
        /// <summary>
        /// Inserts Xml markup representing format attributes inside a specific paragraph or paragraph run
        /// </summary>
        /// <param name="document">Document to insert formatting Xml tags</param>
        /// <param name="xpathInsertionPoint">Paragraph or paragraph run to set format</param>
        /// <param name="content">Formatting tags</param>
        public void InsertFormat(PTWordprocessingDocument document, string xpathInsertionPoint, string content)
        {
            XDocument   xDocument       = parentDocument.GetXDocument(document.Document.MainDocumentPart);
            XmlDocument xmlMainDocument = OpenXmlDocument.LoadXmlDocumentFromXDocument(xDocument);

            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());

            namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

            XmlNodeList insertionPoints = xmlMainDocument.SelectNodes(xpathInsertionPoint, namespaceManager);

            if (insertionPoints.Count == 0)
            {
                throw new Exception("The xpath query did not return a valid location.");
            }

            foreach (XmlNode insertionPoint in insertionPoints)
            {
                XmlNode propertiesElement = insertionPoint.SelectSingleNode(@"w:pPr|w:rPr", namespaceManager);
                if (insertionPoint.Name == "w:p")
                {
                    // Checks if the rPr or pPr element exists
                    if (propertiesElement == null)
                    {
                        propertiesElement = xmlMainDocument.CreateElement("w", "pPr", namespaceManager.LookupNamespace("w"));
                        insertionPoint.PrependChild(propertiesElement);
                    }
                }
                else if (insertionPoint.Name == "w:r")
                {
                    // Checks if the rPr or pPr element exists
                    if (propertiesElement == null)
                    {
                        propertiesElement = xmlMainDocument.CreateElement("w", "rPr", namespaceManager.LookupNamespace("w"));
                        insertionPoint.PrependChild(propertiesElement);
                    }
                }

                if (propertiesElement != null)
                {
                    propertiesElement.InnerXml += content;
                }
                else
                {
                    throw new Exception("Specified xpath query result is not a valid location to place a formatting markup");
                }
            }
            OpenXmlDocument.SaveXmlDocumentIntoXDocument(xmlMainDocument, xDocument);
        }
예제 #12
0
        /// <summary>
        /// Nodes list with elements that need to be deleted
        /// </summary>
        private IEnumerable <XElement> ChangeTrackingElements()
        {
            XDocument mainDocument       = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            XName     del                = ns + "del";
            XName     moveFromRangeStart = ns + "moveFromRangeStart";
            XName     moveFrom           = ns + "moveFrom";
            XName     moveFromRangeEnd   = ns + "moveFromRangeEnd";
            XName     moveToRangeStart   = ns + "moveToRangeStart";
            XName     moveToRangeEnd     = ns + "moveToRangeEnd";

            IEnumerable <XElement> results =
                mainDocument.Descendants().Where(
                    tag =>
                    tag.Name == del ||
                    tag.Name == moveFromRangeStart ||
                    tag.Name == moveFrom ||
                    tag.Name == moveFromRangeEnd ||
                    tag.Name == moveToRangeStart ||
                    tag.Name == moveToRangeEnd
                    );

            return(results);
        }
예제 #13
0
        /// <summary>
        /// Insert a picture into a given xmlpath inside the document part
        /// </summary>
        /// <param name="xpathInsertionPoint">place where we are going to put the picture</param>
        /// <param name="pictureToInsert">picture to insert</param>
        /// <param name="name">name to use for inserted picture</param>
        public void Insert(string xpathInsertionPoint, Image pictureToInsert, string name)
        {
            XDocument           xmlMainDocument  = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            ImagePart           picturePart      = null;
            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(new NameTable());

            namespaceManager.AddNamespace("w", mainns.NamespaceName);
            IEnumerable <XElement> insertionPoints = xmlMainDocument.XPathSelectElements(xpathInsertionPoint, namespaceManager);

            //make the insertion for each insertion point specified in the xpath query
            foreach (XElement insertionPoint in insertionPoints)
            {
                if (picturePart == null)
                {
                    //  Create the picture part in the package
                    picturePart = parentDocument.Document.MainDocumentPart.AddImagePart(GetImagePartType(pictureToInsert.RawFormat));
                }

                //  the pictures in the main document part goes in a very long xml, wich specifies the way the picture
                //  has to be placed using drawingXml.
                insertionPoint.AddAfterSelf(
                    new XElement(mainns + "p",
                                 new XElement(mainns + "r",
                                              new XElement(mainns + "drawing",
                                                           new XElement(wordprocessingDrawingns + "inline",
                                                                        new XElement(wordprocessingDrawingns + "extent",
                                                                                     new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu),
                                                                                     new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu)
                                                                                     ),
                                                                        new XElement(wordprocessingDrawingns + "docPr",
                                                                                     new XAttribute("name", name),
                                                                                     new XAttribute("id", "1")
                                                                                     ),
                                                                        new XElement(drawingmlMainns + "graphic",
                                                                                     new XAttribute(XNamespace.Xmlns + "a", drawingmlMainns.NamespaceName),
                                                                                     new XElement(drawingmlMainns + "graphicData",
                                                                                                  new XAttribute("uri", picturens.NamespaceName),
                                                                                                  new XElement(picturens + "pic",
                                                                                                               new XAttribute(XNamespace.Xmlns + "pic", picturens.NamespaceName),
                                                                                                               new XElement(picturens + "nvPicPr",
                                                                                                                            new XElement(picturens + "cNvPr",
                                                                                                                                         new XAttribute("id", "0"),
                                                                                                                                         new XAttribute("name", name)
                                                                                                                                         ),
                                                                                                                            new XElement(picturens + "cNvPicPr")
                                                                                                                            ),
                                                                                                               new XElement(picturens + "blipFill",
                                                                                                                            new XElement(drawingmlMainns + "blip",
                                                                                                                                         new XAttribute(relationshipns + "embed", parentPart.GetIdOfPart(picturePart))
                                                                                                                                         ),
                                                                                                                            new XElement(drawingmlMainns + "stretch",
                                                                                                                                         new XElement(drawingmlMainns + "fillRect")
                                                                                                                                         )
                                                                                                                            ),
                                                                                                               new XElement(picturens + "spPr",
                                                                                                                            new XElement(drawingmlMainns + "xfrm",
                                                                                                                                         new XElement(drawingmlMainns + "off",
                                                                                                                                                      new XAttribute("x", "0"),
                                                                                                                                                      new XAttribute("y", "0")
                                                                                                                                                      ),
                                                                                                                                         new XElement(drawingmlMainns + "ext",
                                                                                                                                                      new XAttribute("cx", pictureToInsert.Width * pixelsPerEmu),
                                                                                                                                                      new XAttribute("cy", pictureToInsert.Height * pixelsPerEmu)
                                                                                                                                                      )
                                                                                                                                         ),
                                                                                                                            new XElement(drawingmlMainns + "prstGeom",
                                                                                                                                         new XAttribute("prst", "rect")
                                                                                                                                         )
                                                                                                                            )
                                                                                                               )
                                                                                                  )
                                                                                     )
                                                                        )
                                                           )
                                              )
                                 )
                    );
            }
            if (picturePart != null)
            {
                Stream partStream = picturePart.GetStream(FileMode.Create, FileAccess.ReadWrite);
                pictureToInsert.Save(partStream, pictureToInsert.RawFormat);
            }
            else
            {
                throw new Exception("The xpath query did not return a valid location.");
            }
        }
예제 #14
0
        /// <summary>
        /// Gets the document theme
        /// </summary>
        public Package GetTheme(string outputPath)
        {
            Package themePackage = null;
            // Loads the theme part main file
            ThemePart theme = parentDocument.Document.MainDocumentPart.ThemePart;

            if (theme != null)
            {
                XDocument themeDocument = parentDocument.GetXDocument(theme);

                // Creates the theme package (thmx file)
                themePackage = Package.Open(outputPath, FileMode.Create);

                // Creates the theme manager part on the new package and loads default content
                PackagePart newThemeManagerPart = themePackage.CreatePart(new Uri("/theme/theme/themeManager.xml", UriKind.RelativeOrAbsolute), "application/vnd.openxmlformats-officedocument.themeManager+xml");
                themePackage.CreateRelationship(newThemeManagerPart.Uri, TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/officeDocument");
                using (XmlWriter xWriter = XmlWriter.Create(newThemeManagerPart.GetStream(FileMode.Create, FileAccess.Write)))
                {
                    CreateEmptyThemeManager().WriteTo(xWriter);
                    xWriter.Flush();
                }

                // Creates the main theme part
                PackagePart newThemePart = themePackage.CreatePart(new Uri("/theme/theme/" + theme.Uri.OriginalString.Substring(theme.Uri.OriginalString.LastIndexOf('/') + 1), UriKind.RelativeOrAbsolute), theme.ContentType);
                newThemeManagerPart.CreateRelationship(newThemePart.Uri, TargetMode.Internal, theme.RelationshipType);

                // Gets embeded part references
                var embeddedItems =
                    themeDocument
                    .Descendants()
                    .Attributes(relationshipns + "embed");

                foreach (IdPartPair partId in theme.Parts)
                {
                    OpenXmlPart part = partId.OpenXmlPart;

                    // Creates the new media part inside the destination package
                    PackagePart         newPart      = themePackage.CreatePart(new Uri("/theme/media/" + part.Uri.OriginalString.Substring(part.Uri.OriginalString.LastIndexOf('/') + 1), UriKind.RelativeOrAbsolute), part.ContentType);
                    PackageRelationship relationship =
                        newThemePart.CreateRelationship(newPart.Uri, TargetMode.Internal, part.RelationshipType);

                    // Copies binary content from original part to destination part
                    Stream partStream    = part.GetStream(FileMode.Open, FileAccess.Read);
                    Stream newPartStream = newPart.GetStream(FileMode.Create, FileAccess.Write);
                    byte[] fileContent   = new byte[partStream.Length];
                    partStream.Read(fileContent, 0, (int)partStream.Length);
                    newPartStream.Write(fileContent, 0, (int)partStream.Length);
                    newPartStream.Flush();

                    // Replaces old embed part reference with the freshly created one
                    XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == theme.GetIdOfPart(part));
                    if (relationshipAttribute != null)
                    {
                        relationshipAttribute.Value = relationship.Id;
                    }
                }

                // Writes the updated theme XDocument into the destination package
                using (XmlWriter newThemeWriter = XmlWriter.Create(newThemePart.GetStream(FileMode.Create, FileAccess.Write)))
                    themeDocument.WriteTo(newThemeWriter);

                //themePackage.Flush();
                themePackage.Close();
            }
            return(themePackage);
        }
예제 #15
0
        /// <summary>
        /// Sets the style to a given location inside the document part
        /// </summary>
        /// <param name="xpathInsertionPoint">Document fragment to set style</param>
        /// <param name="styleValue">Name of style</param>
        /// <param name="stylesSourceFilePath">Styles library</param>
        public void InsertStyle(string xpathInsertionPoint, string styleValue, string stylesSourceFilePath)
        {
            XDocument   xDocument       = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart);
            XmlDocument xmlMainDocument = OpenXmlDocument.LoadXmlDocumentFromXDocument(xDocument);

            XmlNamespaceManager namespaceManager = new XmlNamespaceManager(xmlMainDocument.NameTable);

            namespaceManager.AddNamespace("w", "http://schemas.openxmlformats.org/wordprocessingml/2006/main");

            XmlNodeList insertionPoints = xmlMainDocument.SelectNodes(xpathInsertionPoint, namespaceManager);


            foreach (XmlNode insertionPoint in insertionPoints)
            {
                XmlElement xmlStyle = null;

                XmlNode propertiesElement = insertionPoint.SelectSingleNode(@"w:pPr|w:rPr", namespaceManager);
                if (insertionPoint.Name == "w:p")
                {
                    xmlStyle = xmlMainDocument.CreateElement("w", "pStyle", namespaceManager.LookupNamespace("w"));
                    xmlStyle.SetAttribute("val", namespaceManager.LookupNamespace("w"), styleValue + newStyleNameSuffix);

                    //  check if the rPr or pPr element exist, if so, then add the style xml element
                    //  inside, if not, then add a new rPr or pPr element
                    if (propertiesElement != null)
                    {
                        //  check if there is already a style node and remove it
                        XmlNodeList xmlStyleList = propertiesElement.SelectNodes("w:pStyle", namespaceManager);
                        for (int i = 0; i < xmlStyleList.Count; i++)
                        {
                            propertiesElement.RemoveChild(xmlStyleList[i]);
                        }
                        propertiesElement.PrependChild(xmlStyle);
                    }
                    else
                    {
                        propertiesElement = xmlMainDocument.CreateElement("w", "pPr", namespaceManager.LookupNamespace("w"));
                        propertiesElement.PrependChild(xmlStyle);
                        insertionPoint.PrependChild(propertiesElement);
                    }
                }

                if (insertionPoint.Name == "w:r")
                {
                    xmlStyle = xmlMainDocument.CreateElement("w", "rStyle", namespaceManager.LookupNamespace("w"));
                    xmlStyle.SetAttribute("val", namespaceManager.LookupNamespace("w"), styleValue + newStyleNameSuffix);
                    if (propertiesElement != null)
                    {
                        // check if there is already a style node and remove it
                        XmlNodeList xmlStyleList = propertiesElement.SelectNodes("w:rStyle", namespaceManager);
                        for (int i = 0; i < xmlStyleList.Count; i++)
                        {
                            propertiesElement.RemoveChild(xmlStyleList[i]);
                        }
                        propertiesElement.PrependChild(xmlStyle);
                    }
                    else
                    {
                        propertiesElement = xmlMainDocument.CreateElement("w", "rPr", namespaceManager.LookupNamespace("w"));
                        propertiesElement.PrependChild(xmlStyle);
                        insertionPoint.PrependChild(propertiesElement);
                    }
                }
            }

            OpenXmlDocument.SaveXmlDocumentIntoXDocument(xmlMainDocument, xDocument);

            //  Adds the style definition in the styles definitions part. The style definition need to be
            //  extracted from the given styles library file.
            Collection <XElement> styleHierarchy = GetStyleHierarchy(styleValue, stylesSourceFilePath);

            //  Opens the styles file in the document
            XDocument xmlStylesDefinitionDocument = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart.StyleDefinitionsPart);
            XDocument xElem = new XDocument();

            xElem.Add(xmlStylesDefinitionDocument.Root);

            //Inserts the new style
            foreach (XElement xmlStyleDefinition in styleHierarchy)
            {
                xElem.Root.Add(xmlStyleDefinition);
            }
            xmlStylesDefinitionDocument.Root.ReplaceWith(xElem.Root);
        }
예제 #16
0
        /// <summary>
        /// Nodes list with displayBackgroundShape elements
        /// </summary>
        public XElement DisplayBackgroundShapeElements()
        {
            XDocument settingsDocument = parentDocument.GetXDocument(parentDocument.Document.MainDocumentPart.DocumentSettingsPart);

            return(settingsDocument.Descendants(settingsns + "displayBackgroundShape").FirstOrDefault());
        }