Beispiel #1
0
        public void DA103_UseXmlDocument(string name, string data, bool err)
        {
            FileInfo templateDocx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name));
            FileInfo dataFile     = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, data));

            WmlDocument wmlTemplate = new WmlDocument(templateDocx.FullName);
            XmlDocument xmldata     = new XmlDocument();

            xmldata.Load(dataFile.FullName);

            bool        returnedTemplateError;
            WmlDocument afterAssembling = DocumentAssembler.AssembleDocument(wmlTemplate, xmldata, out returnedTemplateError);
            var         assembledDocx   = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, templateDocx.Name.Replace(".docx", "-processed-by-DocumentAssembler.docx")));

            afterAssembling.SaveAs(assembledDocx.FullName);

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(afterAssembling.DocumentByteArray, 0, afterAssembling.DocumentByteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                {
                    OpenXmlValidator v = new OpenXmlValidator();
                    var valErrors      = v.Validate(wDoc).Where(ve => !s_ExpectedErrors.Contains(ve.Description));
                    Assert.Equal(0, valErrors.Count());
                }
            }

            Assert.Equal(err, returnedTemplateError);
        }
        private static void SaveValidateAndFormatMainDocPart(FileInfo destDocxFi, WmlDocument doc)
        {
            WmlDocument formattedDoc;

            doc.SaveAs(destDocxFi.FullName);
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(doc.DocumentByteArray, 0, doc.DocumentByteArray.Length);
                using (WordprocessingDocument document = WordprocessingDocument.Open(ms, true))
                {
                    XDocument xDoc = document.MainDocumentPart.GetXDocument();
                    document.MainDocumentPart.PutXDocumentWithFormatting();
                    OpenXmlValidator validator = new OpenXmlValidator();
                    var errors       = validator.Validate(document);
                    var errorsString = errors
                                       .Select(e => e.Description + Environment.NewLine)
                                       .StringConcatenate();

                    // Assert that there were no errors in the generated document.
                    Assert.Equal("", errorsString);
                }
                formattedDoc = new WmlDocument(destDocxFi.FullName, ms.ToArray());
            }
            formattedDoc.SaveAs(destDocxFi.FullName);
        }
Beispiel #3
0
        public AssembleResult AssembleDocument(string templateFile, TextReader xmlData, string outputFile)
        {
            if (!File.Exists(templateFile))
            {
                throw new FileNotFoundException("Template not found in the expected location", templateFile);
            }
            WmlDocument templateDoc     = new WmlDocument(templateFile); // reads the template's bytes into memory
            XElement    data            = xmlData.Peek() == -1 ? new XElement("none") : XElement.Load(xmlData);
            WmlDocument wmlAssembledDoc = DocumentAssembler.AssembleDocument(templateDoc, data, out bool templateError);

            if (templateError)
            {
                Console.WriteLine("Errors in template.");
                Console.WriteLine("See the assembled document to inspect errors.");
            }
            if (!string.IsNullOrEmpty(outputFile))
            {
                //// save the output (even in the case of error, since error messages are in the file)
                wmlAssembledDoc.SaveAs(outputFile);
                return(new AssembleResult(outputFile, templateError));
            }
            else
            {
                return(new AssembleResult(wmlAssembledDoc.DocumentByteArray, templateError));
            }
        }
        static void Main(string[] args)
        {
            // Accept all revisions, save result as a new document
            WmlDocument result = RevisionAccepter.AcceptRevisions(new WmlDocument("../../Source1.docx"));

            result.SaveAs("Out1.docx");
        }
Beispiel #5
0
    public static void ConvertToDocx(string file, string destinationDir)
    {
        bool s_ProduceAnnotatedHtml = true;

        var sourceHtmlFi = new FileInfo(file);

        Console.WriteLine("Converting " + sourceHtmlFi.Name);
        var sourceImageDi = new DirectoryInfo(destinationDir);

        var destCssFi       = new FileInfo(Path.Combine(destinationDir, sourceHtmlFi.Name.Replace(".html", ".css")));
        var destDocxFi      = new FileInfo(Path.Combine(destinationDir, sourceHtmlFi.Name.Replace(".html", "-ConvertedByHtmlToWml.docx")));
        var annotatedHtmlFi = new FileInfo(Path.Combine(destinationDir, sourceHtmlFi.Name.Replace(".html", "-Annotated.txt")));

        XElement html = HtmlToWmlReadAsXElement.ReadAsXElement(sourceHtmlFi);

        string usedAuthorCss = HtmlToWmlConverter.CleanUpCss((string)html.Descendants().FirstOrDefault(d => d.Name.LocalName.ToLower() == "style" && !d.HasAttributes));

        usedAuthorCss = ConvertFontEncode(usedAuthorCss);
        File.WriteAllText(destCssFi.FullName, usedAuthorCss);

        HtmlToWmlConverterSettings settings = HtmlToWmlConverter.GetDefaultSettings();

        // image references in HTML files contain the path to the subdir that contains the images, so base URI is the name of the directory
        // that contains the HTML files
        settings.BaseUriForImages = sourceHtmlFi.DirectoryName;

        WmlDocument doc = HtmlToWmlConverter.ConvertHtmlToWml(defaultCss, usedAuthorCss, userCss, html, settings, null, s_ProduceAnnotatedHtml ? annotatedHtmlFi.FullName : null);

        doc.SaveAs(destDocxFi.FullName);
    }
        private static void SaveValidateAndFormatMainDocPart(FileInfo destDocxFi, WmlDocument doc)
        {
            WmlDocument formattedDoc;

            if (File.Exists(destDocxFi.FullName))
            {
                File.Delete(destDocxFi.FullName);
            }

            doc.SaveAs(destDocxFi.FullName);
            using (var ms = new MemoryStream())
            {
                ms.Write(doc.DocumentByteArray, 0, doc.DocumentByteArray.Length);
                using (var document = WordprocessingDocument.Open(ms, true))
                {
                    var xDoc = document.MainDocumentPart.GetXDocument();
                    document.MainDocumentPart.PutXDocumentWithFormatting();
                    var validator    = new OpenXmlValidator();
                    var errors       = validator.Validate(document);
                    var errorsString = errors.Select(e => e.Description + Environment.NewLine).StringConcatenate();

                    Assert.True(errorsString.Length == 0, $"Error in {destDocxFi.FullName}\n{errorsString}");
                }
                formattedDoc = new WmlDocument(destDocxFi.FullName, ms.ToArray());
            }
            formattedDoc.SaveAs(destDocxFi.FullName);
        }
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]
        //[InlineData("", "")]

        public void WC004_Compare_To_Self(string name)
        {
            FileInfo sourceDocx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name));

            var sourceCopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, sourceDocx.Name.Replace(".docx", "-Source.docx")));

            if (!sourceCopiedToDestDocx.Exists)
            {
                File.Copy(sourceDocx.FullName, sourceCopiedToDestDocx.FullName);
            }

            var before          = sourceCopiedToDestDocx.Name.Replace(".docx", "");
            var docxComparedFi  = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, before + "-COMPARE" + ".docx"));
            var docxCompared2Fi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, before + "-COMPARE2" + ".docx"));

            WmlDocument         source1Wml = new WmlDocument(sourceCopiedToDestDocx.FullName);
            WmlDocument         source2Wml = new WmlDocument(sourceCopiedToDestDocx.FullName);
            WmlComparerSettings settings   = new WmlComparerSettings();

            WmlDocument comparedWml = WmlComparer.Compare(source1Wml, source2Wml, settings);

            comparedWml.SaveAs(docxComparedFi.FullName);
            ValidateDocument(comparedWml);

            WmlDocument comparedWml2 = WmlComparer.Compare(comparedWml, source1Wml, settings);

            comparedWml2.SaveAs(docxCompared2Fi.FullName);
            ValidateDocument(comparedWml2);
        }
