private static void Main()
        {
            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();

            var templateDoc = new FileInfo("../../TemplateDocument.docx");
            var 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.
            var data = GenerateDataFromDataSource(dataFile);

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

            foreach (var customer in data.Elements("Customer"))
            {
                var assembledDoc = new FileInfo(Path.Combine(tempDi.FullName, string.Format("Letter-{0:0000}.docx", count++)));
                Console.WriteLine(assembledDoc.Name);
                var wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, customer, out var 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);
            }
        }
Example #2
0
        #pragma warning restore CS1998

        public static FieldExtractResult ExtractFields(string templateFileName,
                                                       bool removeCustomProperties = true, IEnumerable <string> keepPropertyNames = null)
        {
            string      newTemplateFileName  = templateFileName + "obj.docx";
            string      outputFile           = templateFileName + "obj.json";
            WmlDocument templateDoc          = new WmlDocument(templateFileName); // just reads the template's bytes into memory (that's all), read-only
            WmlDocument preprocessedTemplate = null;

            byte[] byteArray        = templateDoc.DocumentByteArray;
            var    fieldAccumulator = new FieldAccumulator();

            using (MemoryStream mem = new MemoryStream())
            {
                mem.Write(byteArray, 0, byteArray.Length);                                      // copy template file (binary) into memory -- I guess so the template/file handle isn't held/locked?
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, true)) // read & parse that byte array into OXML document (also in memory)
                {
                    // first, remove all the task panes / web extension parts from the template (if there are any)
                    wordDoc.DeleteParts <WebExTaskpanesPart>(wordDoc.GetPartsOfType <WebExTaskpanesPart>());
                    // next, extract all fields (and thus logic) from the template's content parts
                    ExtractAllTemplateFields(wordDoc, fieldAccumulator, removeCustomProperties, keepPropertyNames);
                }
                preprocessedTemplate = new WmlDocument(newTemplateFileName, mem.ToArray());
            }
            // save the output (even in the case of error, since error messages are in the file)
            preprocessedTemplate.Save();

            using (StreamWriter sw = File.CreateText(outputFile))
            {
                fieldAccumulator.JsonSerialize(sw);
                sw.Close();
            }

            return(new FieldExtractResult(newTemplateFileName, outputFile));
        }
Example #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));
            }
        }
        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);
        }
 protected override void ProcessRecord()
 {
     foreach (var document in AllDocuments("Merge-OpenXmlDocumentCommentCmdlet"))
     {
         try
         {
             if (!(document is WmlDocument))
             {
                 throw new PowerToolsDocumentException("Not a wordprocessing document.");
             }
             if (current == null)
             {
                 current = (WmlDocument)document;
             }
             else
             {
                 current = CommentMerger.MergeComments(current, (WmlDocument)document);
             }
         }
         catch (Exception e)
         {
             WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, document));
         }
     }
 }
Example #6
0
        public void Sample2()
        {
            var templateDoc = new FileInfo(GetFilePath("Sample2/TemplateDocument.docx"));
            var dataFile    = new FileInfo(Path.Combine(TempDir, "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.
            var      numberOfDocumentsToGenerate = 100;
            XElement data = GenerateDataFromDataSource(dataFile, numberOfDocumentsToGenerate);

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

            foreach (var customer in data.Elements("Customer"))
            {
                var assembledDoc = new FileInfo(Path.Combine(TempDir, $"Letter-{count++:0000}.docx"));
                Log.WriteLine("Generating {0}", assembledDoc.Name);
                var wmlAssembledDoc = DocumentAssembler.AssembleDocument(wmlDoc, customer, out var templateError);
                if (templateError)
                {
                    Log.WriteLine("Errors in template.");
                    Log.WriteLine("See {0} to determine the errors in the template.", assembledDoc.Name);
                }
                wmlAssembledDoc.SaveAs(assembledDoc.FullName);

                Log.WriteLine("Converting to HTML {0}", assembledDoc.Name);
                var htmlFileName = ConvertToHtml(assembledDoc.FullName, TempDir);

                Log.WriteLine("Converting back to DOCX {0}", htmlFileName.Name);
                ConvertToDocx(htmlFileName.FullName, TempDir);
            }
        }
        private static void ValidateDocument(WmlDocument wmlToValidate)
        {
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(wmlToValidate.DocumentByteArray, 0, wmlToValidate.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);
                    }
                }
            }
        }
        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);
        }
        public void WC003_Throws(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);
            }

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

            Assert.Throws <OpenXmlPowerToolsException>(() =>
            {
                WmlDocument comparedWml = WmlComparer.Compare(source1Wml, source2Wml, settings);
            });
        }
        //[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);
        }
