示例#1
1
 public void X006_Xlsx_DeleteAdd_CoreExtendedProperties()
 {
     var docName = "Spreadsheet.xlsx";
     var ba = File.ReadAllBytes(s_TestFileLocation + docName);
     using (MemoryStream ms = new MemoryStream())
     {
         ms.Write(ba, 0, ba.Length);
         using (SpreadsheetDocument doc = SpreadsheetDocument.Open(ms, true))
         {
             var corePart = doc.CoreFilePropertiesPart;
             var appPart = doc.ExtendedFilePropertiesPart;
             doc.DeletePart(corePart);
             doc.DeletePart(appPart);
             doc.AddCoreFilePropertiesPart();
             doc.AddExtendedFilePropertiesPart();
             doc.AddCustomFilePropertiesPart();
             doc.AddDigitalSignatureOriginPart();
             doc.AddExtendedPart("relType", "contentType/xml", ".xml");
             var tnPart = doc.AddThumbnailPart(ThumbnailPartType.Jpeg);
             doc.DeletePart(tnPart);
             tnPart = doc.AddThumbnailPart("image/jpg");
             OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
             var errs = v.Validate(doc);
             Assert.Equal(1, errs.Count());
         }
     }
 }
示例#2
0
		public void SingleDivOneEmFontSize()
		{
			using (MemoryStream mem = new MemoryStream())
			{
				WordDocument doc = new WordDocument(mem);
			
				doc.Process(new HtmlParser("<div style='font-size:1em'>test</div>"));
				
				Assert.IsNotNull(doc.Document.Body);
				Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);
				
				Paragraph paragraph = doc.Document.Body.ChildElements[0] as Paragraph;
				
				Run run = paragraph.ChildElements[0] as Run;
				Assert.IsNotNull(run);
				Assert.AreEqual(2, run.ChildElements.Count);
				Assert.IsNotNull(run.RunProperties);
				FontSize fontSize = run.RunProperties.ChildElements[0] as FontSize;
				Assert.AreEqual("24", fontSize.Val.Value);
				
				Word.Text text = run.ChildElements[1] as Word.Text;
				Assert.IsNotNull(text);
				Assert.AreEqual(0, text.ChildElements.Count);
				Assert.AreEqual("test", text.InnerText);
				
				OpenXmlValidator validator = new OpenXmlValidator();
				var errors = validator.Validate(doc.WordprocessingDocument);
				Assert.AreEqual(0, errors.Count());
			}
		}