Beispiel #8
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();

            string        source1 = "../../Source1.docx";
            string        source2 = "../../Source2.docx";
            string        source3 = "../../Source3.docx";
            List <Source> sources = null;

            // Create new document from 10 paragraphs starting at paragraph 5 of Source1.docx
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), 5, 10, true),
            };
            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out1.docx"));

            // Create new document from paragraph 1, and paragraphs 5 through end of Source3.docx.
            // This effectively 'deletes' paragraphs 2-4
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source3), 0, 1, false),
                new Source(new WmlDocument(source3), 4, false),
            };
            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out2.docx"));

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source1.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), true),
                new Source(new WmlDocument(source2), false),
            };
            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out3.docx"));

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source2.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), false),
                new Source(new WmlDocument(source2), true),
            };
            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out4.docx"));

            // Create a new document that consists of the first 5 paragraphs of Source1.docx and the first
            // five paragraphs of Source2.docx.  This example returns a new WmlDocument, when you then can
            // serialize to a SharePoint document library, or use in some other interesting scenario.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), 0, 5, false),
                new Source(new WmlDocument(source2), 0, 5, true),
            };
            WmlDocument out5 = DocumentBuilder.BuildDocument(sources);

            out5.SaveAs(Path.Combine(tempDi.FullName, "Out5.docx"));  // save it to the file system, but we could just as easily done something
                                                                      // else with it.
        }
Beispiel #9
0
 protected override void EndProcessing()
 {
     try
     {
         if (m_Sources != null)
         {
             foreach (DocumentSource source in m_Sources)
             {
                 Collection <PathInfo> fileList = SessionState.Path.GetResolvedPSPathFromPSPath(source.SourceFile);
                 foreach (var file in fileList)
                 {
                     OpenXmlPowerToolsDocument document = OpenXmlPowerToolsDocument.FromFileName(file.Path);
                     try
                     {
                         if (!(document is WmlDocument))
                         {
                             throw new PowerToolsDocumentException("Not a wordprocessing document.");
                         }
                         if (source.Count != -1)
                         {
                             buildSources.Add(new Source((WmlDocument)document, source.Start - 1, source.Count, source.KeepSection));
                         }
                         else if (source.Start != -1)
                         {
                             buildSources.Add(new Source((WmlDocument)document, source.Start - 1, source.KeepSection));
                         }
                         else
                         {
                             buildSources.Add(new Source((WmlDocument)document, source.KeepSection));
                         }
                     }
                     catch (Exception e)
                     {
                         WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, document));
                     }
                 }
             }
         }
         WmlDocument result = DocumentBuilder.BuildDocument(buildSources);
         if (m_OutputPath != null)
         {
             if (!File.Exists(m_OutputPath) || ShouldProcess(m_OutputPath, "Merge-OpenXmlDocumentCmdlet"))
             {
                 result.SaveAs(m_OutputPath);
             }
         }
         if (PassThru)
         {
             WriteObject(result, true);
         }
     }
     catch (Exception e)
     {
         WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, null));
     }
 }
        public void RA001(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);
        }
        static void Main(string[] args)
        {
            string        source1 = "../../Source1.docx";
            string        source2 = "../../Source2.docx";
            string        source3 = "../../Source3.docx";
            List <Source> sources = null;

            // Create new document from 10 paragraphs starting at paragraph 5 of Source1.docx
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), 5, 10, true),
            };
            DocumentBuilder.BuildDocument(sources, "Out1.docx");

            // Create new document from paragraph 1, and paragraphs 5 through end of Source3.docx.
            // This effectively 'deletes' paragraphs 2-4
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source3), 0, 1, false),
                new Source(new WmlDocument(source3), 4, false),
            };
            DocumentBuilder.BuildDocument(sources, "Out2.docx");

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source1.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), true),
                new Source(new WmlDocument(source2), false),
            };
            DocumentBuilder.BuildDocument(sources, "Out3.docx");

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source2.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), false),
                new Source(new WmlDocument(source2), true),
            };
            DocumentBuilder.BuildDocument(sources, "Out4.docx");

            // Create a new document that consists of the first 5 paragraphs of Source1.docx and the first
            // five paragraphs of Source2.docx.  This example returns a new WmlDocument, when you then can
            // serialize to a SharePoint document library, or use in some other interesting scenario.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1), 0, 5, false),
                new Source(new WmlDocument(source2), 0, 5, true),
            };
            WmlDocument out5 = DocumentBuilder.BuildDocument(sources);

            out5.SaveAs("Out5.docx");  // save it to the file system, but we could just as easily done something
            // else with it.
        }
        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();

            // Accept all revisions, save result as a new document
            WmlDocument result = RevisionAccepter.AcceptRevisions(new WmlDocument("../../Source1.docx"));

            result.SaveAs(Path.Combine(tempDi.FullName, "Out1.docx"));
        }
