public static WmlDocument AddToc(WmlDocument document, string xPath, string switches, string title, int? rightTabPos)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
     {
         using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
         {
             AddToc(doc, xPath, switches, title, rightTabPos);
         }
         return streamDoc.GetModifiedWmlDocument();
     }
 }
        public WmlDocument(WmlDocument other, params XElement[] replacementParts)
            : base(other)
        {
            using (var streamDoc = new OpenXmlMemoryStreamDocument(this))
            {
                using (Package package = streamDoc.GetPackage())
                {
                    foreach (XElement replacementPart in replacementParts)
                    {
                        XAttribute uriAttribute = replacementPart.Attribute(PtOpenXml.Uri);
                        if (uriAttribute == null)
                        {
                            throw new OpenXmlPowerToolsException("Replacement part does not contain a Uri as an attribute");
                        }

                        string      uri  = uriAttribute.Value;
                        PackagePart part = package.GetParts().FirstOrDefault(p => p.Uri.ToString() == uri);
                        using (Stream partStream = part.GetStream(FileMode.Create, FileAccess.Write))
                            using (XmlWriter partXmlWriter = XmlWriter.Create(partStream))
                                replacementPart.Save(partXmlWriter);
                    }
                }

                DocumentByteArray = streamDoc.GetModifiedDocument().DocumentByteArray;
            }
        }
        /// <summary>
        /// Set a new header in a document
        /// </summary>
        /// <param name="header">XDocument containing the header to add in the document</param>
        /// <param name="type">The header part type</param>
        public static OpenXmlPowerToolsDocument SetHeader(WmlDocument doc, XDocument header, HeaderType type, int sectionIndex)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    //  Removes the reference in the document.xml and the header part if those already
                    //  exist
                    XElement headerReferenceElement = GetHeaderReference(document, type, sectionIndex);
                    if (headerReferenceElement != null)
                    {
                        GetHeaderPart(document, type, sectionIndex).RemovePart();
                        headerReferenceElement.Remove();
                    }

                    //  Add the new header
                    HeaderPart headerPart = document.MainDocumentPart.AddNewPart <HeaderPart>();
                    headerPart.PutXDocument(header);

                    //  Creates the relationship of the header inside the section properties in the document
                    string relID = document.MainDocumentPart.GetIdOfPart(headerPart);
                    AddHeaderReference(document, type, relID, sectionIndex);

                    // add in the settings part the EvendAndOddHeaders. this element
                    // allow to see the odd and even headers and headers in the document.
                    SettingAccessor.AddEvenAndOddHeadersElement(document);
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
        /// <summary>
        /// Sets the document theme
        /// </summary>
        /// <param name="theme">Theme package</param>
        public static OpenXmlPowerToolsDocument SetTheme(WmlDocument doc, OpenXmlPowerToolsDocument themeDoc)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    using (OpenXmlMemoryStreamDocument themeStream = new OpenXmlMemoryStreamDocument(themeDoc))
                        using (Package theme = themeStream.GetPackage())
                        {
                            // Gets the theme manager part
                            PackageRelationship themeManagerRelationship =
                                theme.GetRelationshipsByType(mainDocumentRelationshipType).FirstOrDefault();
                            if (themeManagerRelationship != null)
                            {
                                PackagePart themeManagerPart = theme.GetPart(themeManagerRelationship.TargetUri);

                                // Gets the theme main part
                                PackageRelationship themeRelationship =
                                    themeManagerPart.GetRelationshipsByType(themeRelationshipType).FirstOrDefault();
                                if (themeRelationship != null)
                                {
                                    PackagePart themePart        = theme.GetPart(themeRelationship.TargetUri);
                                    XDocument   newThemeDocument = XDocument.Load(XmlReader.Create(themePart.GetStream(FileMode.Open, FileAccess.Read)));

                                    // Removes existing theme part from document
                                    if (document.MainDocumentPart.ThemePart != null)
                                    {
                                        document.MainDocumentPart.DeletePart(document.MainDocumentPart.ThemePart);
                                    }

                                    // Creates a new theme part
                                    ThemePart documentThemePart = document.MainDocumentPart.AddNewPart <ThemePart>();

                                    var embeddedItems =
                                        newThemeDocument
                                        .Descendants()
                                        .Attributes(relationshipns + "embed");
                                    foreach (PackageRelationship imageRelationship in themePart.GetRelationships())
                                    {
                                        // Adds an image part to the theme part and stores contents inside
                                        PackagePart imagePart    = theme.GetPart(imageRelationship.TargetUri);
                                        ImagePart   newImagePart =
                                            documentThemePart.AddImagePart(GetImagePartType(imagePart.ContentType));
                                        newImagePart.FeedData(imagePart.GetStream(FileMode.Open, FileAccess.Read));

                                        // Updates relationship references into the theme XDocument
                                        XAttribute relationshipAttribute = embeddedItems.FirstOrDefault(e => e.Value == imageRelationship.Id);
                                        if (relationshipAttribute != null)
                                        {
                                            relationshipAttribute.Value = documentThemePart.GetIdOfPart(newImagePart);
                                        }
                                    }
                                    documentThemePart.PutXDocument(newThemeDocument);
                                }
                            }
                        }
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
 public Source(WmlDocument source, int start, int count, bool keepSections)
 {
     WmlDocument = source;
     Start = start;
     Count = count;
     KeepSections = keepSections;
 }
 public Source(WmlDocument source, int start, bool keepSections)
 {
     WmlDocument = source;
     Start = start;
     Count = Int32.MaxValue;
     KeepSections = keepSections;
 }
 public static object GetAllComments(WmlDocument doc, CommentFormat format)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
     {
         IEnumerable<XElement> comments = null;
         WordprocessingCommentsPart commentsPart = document.MainDocumentPart.WordprocessingCommentsPart;
         if (commentsPart != null)
         {
             XDocument commentsPartDocument = commentsPart.GetXDocument();
             comments = commentsPartDocument.Element(W.comments).Elements(W.comment);
         }
         if (comments != null)
         {
             XDocument commentsDocument =
                 new XDocument(
                     new XElement(W.comments,
                         new XAttribute(XNamespace.Xmlns + "w", W.w),
                         comments
                     )
                 );
             switch (format)
             {
                 case CommentFormat.PlainText:
                     return commentsDocument.ToString();
                 case CommentFormat.Xml:
                     return commentsDocument;
                 case CommentFormat.Docx:
                     return CreateCommentsDocument(comments);
             }
         }
         return null;
     }
 }
        private static void Main()
        {
            DateTime n      = DateTime.Now;
            var      tempDi = new DirectoryInfo(
                $"ExampleOutput-{n.Year - 2000:00}-{n.Month:00}-{n.Day:00}-{n.Hour:00}{n.Minute:00}{n.Second:00}");

            tempDi.Create();

            var templateDoc = new FileInfo("../../../TemplateDocument.docx");
            var dataFile    = new FileInfo("../../../Data.xml");

            var         wmlDoc          = new WmlDocument(templateDoc.FullName);
            XElement    data            = XElement.Load(dataFile.FullName);
            WmlDocument wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, data, out bool templateError);

            if (templateError)
            {
                Console.WriteLine("Errors in template.");
                Console.WriteLine("See AssembledDoc.docx to determine the errors in the template.");
            }

            var assembledDoc = new FileInfo(Path.Combine(tempDi.FullName, "AssembledDoc.docx"));

            wmlAssembledDoc.SaveAs(assembledDoc.FullName);
        }