示例#3
0
		public void SinglePRedColor()
		{
			using (MemoryStream mem = new MemoryStream())
			{
				WordDocument doc = new WordDocument(mem);
			
				doc.Process(new HtmlParser("<p style='color:red'>test</p>"));
				
				Assert.IsNotNull(doc.Document.Body);
				Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);
				
				Paragraph paragraph = doc.Document.Body.ChildElements[0] as Paragraph;
				
				Run run = paragraph.ChildElements[0] as Run;
				Assert.IsNotNull(run);
				Assert.AreEqual(2, run.ChildElements.Count);
				Assert.IsNotNull(run.RunProperties);
				Word.Color color = run.RunProperties.ChildElements[0] as Word.Color;
				Assert.AreEqual("FF0000", color.Val.Value);
				
				Word.Text text = run.ChildElements[1] as Word.Text;
				Assert.IsNotNull(text);
				Assert.AreEqual(0, text.ChildElements.Count);
				Assert.AreEqual("test", text.InnerText);
				
				OpenXmlValidator validator = new OpenXmlValidator();
				var errors = validator.Validate(doc.WordprocessingDocument);
				Assert.AreEqual(0, errors.Count());
			}
		}
		public void SimpleText()
		{
			using (MemoryStream mem = new MemoryStream())
			{
				WordDocument doc = new WordDocument(mem);
			
				doc.Process(new HtmlParser("test"));
				
				Assert.IsNotNull(doc.Document.Body);
				Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);
				
				OpenXmlElement para = doc.Document.Body.ChildElements[0];
				
				Assert.IsTrue(para is Paragraph);
				Assert.AreEqual(1, para.ChildElements.Count);
				
				OpenXmlElement run = para.ChildElements[0];
				Assert.IsTrue(run is Run);
				Assert.AreEqual(1, run.ChildElements.Count);
				
				OpenXmlElement text = run.ChildElements[0] as DocumentFormat.OpenXml.Wordprocessing.Text;
				Assert.IsNotNull(text);
				Assert.AreEqual(0, text.ChildElements.Count);
				Assert.AreEqual("test", text.InnerText);
				
				OpenXmlValidator validator = new OpenXmlValidator();
				var errors = validator.Validate(doc.WordprocessingDocument);
				Assert.AreEqual(0, errors.Count());
			}
		}
        public void MinimumStyle()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);
                doc.Process(new HtmlParser("<div style='font:10px verdana'><div style='font-family:arial'>test</div></div>"));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);

                OpenXmlElement para = doc.Document.Body.ChildElements[0];

                Assert.IsTrue(para is Paragraph);
                Assert.AreEqual(1, para.ChildElements.Count);

                Run run = para.ChildElements[0] as Run;
                Assert.IsNotNull(run);
                Assert.AreEqual(2, run.ChildElements.Count);

                Assert.IsNotNull(run.RunProperties);
                Assert.AreEqual(2, run.RunProperties.ChildElements.Count);
                RunFonts fonts = run.RunProperties.ChildElements[0] as RunFonts;
                Assert.IsNotNull(fonts);
                Assert.AreEqual("arial", fonts.Ascii.Value);

                FontSize fontSize = run.RunProperties.ChildElements[1] as FontSize;
                Assert.IsNotNull(fontSize);
                Assert.AreEqual("20", fontSize.Val.Value);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                Assert.AreEqual(0, errors.Count());
            }
        }
        public void OneSentanceInBody()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser(TestUtility.GetHtmlFromFile("Html\\onesentanceinbody.htm")));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);

                Paragraph para = doc.Document.Body.ChildElements[0] as Paragraph;
                Assert.IsNotNull(para);
                Assert.AreEqual(1, para.ChildElements.Count);

                Run run = para.ChildElements[0] as Run;
                Assert.IsNotNull(run);
                Assert.AreEqual(1, run.ChildElements.Count);

                Word.Text text = run.ChildElements[0] as Word.Text;
                Assert.IsNotNull(text);
                Assert.AreEqual(0, text.ChildElements.Count);
                Assert.AreEqual("This is a test", text.InnerText.Trim());

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                errors.PrintValidationErrors();
                Assert.AreEqual(0, errors.Count());
            }
        }
示例#7
0
		public void DivFontBold()
		{
			using (MemoryStream mem = new MemoryStream())
			{
				WordDocument doc = new WordDocument(mem);
			
				doc.Process(new HtmlParser("<div style='font-weight:bold'>test</div>"));
				
				Assert.IsNotNull(doc.Document.Body);
				Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);
				
				OpenXmlElement para = doc.Document.Body.ChildElements[0];
				
				Assert.IsTrue(para is Paragraph);
				Assert.AreEqual(1, para.ChildElements.Count);
				
				Run run = para.ChildElements[0] as Run;
				Assert.IsNotNull(run);
				Assert.AreEqual(2, run.ChildElements.Count);
				
				Assert.IsNotNull(run.RunProperties);
				Assert.AreEqual(1, run.RunProperties.ChildElements.Count);
				Bold bold = run.RunProperties.ChildElements[0] as Bold;
				Assert.IsNotNull(bold);
				
				Word.Text text = run.ChildElements[1] as Word.Text;
				Assert.IsNotNull(text);
				Assert.AreEqual(0, text.ChildElements.Count);
				Assert.AreEqual("test", text.InnerText);
				
				OpenXmlValidator validator = new OpenXmlValidator();
				var errors = validator.Validate(doc.WordprocessingDocument);
				Assert.AreEqual(0, errors.Count());
			}
		}