Beispiel #13
0
        public void FA001_DocumentsWithRevTracking(string testId, string src)
        {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Load the source document
            DirectoryInfo sourceDir         = new DirectoryInfo("../../../../TestFiles/");
            FileInfo      sourceDocxFi      = new FileInfo(Path.Combine(sourceDir.FullName, src));
            WmlDocument   wmlSourceDocument = new WmlDocument(sourceDocxFi.FullName);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Create the dir for the test
            var rootTempDir     = TestUtil.TempDir;
            var thisTestTempDir = new DirectoryInfo(Path.Combine(rootTempDir.FullName, testId));

            if (thisTestTempDir.Exists)
            {
                Assert.True(false, "Duplicate test id: " + testId);
            }
            else
            {
                thisTestTempDir.Create();
            }
            var tempDirFullName = thisTestTempDir.FullName;

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Copy src DOCX to temp directory, for ease of review

            var sourceDocxCopiedToDestFileName = new FileInfo(Path.Combine(tempDirFullName, sourceDocxFi.Name));

            if (!sourceDocxCopiedToDestFileName.Exists)
            {
                wmlSourceDocument.SaveAs(sourceDocxCopiedToDestFileName.FullName);
            }

            var sourceDocxAcceptedCopiedToDestFileName = new FileInfo(Path.Combine(tempDirFullName, sourceDocxFi.Name.ToLower().Replace(".docx", "-accepted.docx")));
            var wmlSourceAccepted = RevisionProcessor.AcceptRevisions(wmlSourceDocument);

            wmlSourceAccepted.SaveAs(sourceDocxAcceptedCopiedToDestFileName.FullName);

            var outFi = new FileInfo(Path.Combine(tempDirFullName, "Output.docx"));
            FormattingAssemblerSettings settings = new FormattingAssemblerSettings();
            var assembledWml = FormattingAssembler.AssembleFormatting(wmlSourceDocument, settings);

            assembledWml.SaveAs(outFi.FullName);

            var outAcceptedFi        = new FileInfo(Path.Combine(tempDirFullName, "Output-accepted.docx"));
            var assembledAcceptedWml = RevisionProcessor.AcceptRevisions(assembledWml);

            assembledAcceptedWml.SaveAs(outAcceptedFi.FullName);

            Validate(outFi);
        }
Beispiel #14
0
            static void Main2(string[] args)
            {
                if (args.Length != 3)
                {
                    PrintUsage();
                    Environment.Exit(0);
                }

                FileInfo templateDoc = new FileInfo(args[0]);

                if (!templateDoc.Exists)
                {
                    Console.WriteLine("Error, {0} does not exist.", args[0]);
                    PrintUsage();
                    Environment.Exit(0);
                }
                FileInfo dataFile = new FileInfo(args[1]);

                if (!dataFile.Exists)
                {
                    Console.WriteLine("Error, {0} does not exist.", args[1]);
                    PrintUsage();
                    Environment.Exit(0);
                }
                FileInfo assembledDoc = new FileInfo(args[2]);

                if (assembledDoc.Exists)
                {
                    Console.WriteLine("Error, {0} exists.", args[2]);
                    PrintUsage();
                    Environment.Exit(0);
                }

                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 {0} to determine the errors in the template.", assembledDoc.Name);
                }

                wmlAssembledDoc.SaveAs(assembledDoc.FullName);
            }
Beispiel #15
0
        public string SaveAs(string saveTo)
        {
            XElement xhtml = HtmlToWmlReadAsXElement.ReadAsXElement(new FileInfo(this.absolutePath));

            xhtml.Descendants().Where(i => i.Name.LocalName.ToLower() == "script").Remove();
            string linkCss   = "";
            string headerCss = "";

            try
            {
                var linkStyleSheets = xhtml.Descendants().Where(d => d.Name.LocalName.ToLower() == "link" &&
                                                                d.Attribute("rel").Value.ToLower() == "stylesheet").Select(d => File.ReadAllText(d.Attribute("href").Value));
                linkCss   = HtmlToWmlConverter.CleanUpCss(string.Join("\r\n", linkStyleSheets));
                headerCss = HtmlToWmlConverter.CleanUpCss((string)xhtml.Descendants().FirstOrDefault(d => d.Name.LocalName.ToLower() == "style"));
                linkCss   = linkCss.Trim('\r', '\n');
            }
            catch (Exception ecss)
            {
                Logger.Error("获取CSS出错", ecss);
            }
            File.WriteAllText(Path.Combine(this.workingDirectory, "dump-link.css"), linkCss);
            File.WriteAllText(Path.Combine(this.workingDirectory, "dump-header.css"), headerCss);
            HtmlToWmlConverterSettings settings = HtmlToWmlConverter.GetDefaultSettings();

            try
            {
                WmlDocument word = HtmlToWmlConverter.ConvertHtmlToWml(defaultCss, linkCss, headerCss, xhtml, settings);
                word.SaveAs(saveTo);
            }
            catch (Exception ew)
            {
                Logger.Error("保存Word出错", ew);
            }
#if !DEBUG
            try
            {
                Directory.Delete(this.workingDirectory, true);
            }
            catch (Exception ex)
            {
                Logger.Error("Delete Directory error. Directory=" + this.workingDirectory, ex);
            }
#endif
            return(saveTo);
        }
 protected override void EndProcessing()
 {
     try
     {
         if (m_OutputPath != null)
         {
             if (!File.Exists(m_OutputPath) || ShouldProcess(m_OutputPath, "Merge-OpenXmlDocumentCommentCmdlet"))
             {
                 current.SaveAs(m_OutputPath);
             }
         }
         if (PassThru)
         {
             WriteObject(current, true);
         }
     }
     catch (Exception e)
     {
         WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, null));
     }
 }
Beispiel #17
0
        public void DA101(string name, string data, bool err)
        {
            DirectoryInfo sourceDir    = new DirectoryInfo("../../../../TestFiles/");
            FileInfo      templateDocx = new FileInfo(Path.Combine(sourceDir.FullName, name));
            FileInfo      dataFile     = new FileInfo(Path.Combine(sourceDir.FullName, data));

            WmlDocument wmlTemplate = new WmlDocument(templateDocx.FullName);
            XElement    xmldata     = XElement.Load(dataFile.FullName);

            bool        returnedTemplateError;
            WmlDocument afterAssembling = DocumentAssembler.AssembleDocument(wmlTemplate, xmldata, out returnedTemplateError);
            var         assembledDocx   = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, templateDocx.Name.Replace(".docx", "-processed-by-DocumentAssembler.docx")));

            afterAssembling.SaveAs(assembledDocx.FullName);

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(afterAssembling.DocumentByteArray, 0, afterAssembling.DocumentByteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                {
                    OpenXmlValidator v = new OpenXmlValidator();
                    var valErrors      = v.Validate(wDoc).Where(ve => !s_ExpectedErrors.Contains(ve.Description));

#if false
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in valErrors.Select(r => r.Description).OrderBy(t => t).Distinct())
                    {
                        sb.Append(item).Append(Environment.NewLine);
                    }
                    string z = sb.ToString();
                    Console.WriteLine(z);
#endif

                    Assert.Empty(valErrors);
                }
            }

            Assert.Equal(err, returnedTemplateError);
        }