예제 #9
0
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            WmlDocument originalWml = new WmlDocument("../../Original.docx");
            List <WmlRevisedDocumentInfo> revisedDocumentInfoList = new List <WmlRevisedDocumentInfo>()
            {
                new WmlRevisedDocumentInfo()
                {
                    RevisedDocument = new WmlDocument("../../RevisedByBob.docx"),
                    Revisor         = "Bob",
                    Color           = Color.LightBlue,
                },
                new WmlRevisedDocumentInfo()
                {
                    RevisedDocument = new WmlDocument("../../RevisedByMary.docx"),
                    Revisor         = "Mary",
                    Color           = Color.LightYellow,
                },
            };
            WmlComparerSettings settings        = new WmlComparerSettings();
            WmlDocument         consolidatedWml = WmlComparer.Consolidate(
                originalWml,
                revisedDocumentInfoList,
                settings);

            consolidatedWml.SaveAs(Path.Combine(tempDi.FullName, "Consolidated.docx"));
        }
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            FileInfo templateDoc = new FileInfo("../../TemplateDocument.docx");
            FileInfo dataFile    = new FileInfo("../../Data.xml");

            WmlDocument wmlDoc = new WmlDocument(templateDoc.FullName);
            XElement    data   = XElement.Load(dataFile.FullName);
            bool        templateError;
            WmlDocument wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, data, out templateError);

            if (templateError)
            {
                Console.WriteLine("Errors in template.");
                Console.WriteLine("See AssembledDoc.docx to determine the errors in the template.");
            }

            FileInfo assembledDoc = new FileInfo(Path.Combine(tempDi.FullName, "AssembledDoc.docx"));

            wmlAssembledDoc.SaveAs(assembledDoc.FullName);
        }
예제 #11
0
        /// <summary>
        /// Sets the document background color
        /// </summary>
        /// <param name="colorValue">String representation of the hexadecimal RGB color</param>
        public static OpenXmlPowerToolsDocument SetColor(WmlDocument doc, string colorValue)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    XDocument mainDocument = document.MainDocumentPart.GetXDocument();

                    // If the background element already exists, deletes it
                    XElement backgroundElement = BackgroundElement(document);
                    if (backgroundElement != null)
                    {
                        backgroundElement.Remove();
                    }

                    mainDocument.Root.AddFirst(
                        new XElement(ns + "background",
                                     new XAttribute(ns + "color", colorValue)
                                     )
                        );

                    // Enables background displaying by adding "displayBackgroundShape" tag
                    if (SettingAccessor.DisplayBackgroundShapeElements(document) == null)
                    {
                        SettingAccessor.AddBackgroundShapeElement(document);
                    }

                    document.MainDocumentPart.PutXDocument();
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
예제 #12
0
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            FileInfo templateDoc = new FileInfo("../../TemplateDocument.docx");
            FileInfo dataFile    = new FileInfo(Path.Combine(tempDi.FullName, "Data.xml"));

            // The following method generates a large data file with random data.
            // In a real world scenario, this is where you would query your data source and produce XML that will drive your document generation process.
            XElement data = GenerateDataFromDataSource(dataFile);

            WmlDocument wmlDoc = new WmlDocument(templateDoc.FullName);
            int         count  = 1;

            foreach (var customer in data.Elements("Customer"))
            {
                FileInfo assembledDoc = new FileInfo(Path.Combine(tempDi.FullName, string.Format("Letter-{0:0000}.docx", count++)));
                Console.WriteLine(assembledDoc.Name);
                bool        templateError;
                WmlDocument wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, customer, out templateError);
                if (templateError)
                {
                    Console.WriteLine("Errors in template.");
                    Console.WriteLine("See {0} to determine the errors in the template.", assembledDoc.Name);
                }
                wmlAssembledDoc.SaveAs(assembledDoc.FullName);
            }
        }