示例#8
0
 private static bool ValidateOpenXmlDocument(OpenXmlPackage package )
 {
     string errorDesc = "";
     try
     {
         OpenXmlValidator validator = new OpenXmlValidator();
         int count = 0;
         foreach (ValidationErrorInfo error in validator.Validate(package))
         {
             count++;
             errorDesc += String.Format("Error: {0}", count) + Environment.NewLine;
             errorDesc += String.Format("Description: {0}", error.Description) + Environment.NewLine;
             errorDesc += String.Format("Path: {0}", error.Path.XPath) + Environment.NewLine;
             errorDesc += String.Format("Part: {0}", error.Part.Uri) + Environment.NewLine;
             errorDesc += "-------------------------------------------" + Environment.NewLine;
         }
     }
     catch (Exception ex)
     {
         errorDesc += ex.Message;
     }
     if (!string.IsNullOrEmpty(errorDesc))
     {
         throw new Exception(errorDesc);
     }
     return true;
 }
		public void DivRGBColorRed()
		{
			using (MemoryStream mem = new MemoryStream())
			{
				WordDocument doc = new WordDocument(mem);
			
				doc.Process(new HtmlParser("<div style='color:rgb(255,0,0)'>test</div>"));
				
				Assert.IsNotNull(doc.Document.Body);
				Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);
				
				OpenXmlElement para = doc.Document.Body.ChildElements[0];
				
				Assert.IsTrue(para is Paragraph);
				Assert.AreEqual(1, para.ChildElements.Count);
				
				Run run = para.ChildElements[0] as Run;
				Assert.IsNotNull(run);
				Assert.AreEqual(2, run.ChildElements.Count);
				
				Assert.IsNotNull(run.RunProperties);
				Assert.IsNotNull(run.RunProperties.Color);
				Assert.AreEqual("FF0000", run.RunProperties.Color.Val.Value);
				
				OpenXmlValidator validator = new OpenXmlValidator();
				var errors = validator.Validate(doc.WordprocessingDocument);
				Assert.AreEqual(0, errors.Count());
			}
		}
示例#10
0
 /// <summary>
 /// Validate a word document and return all detected errors
 /// </summary>
 /// <param name="filePath"></param>
 /// <returns></returns>
 public static IEnumerable <ValidationErrorInfo> ValidateWordDocument(string filePath)
 {
     using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(filePath, false))
     {
         var validator = new DocumentFormat.OpenXml.Validation.OpenXmlValidator();
         var errors    = validator.Validate(wordDoc);
         return(errors);
     }
 }
示例#11
0
        /// <summary>
        /// Validates the file and prints result to console
        /// </summary>
        /// <param name="file">Path to the file</param>
        private static bool ValidateFile(string file)
        {
            ConsoleColor color = Console.ForegroundColor;
            bool isValid = false;

            try
            {
                Console.WriteLine("File name: {0}", file);

                OpenXmlValidator validator = new OpenXmlValidator();

                using (var doc = GetOpenXmlPackage(file))
                {
                    var errors = validator.Validate(doc);
                    if (errors.Any())
                    {
                        Console.ForegroundColor = ConsoleColor.Red;
                        Console.WriteLine("Found {0} validation errors: ", errors.Count());

                        int count = 0;
                        foreach (ValidationErrorInfo error in errors)
                        {
                            count++;
                            Console.WriteLine("Error " + count);
                            Console.WriteLine("Part: " + error.Part.Uri);
                            Console.WriteLine("Description: " + error.Description);
                            Console.WriteLine("Path: " + error.Path.XPath);
                        }
                    }
                    else
                    {
                        Console.ForegroundColor = ConsoleColor.Green;
                        Console.WriteLine("Document valid");
                        isValid = true;
                    }

                    Console.WriteLine();
                }
            }
            catch (Exception e)
            {
                Console.ForegroundColor = ConsoleColor.Red;
                Console.WriteLine("Exception occured while validating file: {0} - {1}",e.GetType().ToString() ,e.Message);
            }
            finally
            {
                Console.ForegroundColor = color;
            }

            return isValid;
        }
        public void SimpleUl()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser("<ul><li>test</li></ul>"));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);

                Paragraph para = doc.Document.Body.ChildElements[0] as Paragraph;

                Assert.IsNotNull(para);
                Assert.AreEqual(2, para.ChildElements.Count);

                ParagraphProperties properties = para.ChildElements[0] as ParagraphProperties;
                Assert.IsNotNull(properties);
                Assert.AreEqual(2, properties.ChildElements.Count);
                ParagraphStyleId paragraphStyleId = properties.ChildElements[0] as ParagraphStyleId;
                Assert.IsNotNull(paragraphStyleId);
                Assert.AreEqual("ListParagraph", paragraphStyleId.Val.Value);

                NumberingProperties numberingProperties = properties.ChildElements[1] as NumberingProperties;
                Assert.IsNotNull(numberingProperties);
                Assert.AreEqual(2, numberingProperties.ChildElements.Count);

                NumberingLevelReference numberingLevelReference = numberingProperties.ChildElements[0] as NumberingLevelReference;
                Assert.IsNotNull(numberingLevelReference);
                Assert.AreEqual(0, numberingLevelReference.Val.Value);

                NumberingId numberingId = numberingProperties.ChildElements[1] as NumberingId;
                Assert.IsNotNull(numberingId);
                Assert.AreEqual((Int32)NumberFormatValues.Bullet, numberingId.Val.Value);

                Run run = para.ChildElements[1] as Run;
                Assert.IsNotNull(run);
                Assert.AreEqual(1, run.ChildElements.Count);

                Word.Text text = run.ChildElements[0] as Word.Text;
                Assert.IsNotNull(text);
                Assert.AreEqual("test", text.InnerText);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                Assert.AreEqual(0, errors.Count());
            }
        }
		public void EmptyBody()
		{
			using (MemoryStream mem = new MemoryStream())
			{
				WordDocument doc = new WordDocument(mem);
			
				doc.Process(new HtmlParser("<body></body>"));
				
				Assert.IsNotNull(doc.Document.Body);
				Assert.AreEqual(0, doc.Document.Body.ChildElements.Count);
				
				OpenXmlValidator validator = new OpenXmlValidator();
				var errors = validator.Validate(doc.WordprocessingDocument);
				Assert.AreEqual(0, errors.Count());
			}
		}