Beispiel #18
0
        /// <summary>
        /// Generate final word document starting from a Template and xml data informations.
        /// </summary>
        /// <param name="currentDate">current Date used in genetayed file name.</param>
        /// <param name="temporaryFolder">use a folder to keep files</param>
        /// <param name="templateDocument">the template document</param>
        /// <param name="openXmlPowerToolsWmlDocument">an object from powerTools</param>
        /// <param name="data">xml data file</param>
        /// <returns>true or false</returns>
        private static bool Generate(DateTime currentDate, DirectoryInfo temporaryFolder, FileInfo templateDocument, WmlDocument openXmlPowerToolsWmlDocument, XElement data)
        {
            bool        errors;
            WmlDocument wmlAssembledDoc = DocumentAssembler.AssembleDocument(openXmlPowerToolsWmlDocument, data, out errors);

            if (errors)
            {
                return(true);
            }

            try
            {
                FileInfo generatedDocument = new FileInfo(Path.Combine(temporaryFolder.FullName, string.Format("GeneratedFromTemplate{0:00}-{1:00}-{2:00}-{3:00}{4:00}{5:00}.docx", currentDate.Year, currentDate.Month, currentDate.Day, currentDate.Hour, currentDate.Minute, currentDate.Second)));
                wmlAssembledDoc.SaveAs(generatedDocument.FullName);
            }
            catch (Exception)
            {
                return(true);
            }


            return(errors);
        }
        public void DB999_DocumentBuilder(string testId, string src, bool shouldThrow)
        {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Load the source document
            DirectoryInfo sourceDir         = new DirectoryInfo("../../../../TestFiles/");
            FileInfo      sourceDocxFi      = new FileInfo(Path.Combine(sourceDir.FullName, src));
            WmlDocument   wmlSourceDocument = new WmlDocument(sourceDocxFi.FullName);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Create the dir for the test
            var rootTempDir     = TestUtil.TempDir;
            var thisTestTempDir = new DirectoryInfo(Path.Combine(rootTempDir.FullName, testId));

            if (thisTestTempDir.Exists)
            {
                Assert.True(false, "Duplicate test id: " + testId);
            }
            else
            {
                thisTestTempDir.Create();
            }
            var tempDirFullName = thisTestTempDir.FullName;

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Copy src DOCX to temp directory, for ease of review

            while (true)
            {
                try
                {
                    ////////// CODE TO REPEAT UNTIL SUCCESS //////////
                    var sourceDocxCopiedToDestFileName = new FileInfo(Path.Combine(tempDirFullName, sourceDocxFi.Name));
                    if (!sourceDocxCopiedToDestFileName.Exists)
                    {
                        wmlSourceDocument.SaveAs(sourceDocxCopiedToDestFileName.FullName);
                    }
                    //////////////////////////////////////////////////
                    break;
                }
                catch (IOException)
                {
                    System.Threading.Thread.Sleep(50);
                }
            }

            List <string> expectedErrors;

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(wmlSourceDocument.DocumentByteArray, 0, wmlSourceDocument.DocumentByteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, false))
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    expectedErrors = validator.Validate(wDoc)
                                     .Select(e => e.Description)
                                     .Distinct()
                                     .ToList();
                }
            }
            foreach (var item in s_ExpectedErrors)
            {
                expectedErrors.Add(item);
            }

            List <Source> sources = new List <Source>()
            {
                new Source(wmlSourceDocument, true),
            };

            var outFi = new FileInfo(Path.Combine(tempDirFullName, "Output.docx"));

            if (shouldThrow)
            {
                Assert.Throws <DocumentBuilderException>(() => DocumentBuilder.BuildDocument(sources, outFi.FullName));
            }
            else
            {
                var outWml = DocumentBuilder.BuildDocument(sources);
                outWml.SaveAs(outFi.FullName);

                using (MemoryStream ms = new MemoryStream())
                {
                    ms.Write(outWml.DocumentByteArray, 0, outWml.DocumentByteArray.Length);
                    using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, false))
                    {
                        OpenXmlValidator validator = new OpenXmlValidator();
                        var errors = validator.Validate(wDoc).Where(e =>
                        {
                            var str = e.Description;
                            foreach (var ee in expectedErrors)
                            {
                                if (str.Contains(ee))
                                {
                                    return(false);
                                }
                            }
                            return(true);
                        });
                        if (errors.Count() != 0)
                        {
                            var message = errors.Select(e => e.Description + Environment.NewLine).StringConcatenate();
                            Assert.True(false, message);
                        }
                    }
                }
            }
        }
        public void DB009_ImportIntoHeadersFooters(string testId, string src, string dest, string insertId)
        {
            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Load the source document
            var sourceDocxFi      = new FileInfo(Path.Combine(_sourceDir.FullName, src));
            var wmlSourceDocument = new WmlDocument(sourceDocxFi.FullName);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Load the dest document
            var destDocxFi      = new FileInfo(Path.Combine(_sourceDir.FullName, dest));
            var wmlDestDocument = new WmlDocument(destDocxFi.FullName);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Create the dir for the test
            var thisTestTempDir = new DirectoryInfo(Path.Combine(TempDir, testId));

            if (thisTestTempDir.Exists)
            {
                Assert.True(false, "Duplicate test id: " + testId);
            }
            else
            {
                thisTestTempDir.Create();
            }
            var tempDirFullName = thisTestTempDir.FullName;

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Copy src DOCX to temp directory, for ease of review

            while (true)
            {
                try
                {
                    ////////// CODE TO REPEAT UNTIL SUCCESS //////////
                    var sourceDocxCopiedToDestFileName = new FileInfo(Path.Combine(tempDirFullName, sourceDocxFi.Name));
                    if (!sourceDocxCopiedToDestFileName.Exists)
                    {
                        wmlSourceDocument.SaveAs(sourceDocxCopiedToDestFileName.FullName);
                    }
                    //////////////////////////////////////////////////
                    break;
                }
                catch (IOException)
                {
                    System.Threading.Thread.Sleep(50);
                }
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Copy dest DOCX to temp directory, for ease of review

            while (true)
            {
                try
                {
                    ////////// CODE TO REPEAT UNTIL SUCCESS //////////
                    var destDocxCopiedToDestFileName = new FileInfo(Path.Combine(tempDirFullName, destDocxFi.Name));
                    if (!destDocxCopiedToDestFileName.Exists)
                    {
                        wmlDestDocument.SaveAs(destDocxCopiedToDestFileName.FullName);
                    }
                    //////////////////////////////////////////////////
                    break;
                }
                catch (IOException)
                {
                    System.Threading.Thread.Sleep(50);
                }
            }

            var sources = new List <ISource>
            {
                new Source(wmlDestDocument),
                new Source(wmlSourceDocument, insertId),
            };

            var outFi = new FileInfo(Path.Combine(tempDirFullName, "Output.docx"));

            DocumentBuilder.BuildDocument(sources, outFi.FullName);
            Validate(outFi);
        }
        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();

            const string source1 = "../../../Source1.docx";
            const string source2 = "../../../Source2.docx";
            const string source3 = "../../../Source3.docx";

            // Create new document from 10 paragraphs starting at paragraph 5 of Source1.docx
            var sources = new List <Source>
            {
                new(new WmlDocument(source1), 5, 10, true)
            };

            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out1.docx"));

            // Create new document from paragraph 1, and paragraphs 5 through end of Source3.docx.
            // This effectively 'deletes' paragraphs 2-4
            sources = new List <Source>
            {
                new(new WmlDocument(source3), 0, 1, false),
                new(new WmlDocument(source3), 4, false)
            };

            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out2.docx"));

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source1.
            sources = new List <Source>
            {
                new(new WmlDocument(source1), true),
                new(new WmlDocument(source2), false)
            };

            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out3.docx"));

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source2.
            sources = new List <Source>
            {
                new(new WmlDocument(source1), false),
                new(new WmlDocument(source2), true)
            };

            DocumentBuilder.BuildDocument(sources, Path.Combine(tempDi.FullName, "Out4.docx"));

            // Create a new document that consists of the first 5 paragraphs of Source1.docx and the first
            // five paragraphs of Source2.docx.  This example returns a new WmlDocument, when you then can
            // serialize to a SharePoint document library, or use in some other interesting scenario.
            sources = new List <Source>
            {
                new(new WmlDocument(source1), 0, 5, false),
                new(new WmlDocument(source2), 0, 5, true)
            };

            WmlDocument out5 = DocumentBuilder.BuildDocument(sources);

            out5.SaveAs(Path.Combine(tempDi.FullName, "Out5.docx"));
        }
        public void WC001_Consolidate(string originalName, string revisedDocumentsXml)
        {
            FileInfo originalDocx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, originalName));

            var originalCopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, originalDocx.Name));

            if (!originalCopiedToDestDocx.Exists)
            {
                File.Copy(originalDocx.FullName, originalCopiedToDestDocx.FullName);
            }

            var revisedDocumentsXElement = XElement.Parse(revisedDocumentsXml);
            var revisedDocumentsArray    = revisedDocumentsXElement
                                           .Elements()
                                           .Select(z =>
            {
                FileInfo revisedDocx        = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, z.Element("DocName").Value));
                var revisedCopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, revisedDocx.Name));
                if (!revisedCopiedToDestDocx.Exists)
                {
                    File.Copy(revisedDocx.FullName, revisedCopiedToDestDocx.FullName);
                }
                return(new WmlRevisedDocumentInfo()
                {
                    RevisedDocument = new WmlDocument(revisedCopiedToDestDocx.FullName),
                    Color = Color.FromName(z.Element("Color").Value),
                    Revisor = z.Element("Revisor").Value,
                });
            })
                                           .ToList();

            var consolidatedDocxName   = originalCopiedToDestDocx.Name.Replace(".docx", "-Consolidated.docx");
            var consolidatedDocumentFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, consolidatedDocxName));

            WmlDocument         source1Wml      = new WmlDocument(originalCopiedToDestDocx.FullName);
            WmlComparerSettings settings        = new WmlComparerSettings();
            WmlDocument         consolidatedWml = WmlComparer.Consolidate(
                source1Wml,
                revisedDocumentsArray,
                settings);

            consolidatedWml.SaveAs(consolidatedDocumentFi.FullName);

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(consolidatedWml.DocumentByteArray, 0, consolidatedWml.DocumentByteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    var errors = validator.Validate(wDoc).Where(e => !ExpectedErrors.Contains(e.Description));
                    if (errors.Count() > 0)
                    {
                        var ind = "  ";
                        var sb  = new StringBuilder();
                        foreach (var err in errors)
                        {
#if true
                            sb.Append("Error" + Environment.NewLine);
                            sb.Append(ind + "ErrorType: " + err.ErrorType.ToString() + Environment.NewLine);
                            sb.Append(ind + "Description: " + err.Description + Environment.NewLine);
                            sb.Append(ind + "Part: " + err.Part.Uri.ToString() + Environment.NewLine);
                            sb.Append(ind + "XPath: " + err.Path.XPath + Environment.NewLine);
#else
                            sb.Append("            \"" + err.Description + "\"," + Environment.NewLine);
#endif
                        }
                        var sbs = sb.ToString();
                        Assert.Equal("", sbs);
                    }
                }
            }

            /************************************************************************************************************************/

            if (s_OpenWord)
            {
                FileInfo wordExe = new FileInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
                WordRunner.RunWord(wordExe, consolidatedDocumentFi);
            }

            /************************************************************************************************************************/
        }
        public void DoTest(string name)
        {
            var sourceFi           = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name));
            var baselineAcceptedFi = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name.Replace(".docx", "-Accepted.docx")));
            var baselineRejectedFi = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name.Replace(".docx", "-Rejected.docx")));

            WmlDocument sourceWml         = new WmlDocument(sourceFi.FullName);
            WmlDocument afterRejectingWml = RevisionProcessor.RejectRevisions(sourceWml);
            WmlDocument afterAcceptingWml = RevisionProcessor.AcceptRevisions(sourceWml);

            var processedAcceptedFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, sourceFi.Name.Replace(".docx", "-Accepted.docx")));

            afterAcceptingWml.SaveAs(processedAcceptedFi.FullName);

            var processedRejectedFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, sourceFi.Name.Replace(".docx", "-Rejected.docx")));

            afterRejectingWml.SaveAs(processedRejectedFi.FullName);

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Copy source files to temp dir
            if (m_CopySourceFilesToTempDir)
            {
                while (true)
                {
                    try
                    {
                        ////////// CODE TO REPEAT UNTIL SUCCESS //////////
                        var sourceDocxCopiedToDestFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, sourceFi.Name));
                        if (!sourceDocxCopiedToDestFi.Exists)
                        {
                            sourceWml.SaveAs(sourceDocxCopiedToDestFi.FullName);
                        }
                        //////////////////////////////////////////////////
                        break;
                    }
                    catch (IOException)
                    {
                        System.Threading.Thread.Sleep(50);
                    }
                }
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // create batch file to copy properly processed documents to the TestFiles directory.
            while (true)
            {
                try
                {
                    ////////// CODE TO REPEAT UNTIL SUCCESS //////////
                    var batchFileName = "Copy-Gen-Files-To-TestFiles.bat";
                    var batchFi       = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, batchFileName));
                    var batch         = "";
                    batch += "copy " + processedAcceptedFi.FullName + " " + baselineAcceptedFi.FullName + Environment.NewLine;
                    batch += "copy " + processedRejectedFi.FullName + " " + baselineRejectedFi.FullName + Environment.NewLine;
                    if (batchFi.Exists)
                    {
                        File.AppendAllText(batchFi.FullName, batch);
                    }
                    else
                    {
                        File.WriteAllText(batchFi.FullName, batch);
                    }
                    //////////////////////////////////////////////////
                    break;
                }
                catch (IOException)
                {
                    System.Threading.Thread.Sleep(50);
                }
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Open Windows Explorer
            if (m_OpenTempDirInExplorer)
            {
                while (true)
                {
                    try
                    {
                        ////////// CODE TO REPEAT UNTIL SUCCESS //////////
                        var semaphorFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "z_ExplorerOpenedSemaphore.txt"));
                        if (!semaphorFi.Exists)
                        {
                            File.WriteAllText(semaphorFi.FullName, "");
                            TestUtil.Explorer(TestUtil.TempDir);
                        }
                        //////////////////////////////////////////////////
                        break;
                    }
                    catch (IOException)
                    {
                        System.Threading.Thread.Sleep(50);
                    }
                }
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Use WmlComparer to see if accepted baseline is same as processed
            if (baselineAcceptedFi.Exists)
            {
                var baselineAcceptedWml = new WmlDocument(baselineAcceptedFi.FullName);
                WmlComparerSettings wmlComparerSettings = new WmlComparerSettings();
                WmlDocument         result = WmlComparer.Compare(baselineAcceptedWml, afterAcceptingWml, wmlComparerSettings);
                var revisions = WmlComparer.GetRevisions(result, wmlComparerSettings);
                if (revisions.Any())
                {
                    Assert.True(false, "Regression Error: Accepted baseline document did not match processed document");
                }
            }
            else
            {
                Assert.True(false, "No Accepted baseline document");
            }

            ///////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
            // Use WmlComparer to see if rejected baseline is same as processed
            if (baselineRejectedFi.Exists)
            {
                var baselineRejectedWml = new WmlDocument(baselineRejectedFi.FullName);
                WmlComparerSettings wmlComparerSettings = new WmlComparerSettings();
                WmlDocument         result = WmlComparer.Compare(baselineRejectedWml, afterRejectingWml, wmlComparerSettings);
                var revisions = WmlComparer.GetRevisions(result, wmlComparerSettings);
                if (revisions.Any())
                {
                    Assert.True(false, "Regression Error: Rejected baseline document did not match processed document");
                }
            }
            else
            {
                Assert.True(false, "No Rejected baseline document");
            }
        }
        //[InlineData("", "", 0)]
        //[InlineData("", "", 0)]
        //[InlineData("", "", 0)]
        //[InlineData("", "", 0)]
        //[InlineData("", "", 0)]
        //[InlineData("", "", 0)]
        //[InlineData("", "", 0)]
        //[InlineData("", "", 0)]

        public void WC003_Compare(string name1, string name2, int revisionCount)
        {
            FileInfo source1Docx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name1));
            FileInfo source2Docx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name2));

            var source1CopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source1Docx.Name));
            var source2CopiedToDestDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source2Docx.Name));

            if (!source1CopiedToDestDocx.Exists)
            {
                File.Copy(source1Docx.FullName, source1CopiedToDestDocx.FullName);
            }
            if (!source2CopiedToDestDocx.Exists)
            {
                File.Copy(source2Docx.FullName, source2CopiedToDestDocx.FullName);
            }

            /************************************************************************************************************************/

            if (s_OpenWord)
            {
                FileInfo source1DocxForWord = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name1));
                FileInfo source2DocxForWord = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name2));

                var source1CopiedToDestDocxForWord = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source1Docx.Name.Replace(".docx", "-For-Word.docx")));
                var source2CopiedToDestDocxForWord = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, source2Docx.Name.Replace(".docx", "-For-Word.docx")));
                if (!source1CopiedToDestDocxForWord.Exists)
                {
                    File.Copy(source1Docx.FullName, source1CopiedToDestDocxForWord.FullName);
                }
                if (!source2CopiedToDestDocxForWord.Exists)
                {
                    File.Copy(source2Docx.FullName, source2CopiedToDestDocxForWord.FullName);
                }

                FileInfo wordExe = new FileInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
                var      path    = new DirectoryInfo(@"C:\Users\Eric\Documents\WindowsPowerShellModules\Open-Xml-PowerTools\TestFiles");
                WordRunner.RunWord(wordExe, source2CopiedToDestDocxForWord);
                WordRunner.RunWord(wordExe, source1CopiedToDestDocxForWord);
            }

            /************************************************************************************************************************/

            var before = source1CopiedToDestDocx.Name.Replace(".docx", "");
            var after  = source2CopiedToDestDocx.Name.Replace(".docx", "");
            var docxWithRevisionsFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, before + "-COMPARE-" + after + ".docx"));

            WmlDocument         source1Wml  = new WmlDocument(source1CopiedToDestDocx.FullName);
            WmlDocument         source2Wml  = new WmlDocument(source2CopiedToDestDocx.FullName);
            WmlComparerSettings settings    = new WmlComparerSettings();
            WmlDocument         comparedWml = WmlComparer.Compare(source1Wml, source2Wml, settings);

            comparedWml.SaveAs(docxWithRevisionsFi.FullName);

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(comparedWml.DocumentByteArray, 0, comparedWml.DocumentByteArray.Length);
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                {
                    OpenXmlValidator validator = new OpenXmlValidator();
                    var errors = validator.Validate(wDoc).Where(e => !ExpectedErrors.Contains(e.Description));
                    if (errors.Count() > 0)
                    {
                        var ind = "  ";
                        var sb  = new StringBuilder();
                        foreach (var err in errors)
                        {
#if true
                            sb.Append("Error" + Environment.NewLine);
                            sb.Append(ind + "ErrorType: " + err.ErrorType.ToString() + Environment.NewLine);
                            sb.Append(ind + "Description: " + err.Description + Environment.NewLine);
                            sb.Append(ind + "Part: " + err.Part.Uri.ToString() + Environment.NewLine);
                            sb.Append(ind + "XPath: " + err.Path.XPath + Environment.NewLine);
#else
                            sb.Append("            \"" + err.Description + "\"," + Environment.NewLine);
#endif
                        }
                        var sbs = sb.ToString();
                        Assert.Equal("", sbs);
                    }
                }
            }

            /************************************************************************************************************************/

            if (s_OpenWord)
            {
                FileInfo wordExe = new FileInfo(@"C:\Program Files (x86)\Microsoft Office\root\Office16\WINWORD.EXE");
                WordRunner.RunWord(wordExe, docxWithRevisionsFi);
            }

            /************************************************************************************************************************/

            WmlDocument revisionWml = new WmlDocument(docxWithRevisionsFi.FullName);
            var         revisions   = WmlComparer.GetRevisions(revisionWml);
            Assert.Equal(revisionCount, revisions.Count());
        }
        public void CU001(string name)
        {
            FileInfo templateFile = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name));

            if (templateFile.Extension.ToLower() == ".docx")
            {
                WmlDocument wmlTemplate = new WmlDocument(templateFile.FullName);

                var afterUpdatingDocx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, templateFile.Name.Replace(".docx", "-processed-by-ChartUpdater.docx")));
                wmlTemplate.SaveAs(afterUpdatingDocx.FullName);

                using (var wDoc = WordprocessingDocument.Open(afterUpdatingDocx.FullName, true))
                {
                    var chart1Data = new ChartData
                    {
                        SeriesNames = new[] {
                            "Car",
                            "Truck",
                            "Van",
                            "Bike",
                            "Boat",
                        },
                        CategoryDataType = ChartDataType.String,
                        CategoryNames    = new[] {
                            "Q1",
                            "Q2",
                            "Q3",
                            "Q4",
                        },
                        Values = new double[][] {
                            new double[] {
                                100, 310, 220, 450,
                            },
                            new double[] {
                                200, 300, 350, 411,
                            },
                            new double[] {
                                80, 120, 140, 600,
                            },
                            new double[] {
                                120, 100, 140, 400,
                            },
                            new double[] {
                                200, 210, 210, 480,
                            },
                        },
                    };
                    ChartUpdater.UpdateChart(wDoc, "Chart1", chart1Data);

                    var chart2Data = new ChartData
                    {
                        SeriesNames = new[] {
                            "Series"
                        },
                        CategoryDataType = ChartDataType.String,
                        CategoryNames    = new[] {
                            "Cars",
                            "Trucks",
                            "Vans",
                            "Boats",
                        },
                        Values = new double[][] {
                            new double[] {
                                320, 112, 64, 80,
                            },
                        },
                    };
                    ChartUpdater.UpdateChart(wDoc, "Chart2", chart2Data);

                    var chart3Data = new ChartData
                    {
                        SeriesNames = new[] {
                            "X1",
                            "X2",
                            "X3",
                            "X4",
                            "X5",
                            "X6",
                        },
                        CategoryDataType = ChartDataType.String,
                        CategoryNames    = new[] {
                            "Y1",
                            "Y2",
                            "Y3",
                            "Y4",
                            "Y5",
                            "Y6",
                        },
                        Values = new double[][] {
                            new double[] { 3.0, 2.1, .7, .7, 2.1, 3.0, },
                            new double[] { 3.0, 2.1, .8, .8, 2.1, 3.0, },
                            new double[] { 3.0, 2.4, 1.2, 1.2, 2.4, 3.0, },
                            new double[] { 3.0, 2.7, 1.7, 1.7, 2.7, 3.0, },
                            new double[] { 3.0, 2.9, 2.5, 2.5, 2.9, 3.0, },
                            new double[] { 3.0, 3.0, 3.0, 3.0, 3.0, 3.0, },
                        },
                    };
                    ChartUpdater.UpdateChart(wDoc, "Chart3", chart3Data);

                    var chart4Data = new ChartData
                    {
                        SeriesNames = new[] {
                            "Car",
                            "Truck",
                            "Van",
                        },
                        CategoryDataType   = ChartDataType.DateTime,
                        CategoryFormatCode = 14,
                        CategoryNames      = new[] {
                            ToExcelInteger(new DateTime(2013, 9, 1)),
                            ToExcelInteger(new DateTime(2013, 9, 2)),
                            ToExcelInteger(new DateTime(2013, 9, 3)),
                            ToExcelInteger(new DateTime(2013, 9, 4)),
                            ToExcelInteger(new DateTime(2013, 9, 5)),
                            ToExcelInteger(new DateTime(2013, 9, 6)),
                            ToExcelInteger(new DateTime(2013, 9, 7)),
                            ToExcelInteger(new DateTime(2013, 9, 8)),
                            ToExcelInteger(new DateTime(2013, 9, 9)),
                            ToExcelInteger(new DateTime(2013, 9, 10)),
                            ToExcelInteger(new DateTime(2013, 9, 11)),
                            ToExcelInteger(new DateTime(2013, 9, 12)),
                            ToExcelInteger(new DateTime(2013, 9, 13)),
                            ToExcelInteger(new DateTime(2013, 9, 14)),
                            ToExcelInteger(new DateTime(2013, 9, 15)),
                            ToExcelInteger(new DateTime(2013, 9, 16)),
                            ToExcelInteger(new DateTime(2013, 9, 17)),
                            ToExcelInteger(new DateTime(2013, 9, 18)),
                            ToExcelInteger(new DateTime(2013, 9, 19)),
                            ToExcelInteger(new DateTime(2013, 9, 20)),
                        },
                        Values = new double[][] {
                            new double[] {
                                1, 2, 3, 2, 3, 4, 5, 4, 5, 6, 5, 4, 5, 6, 7, 8, 7, 8, 8, 9,
                            },
                            new double[] {
                                2, 3, 3, 4, 4, 5, 6, 7, 8, 7, 8, 9, 9, 9, 7, 8, 9, 9, 10, 11,
                            },
                            new double[] {
                                2, 3, 3, 3, 3, 2, 2, 2, 3, 2, 3, 3, 4, 4, 4, 3, 4, 5, 5, 4,
                            },
                        },
                    };
                    ChartUpdater.UpdateChart(wDoc, "Chart4", chart4Data);
                }
            }
            if (templateFile.Extension.ToLower() == ".pptx")
            {
                PmlDocument pmlTemplate = new PmlDocument(templateFile.FullName);

                var afterUpdatingPptx = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, templateFile.Name.Replace(".pptx", "-processed-by-ChartUpdater.pptx")));
                pmlTemplate.SaveAs(afterUpdatingPptx.FullName);

                using (var pDoc = PresentationDocument.Open(afterUpdatingPptx.FullName, true))
                {
                    var chart1Data = new ChartData
                    {
                        SeriesNames = new[] {
                            "Car",
                            "Truck",
                            "Van",
                        },
                        CategoryDataType = ChartDataType.String,
                        CategoryNames    = new[] {
                            "Q1",
                            "Q2",
                            "Q3",
                            "Q4",
                        },
                        Values = new double[][] {
                            new double[] {
                                320, 310, 320, 330,
                            },
                            new double[] {
                                201, 224, 230, 221,
                            },
                            new double[] {
                                180, 200, 220, 230,
                            },
                        },
                    };
                    ChartUpdater.UpdateChart(pDoc, 1, chart1Data);
                }
            }
        }