예제 #13
0
        static void mergeDocx(string paramOutputFile, List<FileStream> paramDocumentstreams)
        {
            var sources = new List<Source>();

            try
            {

                foreach (var stream in paramDocumentstreams)
                {
                    var tempms = new MemoryStream();
                    if (0 != stream.Length)
                    {
                        stream.CopyTo(tempms);
                        WmlDocument doc = new WmlDocument(stream.Length.ToString(), tempms);
                        sources.Add(new Source(doc, true));
                    }
                    tempms.Close();

                }

                Console.WriteLine("Merging documents...");
                var mergedDoc = DocumentBuilder.BuildDocument(sources);
                mergedDoc.SaveAs(paramOutputFile);

            }
            catch (Exception e)
            {
                Console.WriteLine("An Error ocurred while merging, please check the log: ");
                Console.WriteLine(e.ToString());
            }
        }
예제 #14
0
        static void Main(string[] args)
        {
            var n      = DateTime.Now;
            var tempDi = new DirectoryInfo(string.Format("ExampleOutput-{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}", n.Year - 2000, n.Month, n.Day, n.Hour, n.Minute, n.Second));

            tempDi.Create();

            WmlComparerSettings settings = new WmlComparerSettings();
            WmlDocument         result   = WmlComparer.Compare(
                new WmlDocument("../../Source1.docx"),
                new WmlDocument("../../Source2.docx"),
                settings);

            result.SaveAs(Path.Combine(tempDi.FullName, "Compared.docx"));

            var revisions = WmlComparer.GetRevisions(result, settings);

            foreach (var rev in revisions)
            {
                Console.WriteLine("Author: " + rev.Author);
                Console.WriteLine("Revision type: " + rev.RevisionType);
                Console.WriteLine("Revision text: " + rev.Text);
                Console.WriteLine();
            }
        }
        private static WmlDocument HashBlockLevelContent(
            WmlDocument source,
            WmlDocument sourceAfterProc,
            WmlComparerSettings settings)
        {
            using (var msSource = new MemoryStream())
                using (var msAfterProc = new MemoryStream())
                {
                    msSource.Write(source.DocumentByteArray, 0, source.DocumentByteArray.Length);
                    msAfterProc.Write(sourceAfterProc.DocumentByteArray, 0, sourceAfterProc.DocumentByteArray.Length);

                    using (WordprocessingDocument wDocSource = WordprocessingDocument.Open(msSource, true))
                        using (WordprocessingDocument wDocAfterProc = WordprocessingDocument.Open(msAfterProc, true))
                        {
                            // create Unid dictionary for source
                            XDocument sourceMainXDoc = wDocSource.MainDocumentPart.GetXDocument();
                            XElement  sourceMainRoot = sourceMainXDoc.Root ?? throw new ArgumentException();
                            Dictionary <string, XElement> sourceUnidDict = sourceMainRoot
                                                                           .Descendants()
                                                                           .Where(d => d.Name == W.p || d.Name == W.tbl || d.Name == W.tr)
                                                                           .ToDictionary(d => (string)d.Attribute(PtOpenXml.Unid));

                            XDocument afterProcMainXDoc = wDocAfterProc.MainDocumentPart.GetXDocument();
                            XElement  afterProcMainRoot = afterProcMainXDoc.Root ?? throw new ArgumentException();
                            IEnumerable <XElement> blockLevelElements = afterProcMainRoot
                                                                        .Descendants()
                                                                        .Where(d => d.Name == W.p || d.Name == W.tbl || d.Name == W.tr);

                            foreach (XElement blockLevelContent in blockLevelElements)
                            {
                                var cloneBlockLevelContentForHashing = (XElement)CloneBlockLevelContentForHashing(
                                    wDocAfterProc.MainDocumentPart,
                                    blockLevelContent,
                                    true,
                                    settings);

                                string shaString = cloneBlockLevelContentForHashing
                                                   .ToString(SaveOptions.DisableFormatting)
                                                   .Replace(" xmlns=\"http://schemas.openxmlformats.org/wordprocessingml/2006/main\"", "");

                                string sha1Hash = WmlComparerUtil.SHA1HashStringForUTF8String(shaString);
                                var    thisUnid = (string)blockLevelContent.Attribute(PtOpenXml.Unid);
                                if (thisUnid != null)
                                {
                                    if (sourceUnidDict.ContainsKey(thisUnid))
                                    {
                                        XElement correlatedBlockLevelContent = sourceUnidDict[thisUnid];
                                        correlatedBlockLevelContent.Add(new XAttribute(PtOpenXml.CorrelatedSHA1Hash, sha1Hash));
                                    }
                                }
                            }

                            wDocSource.MainDocumentPart.PutXDocument();
                        }

                    var sourceWithCorrelatedSHA1Hash = new WmlDocument(source.FileName, msSource.ToArray());
                    return(sourceWithCorrelatedSHA1Hash);
                }
        }
        /// <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 static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, string content)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    XDocument   xDocument       = document.MainDocumentPart.GetXDocument();
                    XmlDocument xmlMainDocument = new XmlDocument();
                    xmlMainDocument.Load(xDocument.CreateReader());

                    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 ArgumentException("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 ArgumentException("Specified xpath query result is not a valid location to place a formatting markup");
                        }
                    }
                    XDocument xNewDocument = new XDocument();
                    using (XmlWriter xWriter = xNewDocument.CreateWriter())
                        xmlMainDocument.WriteTo(xWriter);
                    document.MainDocumentPart.PutXDocument(xNewDocument);
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
예제 #17
0
 public Source(string fileName, string insertId)
 {
     WmlDocument = new WmlDocument(fileName);
     Start = 0;
     Count = Int32.MaxValue;
     KeepSections = false;
     InsertId = insertId;
 }
 public Source(WmlDocument source, int start, int count, string insertId)
 {
     WmlDocument = source;
     Start = start;
     Count = count;
     KeepSections = false;
     InsertId = insertId;
 }