Example #11
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 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 solarSystemDoc = new WmlDocument("../../../solar-system.docx");

            using var streamDoc = new OpenXmlMemoryStreamDocument(solarSystemDoc);
            using WordprocessingDocument solarSystem = streamDoc.GetWordprocessingDocument();
            XElement root = solarSystem.MainDocumentPart.GetXElement();

            // Get children elements of the <w:body> element, ignoring the w:sectPr element.
            IEnumerable <XElement> q1 = root
                                        .Elements(W.body)
                                        .Elements()
                                        .Where(e => e.Name != W.sectPr);

            // Project collection of tuples containing element and type.
            var q2 = q1.Select(e => new
            {
                Element             = e,
                KeyForGroupAdjacent = e.Name.LocalName switch
                {
                    nameof(W.sdt) => e.Element(W.sdtPr)?.Element(W.tag)?.Attribute(W.val)?.Value,
                    _ => ".NonContentControl"
                }
            });
Example #13
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);
        }
Example #14
0
        #pragma warning restore CS1998

        private static CompileResult TransformTemplate(string originalTemplateFile, string preProcessedTemplateFile)
        {
            string newDocxFilename = originalTemplateFile + "ncc.docx";

            byte[]      byteArray           = File.ReadAllBytes(preProcessedTemplateFile);
            WmlDocument transformedTemplate = null;

            using (MemoryStream memStream = new MemoryStream())
            {
                memStream.Write(byteArray, 0, byteArray.Length);                                      // copy the bytes into an expandable MemoryStream
                using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(memStream, true)) // read & parse that memory stream into an editable OXML document (also in memory)
                {
                    PrepareTemplate(wordDoc);
                }
                transformedTemplate = new WmlDocument(newDocxFilename, memStream.ToArray());
            }
            // delete output file if it already exists (Save() below is supposed to always overwrite, but I just want to be sure)
            if (File.Exists(newDocxFilename))
            {
                File.Delete(newDocxFilename);
            }
            // save the output (even in the case of error, since error messages are in the file)
            transformedTemplate.Save();

            return(new CompileResult(transformedTemplate.FileName, null));
        }
Example #15
0
        public void DA101(string name, string data, bool err)
        {
            var sourceDir    = new DirectoryInfo("../../../../TestFiles/");
            var templateDocx = new FileInfo(Path.Combine(sourceDir.FullName, name));
            var dataFile     = new FileInfo(Path.Combine(sourceDir.FullName, data));

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

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

            afterAssembling.SaveAs(assembledDocx.FullName);

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

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

                Assert.Empty(valErrors);
            }

            Assert.Equal(err, returnedTemplateError);
        }