Beispiel #26
0
        public void DB006_Example_DocumentBuilder01()
        {
            FileInfo      source1 = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "DB006-Source1.docx"));
            FileInfo      source2 = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "DB006-Source2.docx"));
            FileInfo      source3 = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "DB006-Source3.docx"));
            List <Source> sources = null;

            // Create new document from 10 paragraphs starting at paragraph 5 of Source1.docx
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1.FullName), 5, 10, true),
            };
            var out1 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out1.docx"));

            DocumentBuilder.BuildDocument(sources, out1.FullName);
            Validate(out1);

            // Create new document from paragraph 1, and paragraphs 5 through end of Source3.docx.
            // This effectively 'deletes' paragraphs 2-4
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source3.FullName), 0, 1, false),
                new Source(new WmlDocument(source3.FullName), 4, false),
            };
            var out2 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out2.docx"));

            DocumentBuilder.BuildDocument(sources, out2.FullName);
            Validate(out2);

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source1.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1.FullName), true),
                new Source(new WmlDocument(source2.FullName), false),
            };
            var out3 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out3.docx"));

            DocumentBuilder.BuildDocument(sources, out3.FullName);
            Validate(out3);

            // Create a new document that consists of the entirety of Source1.docx and Source2.docx.  Use
            // the section information (headings and footers) from source2.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1.FullName), false),
                new Source(new WmlDocument(source2.FullName), true),
            };
            var out4 = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out4.docx"));

            DocumentBuilder.BuildDocument(sources, out4.FullName);
            Validate(out4);

            // Create a new document that consists of the first 5 paragraphs of Source1.docx and the first
            // five paragraphs of Source2.docx.  This example returns a new WmlDocument, when you then can
            // serialize to a SharePoint document library, or use in some other interesting scenario.
            sources = new List <Source>()
            {
                new Source(new WmlDocument(source1.FullName), 0, 5, false),
                new Source(new WmlDocument(source2.FullName), 0, 5, true),
            };
            WmlDocument wmlOut5 = DocumentBuilder.BuildDocument(sources);
            var         out5    = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, "DB006-Out5.docx"));

            wmlOut5.SaveAs(out5.FullName);  // save it to the file system, but we could just as easily done something
                                            // else with it.
            Validate(out5);
        }