예제 #19
0
 public static XDocument GetStylesDocument(WmlDocument doc)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             return(GetStylesDocument(document));
         }
 }
 public Source(string fileName, bool keepSections)
 {
     WmlDocument = new WmlDocument(fileName);
     Start = 0;
     Count = Int32.MaxValue;
     KeepSections = keepSections;
     InsertId = null;
 }
 public Source(WmlDocument source, int start, string insertId)
 {
     WmlDocument = source;
     Start = start;
     Count = Int32.MaxValue;
     KeepSections = false;
     InsertId = insertId;
 }
 private static void SaveDocumentIfDesired(WmlDocument source, string name, WmlComparerSettings settings)
 {
     if (SaveIntermediateFilesForDebugging && settings.DebugTempFileDi != null)
     {
         var fileInfo = new FileInfo(Path.Combine(settings.DebugTempFileDi.FullName, name));
         source.SaveAs(fileInfo.FullName);
     }
 }
 public Source(WmlDocument source, bool keepSections)
 {
     WmlDocument = source;
     Start = 0;
     Count = Int32.MaxValue;
     KeepSections = keepSections;
     InsertId = null;
 }
 public Source(WmlDocument source)
 {
     WmlDocument = source;
     Start = 0;
     Count = Int32.MaxValue;
     KeepSections = false;
     InsertId = null;
 }
        /// <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 static OpenXmlPowerToolsDocument Insert(WmlDocument doc, string xpathInsertionPoint, string content)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    XDocument xDocument = document.MainDocumentPart.GetXDocument();
                    XmlDocument xmlMainDocument = new XmlDocument();
                    xmlMainDocument.Load(xDocument.CreateReader());

                    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 ArgumentException("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 ArgumentException("Specified xpath query result is not a valid location to place a formatting markup");
                        }

                    }
                    XDocument xNewDocument = new XDocument();
                    using (XmlWriter xWriter = xNewDocument.CreateWriter())
                        xmlMainDocument.WriteTo(xWriter);
                    document.MainDocumentPart.PutXDocument(xNewDocument);
                }
                return streamDoc.GetModifiedDocument();
            }
        }
 public PtWordprocessingCommentsPart(WmlDocument wmlDocument, Uri uri, XName name, params object[] values)
     : base(name, values)
 {
     ParentWmlDocument = wmlDocument;
     this.Add(
         new XAttribute(PtOpenXml.Uri, uri),
         new XAttribute(XNamespace.Xmlns + "pt", PtOpenXml.pt)
     );
 }
        public void RA001_RevisionAccepter(string name)
        {
            FileInfo sourceDocx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name));

            WmlDocument notAccepted = new WmlDocument(sourceDocx.FullName);
            WmlDocument afterAccepting = RevisionAccepter.AcceptRevisions(notAccepted);
            var processedDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, sourceDocx.Name.Replace(".docx", "-processed-by-RevisionAccepter.docx")));
            afterAccepting.SaveAs(processedDestDocx.FullName);
        }
        public static IEnumerable <ValidationErrorInfo> GetOpenXmlValidationErrors(string fileName,
                                                                                   string officeVersion)
        {
#if !NET35
            FileFormatVersions fileFormatVersion = FileFormatVersions.Office2013;
#else
            FileFormatVersions fileFormatVersion = FileFormatVersions.Office2010;
#endif
            try
            {
                fileFormatVersion = (FileFormatVersions)Enum.Parse(fileFormatVersion.GetType(), officeVersion);
            }
            catch (Exception)
            {
#if !NET35
                fileFormatVersion = FileFormatVersions.Office2013;
#else
                fileFormatVersion = FileFormatVersions.Office2010;
#endif
            }

            FileInfo fi = new FileInfo(fileName);
            if (Util.IsWordprocessingML(fi.Extension))
            {
                WmlDocument wml = new WmlDocument(fileName);
                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(wml))
                    using (WordprocessingDocument wDoc = streamDoc.GetWordprocessingDocument())
                    {
                        OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
                        var errors = validator.Validate(wDoc);
                        return(errors.ToList());
                    }
            }
            else if (Util.IsSpreadsheetML(fi.Extension))
            {
                SmlDocument Sml = new SmlDocument(fileName);
                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Sml))
                    using (SpreadsheetDocument wDoc = streamDoc.GetSpreadsheetDocument())
                    {
                        OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
                        var errors = validator.Validate(wDoc);
                        return(errors.ToList());
                    }
            }
            else if (Util.IsPresentationML(fi.Extension))
            {
                PmlDocument Pml = new PmlDocument(fileName);
                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(Pml))
                    using (PresentationDocument wDoc = streamDoc.GetPresentationDocument())
                    {
                        OpenXmlValidator validator = new OpenXmlValidator(fileFormatVersion);
                        var errors = validator.Validate(wDoc);
                        return(errors.ToList());
                    }
            }
            return(Enumerable.Empty <ValidationErrorInfo>());
        }
 public static WmlDocument SimplifyMarkup(WmlDocument doc, SimplifyMarkupSettings settings)
 {
     using (var streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
             SimplifyMarkup(document, settings);
         return(streamDoc.GetModifiedWmlDocument());
     }
 }
 public PtMainDocumentPart(WmlDocument wmlDocument, Uri uri, XName name, params object[] values)
     : base(name, values)
 {
     _parentWmlDocument = wmlDocument;
     Add(
         new XAttribute(PtOpenXml.Uri, uri),
         new XAttribute(XNamespace.Xmlns + "pt", PtOpenXml.pt)
         );
 }
 /// <summary>
 /// Removes the specified header in the document
 /// </summary>
 /// <param name="type">The header part type</param>
 public void RemoveHeader(WmlDocument doc, HeaderType type, int sectionIndex)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             OpenXmlPart headerPart = GetHeaderPart(document, type, sectionIndex);
             headerPart.RemovePart();
         }
 }