示例#14
0
 public void X007_SpreadsheetDocument_Open()
 {
     var fiSource = new FileInfo(Path.Combine(s_TestFileLocation, "Spreadsheet.xlsx"));
     var fiCopy = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, Guid.NewGuid().ToString() + ".xlsx"));
     File.Copy(fiSource.FullName, fiCopy.FullName);
     OpenSettings openSettings = new OpenSettings();
     openSettings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013);
     using (SpreadsheetDocument doc = SpreadsheetDocument.Open(fiCopy.FullName, true, openSettings))
     {
         OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
         var errs = v.Validate(doc);
         Assert.Equal(1, errs.Count());
     }
     if (TestUtil.DeleteTempFiles)
         fiCopy.Delete();
 }
        public void EmptyHtmlBody()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser(TestUtility.GetHtmlFromFile("Html\\emptybody.htm")));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(0, doc.Document.Body.ChildElements.Count);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                errors.PrintValidationErrors();
                Assert.AreEqual(0, errors.Count());
            }
        }
        public void StyleElement()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                string html = "<style type=\"text/css\">.cls{font-size:10px;}</style>";
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser(html));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(0, doc.Document.Body.ChildElements.Count);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                Assert.AreEqual(0, errors.Count());
            }
        }
        public void ScriptElement()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                string html = "<script type=\"text/javascript\">console.log('ok');</script>";
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser(html));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(0, doc.Document.Body.ChildElements.Count);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                Assert.AreEqual(0, errors.Count());
            }
        }
示例#18
0
        public static DocumentValidation Validate(byte[] docByteArray)
        {
            using (MemoryStream mem = new MemoryStream())
            {
                Console.WriteLine((int)docByteArray.Length);
                mem.Write(docByteArray, 0, (int)docByteArray.Length);

                using (WordprocessingDocument wordDoc =
                    WordprocessingDocument.Open(mem, false))
                {

                    var validator = new OpenXmlValidator();
                    var errors = validator.Validate(wordDoc).Select(err => new DocumentError(err));
                    bool valid = !errors.Any();

                    return new DocumentValidation(valid, errors);
                }
            }
        }
示例#19
0
 public void P005_PptxCreation_Package_Settings()
 {
     var fiSource = new FileInfo(Path.Combine(s_TestFileLocation, "Presentation.pptx"));
     var fiCopy = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, Guid.NewGuid().ToString() + ".pptx"));
     File.Copy(fiSource.FullName, fiCopy.FullName);
     using (Package package = Package.Open(fiCopy.FullName, FileMode.Open, FileAccess.ReadWrite))
     {
         OpenSettings openSettings = new OpenSettings();
         openSettings.MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013);
         using (PresentationDocument doc = PresentationDocument.Open(package, openSettings))
         {
             OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
             var errs = v.Validate(doc);
             Assert.Equal(94, errs.Count());
         }
     }
     if (TestUtil.DeleteTempFiles)
         fiCopy.Delete();
 }