Example #16
0
        public ValidateResult ValidateDocument(string documentFile)
        {
            bool        hasErrors = false;
            string      errorList;
            WmlDocument doc = new WmlDocument(documentFile); // reads the document's bytes into memory

            byte[] byteArray = doc.DocumentByteArray;
            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(byteArray, 0, byteArray.Length); // copy document file (binary) into memory stream
                using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
                {
                    OpenXmlValidator v = new OpenXmlValidator();
                    var valErrors      = v.Validate(wDoc).Where(ve => !s_ExpectedErrors.Contains(ve.Description));

                    StringBuilder sb = new StringBuilder();
                    foreach (var item in valErrors.Select(r => r.Description).OrderBy(t => t).Distinct())
                    {
                        hasErrors = true;
                        sb.Append(item).Append(Environment.NewLine);
                    }
                    errorList = sb.ToString();
                }
            }
            return(new ValidateResult(hasErrors, errorList));
        }
Example #17
0
        public void Sample()
        {
            var srcDoc = new WmlDocument("../../../Word/Samples/RevisionAccepter/Source1.docx");
            var result = RevisionAccepter.AcceptRevisions(srcDoc);

            result.SaveAs(Path.Combine(TempDir, "Out1.docx"));
        }
        public void MG001(string name)
        {
            DirectoryInfo sourceDir = new DirectoryInfo("../../../../TestFiles/");
            FileInfo      fi        = new FileInfo(Path.Combine(sourceDir.FullName, name));

            MetricsGetterSettings settings = new MetricsGetterSettings()
            {
                IncludeTextInContentControls = false,
                IncludeXlsxTableCellData     = false,
                RetrieveNamespaceList        = true,
                RetrieveContentTypeList      = true,
            };

            var      extension = fi.Extension.ToLower();
            XElement metrics   = null;

            if (Util.IsWordprocessingML(extension))
            {
                WmlDocument wmlDocument = new WmlDocument(fi.FullName);
                metrics = MetricsGetter.GetDocxMetrics(wmlDocument, settings);
            }
            else if (Util.IsSpreadsheetML(extension))
            {
                SmlDocument smlDocument = new SmlDocument(fi.FullName);
                metrics = MetricsGetter.GetXlsxMetrics(smlDocument, settings);
            }
            else if (Util.IsPresentationML(extension))
            {
                PmlDocument pmlDocument = new PmlDocument(fi.FullName);
                metrics = MetricsGetter.GetPptxMetrics(pmlDocument, settings);
            }

            Assert.NotNull(metrics);
        }
        private static void Main()
        {
            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();

            var originalWml             = new WmlDocument("../../Original.docx");
            var 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,
                },
            };
            var settings        = new WmlComparerSettings();
            var consolidatedWml = WmlComparer.Consolidate(
                originalWml,
                revisedDocumentInfoList,
                settings);

            consolidatedWml.SaveAs(Path.Combine(tempDi.FullName, "Consolidated.docx"));
        }
        public void HW003(string name)
        {
            string testDocPrefix = "HW003_";
            var    sourceHtmlFi  = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, name));

            var sourceCopiedToDestHtmlFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, (testDocPrefix + sourceHtmlFi.Name).Replace(".html", "-1-Source.html")));
            var destCssFi       = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, (testDocPrefix + sourceHtmlFi.Name).Replace(".html", "-2.css")));
            var destDocxFi      = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, (testDocPrefix + sourceHtmlFi.Name).Replace(".html", "-3-ConvertedByHtmlToWml.docx")));
            var annotatedHtmlFi = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, (testDocPrefix + sourceHtmlFi.Name).Replace(".html", "-4-Annotated.txt")));

            File.Copy(sourceHtmlFi.FullName, sourceCopiedToDestHtmlFi.FullName);
            XElement html = HtmlToWmlReadAsXElement.ReadAsXElement(sourceCopiedToDestHtmlFi);

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

            File.WriteAllText(destCssFi.FullName, usedAuthorCss);

            HtmlToWmlConverterSettings settings = HtmlToWmlConverter.GetDefaultSettings();

            settings.BaseUriForImages          = Path.Combine(TestUtil.TempDir.FullName);
            settings.DefaultBlockContentMargin = "36pt";

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

            Assert.NotNull(doc);
            if (doc != null)
            {
                SaveValidateAndFormatMainDocPart(destDocxFi, doc);
            }
        }