예제 #32
0
 public PtWordprocessingCommentsPart(WmlDocument wmlDocument, Uri uri, XName name, params object[] values)
     : base(name, values)
 {
     ParentWmlDocument = wmlDocument;
     this.Add(
         new XAttribute(PtOpenXml.Uri, uri),
         new XAttribute(XNamespace.Xmlns + "pt", PtOpenXml.pt)
         );
 }
예제 #33
0
 public static string GetBackgroundColor(WmlDocument doc)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             XDocument mainDocument      = document.MainDocumentPart.GetXDocument();
             XElement  backgroundElement = mainDocument.Descendants(W.background).FirstOrDefault();
             return((backgroundElement == null) ? string.Empty : backgroundElement.Attribute(W.color).Value);
         }
 }
예제 #34
0
 public static XElement ConvertToHtml(WmlDocument doc, HtmlConverterSettings htmlConverterSettings)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             return(ConvertToHtml(document, htmlConverterSettings));
         }
     }
 }
 public static string GetBackgroundColor(WmlDocument doc)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
     {
         XDocument mainDocument = document.MainDocumentPart.GetXDocument();
         XElement backgroundElement = mainDocument.Descendants(W.background).FirstOrDefault();
         return (backgroundElement == null) ? string.Empty : backgroundElement.Attribute(W.color).Value;
     }
 }
예제 #36
0
 public static XElement ConvertToHtml(WmlDocument doc, HtmlConverterSettings htmlConverterSettings, Func <ImageInfo, XElement> imageHandler)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             return(ConvertToHtml(document, htmlConverterSettings, imageHandler));
         }
     }
 }
 public static XElement ConvertToHtml(WmlDocument doc, HtmlConverterSettings htmlConverterSettings, Func<ImageInfo, XElement> imageHandler)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             return ConvertToHtml(document, htmlConverterSettings, imageHandler);
         }
     }
 }
 public static XElement ConvertToHtml(WmlDocument doc, HtmlConverterSettings htmlConverterSettings)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             return ConvertToHtml(document, htmlConverterSettings);
         }
     }
 }
예제 #39
0
 public static WmlDocument AcceptRevisions(WmlDocument document)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
     {
         using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
         {
             AcceptRevisions(doc);
         }
         return(streamDoc.GetModifiedWmlDocument());
     }
 }
 /// <summary>
 /// Get the specified footer from the document
 /// </summary>
 /// <param name="type">The footer part type</param>
 /// <returns>the XDocument containing the footer</returns>
 public static XDocument GetFooter(WmlDocument doc, FooterType type, int sectionIndex)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
     {
         OpenXmlPart footer = GetFooterPart(document, type, sectionIndex);
         if (footer != null)
             return footer.GetXDocument();
         return null;
     }
 }
        private static void SaveCleanedDocuments(WmlDocument source1, WmlDocument producedDocument, WmlComparerSettings settings)
        {
            if (SaveIntermediateFilesForDebugging && settings.DebugTempFileDi != null)
            {
                WmlDocument cleanedSource = CleanPowerToolsAndRsid(source1);
                SaveDocumentIfDesired(cleanedSource, "Cleaned-Source.docx", settings);

                WmlDocument cleanedProduced = CleanPowerToolsAndRsid(producedDocument);
                SaveDocumentIfDesired(cleanedProduced, "Cleaned-Produced.docx", settings);
            }
        }