示例#20
0
        public void Validator2007BugRegressionTest()
        {
            OpenXmlValidator validator = new OpenXmlValidator(FileFormatVersions.Office2007);

            Bug423998(validator);
            Bug423974(validator);
            Bug424104(validator);
            Bug412116(validator);
            Bug345436(validator);
            Bug403545(validator);
            Bug429396(validator);
            Bug514988(validator);
            Bug448264(validator);
            Bug319778(validator);
            Bug643538(validator);
            Bug669663(validator);
            Bug583585(validator);
            Bug704004(validator);
            Bug743591(validator);
        }
示例#21
0
        static void AssertThatOpenXmlDocumentIsValid(WordprocessingDocument wpDoc)
        {
            var validator = new OpenXmlValidator(FileFormatVersions.Office2010);
            var errors = validator.Validate(wpDoc);

            if (!errors.GetEnumerator().MoveNext())
                return;

            Console.ForegroundColor = ConsoleColor.Red;
            Console.WriteLine("The document doesn't look 100% compatible with Office 2010.\n");

            Console.ForegroundColor = ConsoleColor.Gray;
            foreach (ValidationErrorInfo error in errors)
            {
                Console.Write("{0}\n\t{1}", error.Path.XPath, error.Description);
                Console.WriteLine();
            }

            Console.ReadLine();
        }
示例#22
0
文件: Program.cs 项目: zyayaa/TestXLS
        static void Main(string[] args) {

            try {
                OpenXmlValidator validator = new OpenXmlValidator();
                int count = 0;
                string file = "";
                foreach(ValidationErrorInfo error in validator.Validate(SpreadsheetDocument.Open(@"C:\Users\joao.delgado\Desktop\Reports\" + file + ".xlsx", true))) {
                    count++;
                    Console.WriteLine("Error " + count);
                    Console.WriteLine("Description: " + error.Description);
                    Console.WriteLine("Path: " + error.Path.XPath);
                    Console.WriteLine("Part: " + error.Part.Uri);
                    Console.WriteLine("-------------------------------------------");
                }
                Console.ReadKey();
            } catch(Exception ex) {
                Console.WriteLine(ex.Message);
                Console.ReadKey();
            }
        }
示例#23
0
        public void W054_Load_Save_Strict()
        {
            var fileInfo = new FileInfo(Path.Combine(TestUtil.TempDir.FullName, Guid.NewGuid().ToString() + ".docx"));
            var orig = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, "Strict01.docx"));
            File.Copy(orig.FullName, fileInfo.FullName);

            using (WordprocessingDocument doc =
                WordprocessingDocument.Open(fileInfo.FullName, true))
            {
                W.Body body = doc.MainDocumentPart.Document.Body;
                W.Paragraph para = body.Elements<W.Paragraph>().First();
                var newPara = new W.Paragraph(
                    new W.Run(
                        new W.Text("Test")));
                para.InsertBeforeSelf(newPara);
                OpenXmlValidator v = new OpenXmlValidator(FileFormatVersions.Office2013);
                var errs = v.Validate(doc);
            }
            if (TestUtil.DeleteTempFiles)
                fileInfo.Delete();
        }
    public void CreateSlideShow(string newPresentation,  List<string> imageFileNames)
    {
        //string newPresentation = "DeckFromImages.pptx";
        //string presentationTemplate = "PresentationTemplate.pptx";
        //string presentationFolder = @"C:\Temp\";
        //string imageFolder = @"C:\Temp";
        string[] imageFileExtensions = new[] { "*.jpg", "*.jpeg", "*.gif", "*.bmp", "*.png", "*.tif" };

        // Make a copy of the template presentation. This will throw an exception if the template
        // presentation does not exist.
        File.Copy(presentationTemplate, newPresentation, true);

        // Get the image files in the image folder.

        // Create new slides for the images.
        if (imageFileNames.Count() > 0)
            CreateSlides(imageFileNames, newPresentation);

        // Validate the new presentation.
        OpenXmlValidator validator = new OpenXmlValidator();

        // var errors = validator.Validate(presentationFolder + newPresentation);
        var errors = validator.Validate(PresentationDocument.Open(newPresentation, true));
        if (errors.Count() > 0)
        {
            Console.WriteLine("The deck creation process completed but the created presentation failed to validate.");
            Console.WriteLine("There are " + errors.Count() + " errors:\r\n");

            DisplayValidationErrors(errors);
        }
        else
        {
            Console.WriteLine("The deck creation process completed and the created presentation validated with 0 errors.");
            Utils.OpenPowerPoint(newPresentation);
        }
    }
        public void OwnStyleOverride()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser(TestUtility.GetHtmlFromFile("Html\\ownstyleoverride.htm")));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);

                Paragraph para = doc.Document.Body.ChildElements[0] as Paragraph;
                Assert.IsNotNull(para);
                Assert.AreEqual(1, para.ChildElements.Count);

                Run run = para.ChildElements[0] as Run;
                Assert.IsNotNull(run);
                Assert.AreEqual(2, run.ChildElements.Count);

                RunProperties properties = run.ChildElements[0] as RunProperties;
                Assert.IsNotNull(properties);
                Assert.AreEqual(2, properties.ChildElements.Count);

                Bold bold = properties.ChildElements[0] as Bold;
                Assert.IsNotNull(bold);

                FontSize fontSize = properties.ChildElements[1] as FontSize;
                Assert.IsNotNull(fontSize);
                Assert.AreEqual("46", fontSize.Val.Value);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                errors.PrintValidationErrors();
                Assert.AreEqual(0, errors.Count());
            }
        }
        public void DA101_DocumentAssembler(string templateDocumentName, string dataFileName, bool templateError)
        {
            FileInfo templateDocx = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, templateDocumentName));
            FileInfo dataFile = new FileInfo(Path.Combine(TestUtil.SourceDir.FullName, dataFileName));

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

            bool returnedTemplateError;
            WmlDocument afterAssembling = DocumentAssembler.AssembleDocument(wmlTemplate, data, 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();
#endif

                    Assert.Equal(0, valErrors.Count());
                }
            }

            Assert.Equal(templateError, returnedTemplateError);
        }