Beispiel #27
0
        public static void HTMLToWord(string filepath, string printData)
        {
            bool s_ProduceAnnotatedHtml = true;


            //var destCssFi = new FileInfo(Path.Combine(destinationDir, sourceHtmlFi.Name.Replace(".html", "-2.css")));
            var destDocxFi = new FileInfo(filepath);

            XElement html = HtmlToWmlReadAsXElement.ReadAsXElement(printData);

            string usedAuthorCss = HtmlToWmlConverter.CleanUpCss((string)html.Descendants().FirstOrDefault(d => d.Name.LocalName.ToLower() == "style"));
            //File.WriteAllText(destCssFi.FullName, usedAuthorCss);

            HtmlToWmlConverterSettings settings = HtmlToWmlConverter.GetDefaultSettings();
            // image references in HTML files contain the path to the subdir that contains the images, so base URI is the name of the directory
            // that contains the HTML files

            string defaultCss = @"html, address,
blockquote,
body, dd, div,
dl, dt, fieldset, form,
frame, frameset,
h1, h2, h3, h4,
h5, h6, noframes,
ol, p, ul, center,
dir, hr, menu, pre { display: block; unicode-bidi: embed }
li { display: list-item }
head { display: none }
table { display: table }
tr { display: table-row }
thead { display: table-header-group }
tbody { display: table-row-group }
tfoot { display: table-footer-group }
col { display: table-column }
colgroup { display: table-column-group }
td, th { display: table-cell }
caption { display: table-caption }
th { font-weight: bolder; text-align: center }
caption { text-align: center }
body { margin: auto; }
h1 { font-size: 2em; margin: auto; }
h2 { font-size: 1.5em; margin: auto; }
h3 { font-size: 1.17em; margin: auto; }
h4, p,
blockquote, ul,
fieldset, form,
ol, dl, dir,
menu { margin: auto }
a { color: blue; }
h5 { font-size: .83em; margin: auto }
h6 { font-size: .75em; margin: auto }
h1, h2, h3, h4,
h5, h6, b,
strong { font-weight: bolder }
blockquote { margin-left: 40px; margin-right: 40px }
i, cite, em,
var, address { font-style: italic }
pre, tt, code,
kbd, samp { font-family: monospace }
pre { white-space: pre }
button, textarea,
input, select { display: inline-block }
big { font-size: 1.17em }
small, sub, sup { font-size: .83em }
sub { vertical-align: sub }
sup { vertical-align: super }
table { border-spacing: 2px; }
thead, tbody,
tfoot { vertical-align: middle }
td, th, tr { vertical-align: inherit }
s, strike, del { text-decoration: line-through }
hr { border: 1px inset }
ol, ul, dir,
menu, dd { margin-left: 40px }
ol { list-style-type: decimal }
ol ul, ul ol,
ul ul, ol ol { margin-top: 0; margin-bottom: 0 }
u, ins { text-decoration: underline }
br:before { content: ""\A""; white-space: pre-line }
center { text-align: center }
:link, :visited { text-decoration: underline }
:focus { outline: thin dotted invert }
/* Begin bidirectionality settings (do not change) */
BDO[DIR=""ltr""] { direction: ltr; unicode-bidi: bidi-override }
BDO[DIR=""rtl""] { direction: rtl; unicode-bidi: bidi-override }
*[DIR=""ltr""] { direction: ltr; unicode-bidi: embed }
*[DIR=""rtl""] { direction: rtl; unicode-bidi: embed }
";

            string userCss = @"";

            WmlDocument doc = HtmlToWmlConverter.ConvertHtmlToWml(defaultCss, usedAuthorCss, userCss, html, settings);

            doc.SaveAs(destDocxFi.FullName);
        }