예제 #42
0
 public static WmlDocument AcceptRevisions(WmlDocument document)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
     {
         using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
         {
             AcceptRevisions(doc);
         }
         return streamDoc.GetModifiedWmlDocument();
     }
 }
 public static string RetrieveListItem(WmlDocument document,
                                       XElement paragraph, string bulletReplacementString)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
     {
         using (WordprocessingDocument wdoc = streamDoc.GetWordprocessingDocument())
         {
             return(RetrieveListItem(wdoc, paragraph, bulletReplacementString));
         }
     }
 }
 public static WmlDocument SearchAndReplace(WmlDocument doc, string search, string replace, bool matchCase)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             SearchAndReplace(document, search, replace, matchCase);
         }
         return streamDoc.GetModifiedWmlDocument();
     }
 }
 public static WmlDocument AssembleFormatting(WmlDocument document, FormattingAssemblerSettings settings)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
     {
         using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
         {
             AssembleFormatting(doc, settings);
         }
         return streamDoc.GetModifiedWmlDocument();
     }
 }
예제 #46
0
 public static WmlDocument AddToc(WmlDocument document, string xPath, string switches, string title, int?rightTabPos)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
     {
         using (WordprocessingDocument doc = streamDoc.GetWordprocessingDocument())
         {
             AddToc(doc, xPath, switches, title, rightTabPos);
         }
         return(streamDoc.GetModifiedWmlDocument());
     }
 }
예제 #47
0
 public static WmlDocument SearchAndReplace(WmlDocument doc, string search, string replace, bool matchCase)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             SearchAndReplace(document, search, replace, matchCase);
         }
         return(streamDoc.GetModifiedWmlDocument());
     }
 }
 public static WmlDocument SimplifyMarkup(WmlDocument doc, SimplifyMarkupSettings settings)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             SimplifyMarkup(document, settings);
         }
         return streamDoc.GetModifiedWmlDocument();
     }
 }
 public static string RetrieveListItem(WmlDocument document,
     XElement paragraph, string bulletReplacementString)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(document))
     {
         using (WordprocessingDocument wdoc = streamDoc.GetWordprocessingDocument())
         {
             return RetrieveListItem(wdoc, paragraph, bulletReplacementString);
         }
     }
 }
예제 #50
0
 public static WmlDocument ConvertHtmlToWml(
     string defaultCss,
     string authorCss,
     string userCss,
     XElement xhtml,
     HtmlToWmlConverterSettings settings,
     WmlDocument emptyDocument,
     string annotatedHtmlDumpFileName)
 {
     return(HtmlToWmlConverterCore.ConvertHtmlToWml(defaultCss, authorCss, userCss, xhtml, settings, emptyDocument, annotatedHtmlDumpFileName));
 }