示例#27
0
		public void SinglePBackGround()
		{
			using (MemoryStream mem = new MemoryStream())
			{
				WordDocument doc = new WordDocument(mem);
			
				doc.Process(new HtmlParser("<p style='background-color:#000'>test</p>"));
				
				Assert.IsNotNull(doc.Document.Body);
				Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);
				
				Paragraph paragraph = doc.Document.Body.ChildElements[0] as Paragraph;
				Assert.AreEqual(2, paragraph.ChildElements.Count);
				Assert.IsNotNull(paragraph.ParagraphProperties);
				Assert.IsNotNull(paragraph.ParagraphProperties.Shading);
				Assert.AreEqual("000000", paragraph.ParagraphProperties.Shading.Fill.Value);
				Assert.AreEqual(Word.ShadingPatternValues.Clear, paragraph.ParagraphProperties.Shading.Val.Value);
				
				Run run = paragraph.ChildElements[1] as Run;
				Assert.IsNotNull(run);
				Assert.AreEqual(2, run.ChildElements.Count);

                RunProperties runProperties = run.ChildElements[0] as RunProperties;
                Assert.IsNotNull(runProperties);
                Assert.AreEqual("000000", runProperties.Shading.Fill.Value);

				Word.Text text = run.ChildElements[1] as Word.Text;
				Assert.IsNotNull(text);
				Assert.AreEqual(0, text.ChildElements.Count);
				Assert.AreEqual("test", text.InnerText);
				
				OpenXmlValidator validator = new OpenXmlValidator();
				var errors = validator.Validate(doc.WordprocessingDocument);
				Assert.AreEqual(0, errors.Count());
			}
		}
        private void Validate(FileInfo fi)
        {
            using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(fi.FullName, true))
            {
                OpenXmlValidator v = new OpenXmlValidator();
                var errors = v.Validate(sDoc).Where(ve => !s_ExpectedErrors.Contains(ve.Description));

#if false
                // if a test fails validation post-processing, then can use this code to determine the SDK
                // validation error(s).

                if (errors.Count() != 0)
                {
                    StringBuilder sb = new StringBuilder();
                    foreach (var item in errors)
                    {
                        sb.Append(item.Description).Append(Environment.NewLine);
                    }
                    var s = sb.ToString();
                    Console.WriteLine(s);
                }
#endif

                Assert.Equal(0, errors.Count());
            }
        }