Example #21
0
        public void Sample2()
        {
            var originalWml             = new WmlDocument(GetFilePath("Sample2/Original.docx"));
            var revisedDocumentInfoList = new List <WmlRevisedDocumentInfo>()
            {
                new()
                {
                    RevisedDocument = new WmlDocument(GetFilePath("Sample2/RevisedByBob.docx")),
                    Revisor         = "Bob",
                    Color           = Color.LightBlue,
                },
                new()
                {
                    RevisedDocument = new WmlDocument(GetFilePath("Sample2/RevisedByMary.docx")),
                    Revisor         = "Mary",
                    Color           = Color.LightYellow,
                },
            };

            var settings        = new WmlComparerSettings();
            var consolidatedWml = WmlComparer.Consolidate(
                originalWml,
                revisedDocumentInfoList,
                settings);

            consolidatedWml.SaveAs(Path.Combine(TempDir, "Consolidated.docx"));
        }
        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");
        }
Example #23
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.
        }
Example #24
0
 public Source(string fileName, int start, string insertId)
 {
     WmlDocument  = new WmlDocument(fileName);
     Start        = start;
     Count        = int.MaxValue;
     KeepSections = false;
     InsertId     = insertId;
 }
Example #25
0
        public WmlDocument GetDoc()
        {
            XElement dataXML = GenerateXML();

            WmlDocument wmlAssembledDoc = GenerateDoc(dataXML);

            return(wmlAssembledDoc);
        }
Example #26
0
 public Source(string fileName, int start, bool keepSections)
 {
     WmlDocument  = new WmlDocument(fileName);
     Start        = start;
     Count        = int.MaxValue;
     KeepSections = keepSections;
     InsertId     = null;
 }
 /// <summary>
 /// Validate the given <see cref="WmlDocument" />, using the <see cref="OpenXmlValidator" />.
 /// </summary>
 /// <param name="wmlDocument">The <see cref="WmlDocument" />.</param>
 protected static void Validate(WmlDocument wmlDocument)
 {
     using (var memoryStreamDocument = new OpenXmlMemoryStreamDocument(wmlDocument))
         using (WordprocessingDocument wordDocument = memoryStreamDocument.GetWordprocessingDocument())
         {
             Validate(wordDocument);
         }
 }
Example #28
0
 public Source(WmlDocument source, int start, bool keepSections)
 {
     WmlDocument  = source;
     Start        = start;
     Count        = int.MaxValue;
     KeepSections = keepSections;
     InsertId     = null;
 }
Example #29
0
        public ActionResult Download(string ownerName, string description, string version, string[] SelectedServers)
        {
            var gmud = new Gmud(Server.MapPath("\\Files\\ScriptTemplate.docx"), SelectedServers, ownerName, description, version);

            WmlDocument wmlAssembledDoc = gmud.GetDoc();

            return(File(wmlAssembledDoc.DocumentByteArray, System.Net.Mime.MediaTypeNames.Application.Octet, "GMUD.docx"));
        }
Example #30
0
 public Source(WmlDocument source, string insertId)
 {
     WmlDocument  = source;
     Start        = 0;
     Count        = int.MaxValue;
     KeepSections = false;
     InsertId     = insertId;
 }
 protected override void ProcessRecord()
 {
     foreach (var document in AllDocuments("Merge-OpenXmlDocumentCommentCmdlet"))
     {
         try
         {
             if (!(document is WmlDocument))
                 throw new PowerToolsDocumentException("Not a wordprocessing document.");
             if (current == null)
                 current = (WmlDocument)document;
             else
                 current = CommentMerger.MergeComments(current, (WmlDocument)document);
         }
         catch (Exception e)
         {
             WriteError(PowerToolsExceptionHandling.GetExceptionErrorRecord(e, document));
         }
     }
 }