예제 #51
0
        /// <summary>
        /// Sets the document background image
        /// </summary>
        /// <param name="imagePath">Path of the background image</param>
        public static OpenXmlPowerToolsDocument SetImage(WmlDocument doc, string imagePath)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    XDocument mainDocument = document.MainDocumentPart.GetXDocument();

                    // Adds the image to the package
                    ImagePart imagePart   = document.MainDocumentPart.AddImagePart(ImagePartType.Bmp);
                    Stream    imageStream = new StreamReader(imagePath).BaseStream;
                    byte[]    imageBytes  = new byte[imageStream.Length];
                    imageStream.Read(imageBytes, 0, imageBytes.Length);
                    imagePart.GetStream().Write(imageBytes, 0, imageBytes.Length);

                    // Creates a "background" element relating the image and the document

                    // If the background element already exists, deletes it
                    XElement backgroundElement = BackgroundElement(document);
                    if (backgroundElement != null)
                    {
                        backgroundElement.Remove();
                    }

                    // Background element construction
                    mainDocument.Root.Add(
                        new XElement(ns + "background",
                                     new XAttribute(ns + "color", defaultBackgroundColor),
                                     new XElement(vmlns + "background",
                                                  new XAttribute(vmlns + "id", defaultVmlBackgroundImageId),
                                                  new XAttribute(officens + "bwmode", defaultBWMode),
                                                  new XAttribute(officens + "targetscreensize", defaultTargetScreenSize),
                                                  new XElement(vmlns + "fill",
                                                               new XAttribute(relationshipsns + "id", document.MainDocumentPart.GetIdOfPart(imagePart)),
                                                               new XAttribute("recolor", defaultImageRecolor),
                                                               new XAttribute("type", defaultImageType)
                                                               )
                                                  )
                                     )
                        );


                    // Enables background displaying by adding "displayBackgroundShape" tag
                    if (SettingAccessor.DisplayBackgroundShapeElements(document) == null)
                    {
                        SettingAccessor.AddBackgroundShapeElement(document);
                    }

                    document.MainDocumentPart.PutXDocument();
                }
                return(streamDoc.GetModifiedDocument());
            }
        }
 /// <summary>
 /// Get the specified header from the document
 /// </summary>
 /// <param name="type">The header part type</param>
 /// <returns>A XDocument containing the header</returns>
 public static XDocument GetHeader(WmlDocument doc, HeaderType type, int sectionIndex)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
         using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
         {
             OpenXmlPart header = GetHeaderPart(document, type, sectionIndex);
             if (header != null)
             {
                 return(header.GetXDocument());
             }
             return(null);
         }
 }
 /// <summary>
 /// Gets the text related to watermark from a document
 /// </summary>
 /// <returns>Watermark text</returns>
 public static string GetWatermarkText(WmlDocument doc)
 {
     IEnumerable<XElement> watermarkDescription = GetWatermark(doc);
     if (watermarkDescription != null)
         return
             watermarkDescription
             .Descendants(vmlns + "shape")
             .Descendants(vmlns + "textpath")
             .First()
             .Attribute("string")
             .Value;
     else
         return string.Empty;
 }
        public static DocxMetrics GetDocxMetrics(string fileName)
        {
            WmlDocument           wmlDoc   = new WmlDocument(fileName);
            MetricsGetterSettings settings = new MetricsGetterSettings();

            settings.IncludeTextInContentControls = false;
            settings.IncludeXlsxTableCellData     = false;
            var         metricsXml = MetricsGetter.GetDocxMetrics(wmlDoc, settings);
            DocxMetrics metrics    = new DocxMetrics();

            metrics.FileName = wmlDoc.FileName;

            metrics.StyleHierarchy      = GetXmlDocumentForMetrics(metricsXml, H.StyleHierarchy);
            metrics.ContentControls     = GetXmlDocumentForMetrics(metricsXml, H.Parts);
            metrics.TextBox             = GetIntForMetrics(metricsXml, H.TextBox);
            metrics.ContentControlCount = GetIntForMetrics(metricsXml, H.ContentControl);
            metrics.ComplexField        = GetIntForMetrics(metricsXml, H.ComplexField);
            metrics.SimpleField         = GetIntForMetrics(metricsXml, H.SimpleField);
            metrics.AltChunk            = GetIntForMetrics(metricsXml, H.AltChunk);
            metrics.Table                  = GetIntForMetrics(metricsXml, H.Table);
            metrics.Hyperlink              = GetIntForMetrics(metricsXml, H.Hyperlink);
            metrics.LegacyFrame            = GetIntForMetrics(metricsXml, H.LegacyFrame);
            metrics.ActiveX                = GetIntForMetrics(metricsXml, H.ActiveX);
            metrics.SubDocument            = GetIntForMetrics(metricsXml, H.SubDocument);
            metrics.ReferenceToNullImage   = GetIntForMetrics(metricsXml, H.ReferenceToNullImage);
            metrics.ElementCount           = GetIntForMetrics(metricsXml, H.ElementCount);
            metrics.AverageParagraphLength = GetIntForMetrics(metricsXml, H.AverageParagraphLength);
            metrics.RunCount               = GetIntForMetrics(metricsXml, H.RunCount);
            metrics.ZeroLengthText         = GetIntForMetrics(metricsXml, H.ZeroLengthText);
            metrics.MultiFontRun           = GetIntForMetrics(metricsXml, H.MultiFontRun);
            metrics.AsciiCharCount         = GetIntForMetrics(metricsXml, H.AsciiCharCount);
            metrics.CSCharCount            = GetIntForMetrics(metricsXml, H.CSCharCount);
            metrics.EastAsiaCharCount      = GetIntForMetrics(metricsXml, H.EastAsiaCharCount);
            metrics.HAnsiCharCount         = GetIntForMetrics(metricsXml, H.HAnsiCharCount);
            metrics.AsciiRunCount          = GetIntForMetrics(metricsXml, H.AsciiRunCount);
            metrics.CSRunCount             = GetIntForMetrics(metricsXml, H.CSRunCount);
            metrics.EastAsiaRunCount       = GetIntForMetrics(metricsXml, H.EastAsiaRunCount);
            metrics.HAnsiRunCount          = GetIntForMetrics(metricsXml, H.HAnsiRunCount);
            metrics.RevisionTracking       = GetBoolForMetrics(metricsXml, H.RevisionTracking);
            metrics.EmbeddedXlsx           = GetBoolForMetrics(metricsXml, H.EmbeddedXlsx);
            metrics.InvalidSaveThroughXslt = GetBoolForMetrics(metricsXml, H.InvalidSaveThroughXslt);
            metrics.TrackRevisionsEnabled  = GetBoolForMetrics(metricsXml, H.TrackRevisionsEnabled);
            metrics.DocumentProtection     = GetBoolForMetrics(metricsXml, H.DocumentProtection);
            metrics.Valid                  = GetBoolForMetrics(metricsXml, H.Valid);
            metrics.Languages              = GetStringForMetrics(metricsXml, H.Languages);
            metrics.NumberingFormatList    = GetStringForMetrics(metricsXml, H.NumberingFormatList);

            return(metrics);
        }