示例#29
0
        public static DocumentValidation Validate(string docFileName)
        {
            using (WordprocessingDocument wordDoc =
                WordprocessingDocument.Open(docFileName, false))
            {

                var validator = new OpenXmlValidator();
                var errors = validator.Validate(wordDoc).Select(err => new DocumentError(err));
                bool valid = !errors.Any();

                return new DocumentValidation(valid, errors);
            }
        }
示例#30
0
        public void TableInsideAnotherTable()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser("<table><tr><td><table><tr><td>test</td></tr></table></td></tr></table>"));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);

                Word.Table table = doc.Document.Body.ChildElements[0] as Word.Table;

                Assert.IsNotNull(table);
                Assert.AreEqual(3, table.ChildElements.Count);

                TableRow row = table.ChildElements[2] as TableRow;

                Assert.IsNotNull(row);
                Assert.AreEqual(1, row.ChildElements.Count);

                TableCell cell = row.ChildElements[0] as TableCell;
                Assert.IsNotNull(cell);
                Assert.AreEqual(2, cell.ChildElements.Count);

                table = cell.ChildElements[0] as Word.Table;
                Assert.IsNotNull(table);
                Paragraph para = cell.ChildElements[1] as Paragraph;
                Assert.IsNotNull(para);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                Assert.AreEqual(0, errors.Count());
            }
        }
        public string  BuildPresentation(string parameterList, string UserId)
        {
            GanttChartAutomation.GanttChartDataHelper gantt           = new GanttChartAutomation.GanttChartDataHelper();
            GanttChartAutomation.GanttReportObject    ganttReportData = gantt.GenerateGanttChartReport(parameterList, UserId);

            DateTime startDate, endDate;

            startDate = ganttReportData.StatusDate.AddMonths(-2);
            endDate   = ganttReportData.StatusDate.AddMonths(3);
            ganttReportData.SetExplicitStartEndDate(startDate, endDate);
            _dtStatsDate = ganttReportData.StatusDate;

            IList <GanttChartAutomation.GanttReportObject> ganttChartPages = ganttReportData.PaginateDataWithWeightage(15);

            GanttChartAutomation.GanttReportObject testObject = ganttChartPages[0];


            byte[] fileBytes = PPTTemplate;
            using (MemoryStream stream = new MemoryStream())
            {
                stream.Write(fileBytes, 0, fileBytes.Length);

                using (PresentationDocument presentationDocument = PresentationDocument.Open(stream, true))
                {
                    PresentationPart presentationPart  = presentationDocument.PresentationPart;
                    SlidePart        templateSlidePart = presentationPart.SlideParts.LastOrDefault();
                    SlidePart        slidePart         = presentationPart.SlideParts.FirstOrDefault();


                    SlidePart newSlide;
                    _dtstartDate = ganttChartPages[0].StartDate;
                    _dtendDate   = ganttChartPages[0].EndDate;

                    for (int _intPageCount = 0; _intPageCount < ganttChartPages.Count; _intPageCount++)
                    {
                        bool lblnSlide = false;

                        GanttChartAutomation.GanttReportObject objganttReport = ganttChartPages[_intPageCount];

                        temp = templateSlidePart.Slide.CommonSlideData.ShapeTree.ChildElements.OfType <Shape>().Where(item => (item.NonVisualShapeProperties.NonVisualDrawingProperties.Description != null) && (item.NonVisualShapeProperties.NonVisualDrawingProperties.Description.Value.Equals("PositionBox", StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
                        _shpNofillDiamond = templateSlidePart.Slide.CommonSlideData.ShapeTree.ChildElements.OfType <Shape>().Where(item => (item.NonVisualShapeProperties.NonVisualDrawingProperties.Description != null) && (item.NonVisualShapeProperties.NonVisualDrawingProperties.Description.Value.Equals("NoFillDiamond", StringComparison.OrdinalIgnoreCase))).FirstOrDefault();
                        _intCellWidth     = temp.ShapeProperties.Transform2D.Extents.Cx;
                        getheight(temp.ShapeProperties.Transform2D.Extents.Cy, 15);
                        _intSymbolWidth = _shpNofillDiamond.ShapeProperties.Transform2D.Extents.Cx;
                        newSlide        = CloneSlidePart(presentationPart, templateSlidePart);
                        InitializePosition(newSlide);


                        for (int i = 1; i <= objganttReport.RowCollection.Count; i++)
                        {
                            IList <Xdr.TableCell> cells = rows[i].ChildElements.OfType <Xdr.TableCell>().ToList();
                            _intTaskhaving += objganttReport.RowCollection[i - 1].Weightage;
                            SetCellText(cells[2], objganttReport.RowCollection[i - 1].TaskName.ToString(), objganttReport.RowCollection[i - 1].Weightage, rows[i]);
                            InsertTrend(objganttReport.RowCollection[i - 1].Trend, newSlide, i - 1, objganttReport.RowCollection[i - 1].Weightage);
                            SetCellText(cells[1], objganttReport.RowCollection[i - 1].CpValue == null ? "" : objganttReport.RowCollection[i - 1].CpValue.ToString(), objganttReport.RowCollection[i - 1].Weightage, rows[i]);

                            SetCellText(cells[3], objganttReport.RowCollection[i - 1].RaaValue == null ? "" : objganttReport.RowCollection[i - 1].RaaValue.ToString(), objganttReport.RowCollection[i - 1].Weightage, rows[i]);
                            SetCellText(cells[4], objganttReport.RowCollection[i - 1].BacValue == null ? "" : objganttReport.RowCollection[i - 1].BacValue.ToString(), objganttReport.RowCollection[i - 1].Weightage, rows[i]);
                            SetCellText(cells[5], objganttReport.RowCollection[i - 1].SvValue == null ? "" : objganttReport.RowCollection[i - 1].SvValue.ToString(), objganttReport.RowCollection[i - 1].Weightage, rows[i]);
                            SetShapeCe(cells[6], "", newSlide, objganttReport.RowCollection[i - 1].rowImageDetails, i - 1, objganttReport.RowCollection[i - 1].Weightage);
                            InsertPageDetasils(newSlide, objganttReport);
                            //InsertstatusLine(newSlide);
                        }
                        if (objganttReport.RowCollection.Count < 15)
                        {
                            //_cshpStatsLine.ShapeProperties.Transform2D.Extents.Cx = (_intTaskhaving + 1) * _intcellHeight;
                            //_cshpStatsLine.ShapeProperties.Transform2D.Offset.Y = 3848497;

                            for (int i = objganttReport.RowCollection.Count + 1; i <= 15; i++)
                            {
                                rows[i].Remove();
                            }
                        }
                        _intTaskhaving = -1;

                        RemoveShapePosition(newSlide, presentationPart);
                    }

                    DeleteTemplateSlide(presentationPart, templateSlidePart);


                    xVal.OpenXmlValidator validator = new xVal.OpenXmlValidator();
                    var errors = validator.Validate(presentationDocument).ToList();



                    if (errors.Count == 0)
                    {
                        presentationPart.Presentation.Save();
                    }
                    else
                    {
                        throw new ApplicationException("Error in document.");
                    }
                }

                byte[] presentationFile = stream.ToArray();
                string outputFolder     = @"C:\\ReMICS\\OpenXMLPpt\\";
                if (!System.IO.Directory.Exists(outputFolder))
                {
                    System.IO.Directory.CreateDirectory(outputFolder);
                }

                string newPresentation = outputFolder + "OpenXML-PPT-" + Guid.NewGuid().ToString() + ".pptx";
                File.WriteAllBytes(newPresentation, presentationFile);

                return(newPresentation);
            }
        }
        public void SpanDefault()
        {
            using (MemoryStream mem = new MemoryStream())
            {
                WordDocument doc = new WordDocument(mem);

                doc.Process(new HtmlParser("<span>test</span>"));

                Assert.IsNotNull(doc.Document.Body);
                Assert.AreEqual(1, doc.Document.Body.ChildElements.Count);
                Paragraph para = doc.Document.Body.ChildElements[0] as Paragraph;

                Assert.IsNotNull(para);
                Assert.AreEqual(1, para.ChildElements.Count);

                Run run = para.ChildElements[0] as Run;
                Assert.IsNotNull(run);
                Assert.AreEqual(1, run.ChildElements.Count);
                var text = run.ChildElements[0] as Word.Text;
                Assert.IsNotNull(text);
                Assert.AreEqual("test", text.InnerText);

                OpenXmlValidator validator = new OpenXmlValidator();
                var errors = validator.Validate(doc.WordprocessingDocument);
                Assert.AreEqual(0, errors.Count());
            }
        }