예제 #55
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 static XDocument Find(WmlDocument doc, string xmlPartName)
 {
     using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
     {
         WordprocessingDocument document = streamDoc.GetWordprocessingDocument();
         string partName = "/" + xmlPartName;
         var customXmlPart =
             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 customXmlPart.GetXDocument();
     }
 }
        public static XElement GetDocxMetrics(WmlDocument wmlDoc, MetricsGetterSettings settings)
        {
            WmlDocument converted = new WmlDocument(wmlDoc, true);
            WmlDocument noTrackedRevisions = new WmlDocument(converted);

            try
            {
                using (OpenXmlMemoryStreamDocument noTrackedStreamDoc = new OpenXmlMemoryStreamDocument(noTrackedRevisions))
                using (WordprocessingDocument noTrackedDocument = noTrackedStreamDoc.GetWordprocessingDocument())
                using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(converted))
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    if (RevisionAccepter.HasTrackedRevisions(noTrackedDocument))
                        RevisionAccepter.AcceptRevisions(noTrackedDocument);
                    return GetWmlMetrics(converted.FileName, false, document, noTrackedDocument, settings);
                }
            }
            catch (OpenXmlPowerToolsException e)
            {
                if (e.ToString().Contains("Invalid Hyperlink"))
                {
                    using (MemoryStream ms = new MemoryStream())
                    {
                        WmlDocument fixedWmlDoc = new WmlDocument(converted);
                        ms.Write(converted.DocumentByteArray, 0, converted.DocumentByteArray.Length);
#if !NET35
                        UriFixer.FixInvalidUri(ms, brokenUri => FixUri(brokenUri));
#endif
                        converted = new WmlDocument("dummy.docx", ms.ToArray());
                    }
                    noTrackedRevisions = new WmlDocument(converted);
                    using (OpenXmlMemoryStreamDocument noTrackedStreamDoc = new OpenXmlMemoryStreamDocument(noTrackedRevisions))
                    using (WordprocessingDocument noTrackedDocument = noTrackedStreamDoc.GetWordprocessingDocument())
                    using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(converted))
                    using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                    {
                        if (RevisionAccepter.HasTrackedRevisions(noTrackedDocument))
                            RevisionAccepter.AcceptRevisions(noTrackedDocument);
                        return GetWmlMetrics(converted.FileName, true, document, noTrackedDocument, settings);
                    }
                }
            }
            var metrics = new XElement(H.Metrics,
                new XAttribute(H.FileName, converted.FileName),
                new XAttribute(H.FileType, "WordprocessingML"),
                new XAttribute(H.Error, "Unknown error, metrics not determined"));
            return metrics;
        }
        /// <summary>
        /// Removes all of the comments existing in the document
        /// </summary>
        public static OpenXmlPowerToolsDocument RemoveAll(WmlDocument doc)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    //Removes comment-related tags inside the main document part
                    IEnumerable<XElement> commentReferences = CommentReferences(document).ToList();
                    commentReferences.Remove();
                    document.MainDocumentPart.PutXDocument();

                    WordprocessingCommentsPart commentsPart = document.MainDocumentPart.WordprocessingCommentsPart;
                    if (commentsPart != null)
                        commentsPart.RemovePart();
                }
                return streamDoc.GetModifiedDocument();
            }
        }
        public void LIR001_ListItemRetriever(string file)
        {
            FileInfo lirFile = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, file));
            WmlDocument wmlDoc = new WmlDocument(lirFile.FullName);

            var wordHtmlFile = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, lirFile.Name.Replace(".docx", "-Word.html")));
            WordAutomationUtilities.SaveAsHtmlUsingWord(lirFile, wordHtmlFile);

            var ptHtmlFile = ConvertToHtml(lirFile.FullName, TestUtil.TempDir.FullName);
            var fiPtXml = SaveHtmlAsXml(ptHtmlFile);

            // read and write to get the BOM on the file
            var wh = File.ReadAllText(wordHtmlFile.FullName, Encoding.Default);
            File.WriteAllText(wordHtmlFile.FullName, wh, Encoding.UTF8);

            var wordXml = SaveHtmlAsXml(wordHtmlFile);
            CompareNumbering(fiPtXml, wordXml);
        }
예제 #59
0
        static void mergeDocx(string paramOutputFile, List<FileStream> paramDocumentstreams)
        {
            var sources = new List<Source>();
            foreach (var stream in paramDocumentstreams)
            {
                var tempms = new MemoryStream();

                if (0 != stream.Length)
                {
                    stream.CopyTo(tempms);
                    WmlDocument doc = new WmlDocument(stream.Length.ToString(), tempms);
                    sources.Add(new Source(doc, true));
                }
            }

            var mergedDoc = DocumentBuilder.BuildDocument(sources);
            mergedDoc.SaveAs(paramOutputFile);
        }
예제 #60
0
        /// <summary>
        /// Replaces a previously existing customXml part by another one
        /// </summary>
        /// <param name="customXmlDocument">XDocument of part to replace inside the document package</param>
        /// <param name="partNameOnly">Name of the part.</param>
        public static OpenXmlPowerToolsDocument SetDocument(WmlDocument doc, XDocument customXmlDocument, string partNameOnly)
        {
            using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(doc))
            {
                using (WordprocessingDocument document = streamDoc.GetWordprocessingDocument())
                {
                    string partName = "/" + partNameOnly;
                    var customXmlPart = document.MainDocumentPart.CustomXmlParts.Where(
                            t => t.Uri.OriginalString.EndsWith(partName, System.StringComparison.OrdinalIgnoreCase)
                        ).FirstOrDefault();

                    if (customXmlPart == null)
                        customXmlPart = document.MainDocumentPart.AddCustomXmlPart(CustomXmlPartType.CustomXml);
                    customXmlPart.PutXDocument(customXmlDocument);
                }
                return streamDoc.GetModifiedDocument();
            }
        }