Пример #1
0
        public string Convert(string filePath)
        {
            var sb = new StringBuilder();

            try
            {
                using (PresentationDocument document = PresentationDocument.Open(filePath, false))
                {
                    if (document == null)
                    {
                        throw new ArgumentNullException("presentationDocument doesn't exist or unreadable.");
                    }

                    this.ExtractTextFromPresentation(document, sb);
                }
            }
            catch (Exception exception)
            {
                Console.WriteLine(exception.Message);
            }

            return(sb.ToString());
        }
Пример #2
0
        public void CanDoFileBasedClone()
        {
            // Test WordprocessingDocument.
            using (var source = WordprocessingDocument.Open(DocumentPath, false))
                using (source.Clone(DocumentPath + ".File.docx", false))
                {
                    CheckWordprocessingDocument(DocumentPath, DocumentPath + ".File.docx");
                }

            // Test SpreadsheetDocument.
            using (var source = SpreadsheetDocument.Open(SpreadsheetPath, false))
                using (source.Clone(SpreadsheetPath + ".File.xlsx", false))
                {
                    CheckSpreadsheetDocument(SpreadsheetPath, SpreadsheetPath + ".File.xlsx");
                }

            // Test PresentationDocument.
            using (var source = PresentationDocument.Open(PresentationPath, false))
                using (source.Clone(PresentationPath + ".File.pptx", false))
                {
                    CheckPresentationDocument(PresentationPath, PresentationPath + ".File.pptx");
                }
        }
Пример #3
0
        public string ReadAll()
        {
            try
            {
                var sb               = new StringBuilder();
                var presentation     = PresentationDocument.Open(_file.FullName, false);
                var presentationPart = presentation.PresentationPart;
                foreach (var slidePart in presentationPart.SlideParts)
                {
                    sb.Append(slidePart.Slide.InnerText);
                    sb.Append(" ");
                }

                presentation.Close();
                return(sb.ToString());
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                SentrySdk.CaptureException(e);
                return(_file.Extension == "" ? _file.Name : _file.Name.Replace(_file.Extension, ""));
            }
        }
Пример #4
0
        /// <summary>
        /// Constructor
        /// Get URI attribute value of PresentationExtension
        /// </summary>
        /// <param name="stream">Generated stream</param>
        public TestEntities(Stream stream)
        {
            using (PresentationDocument package = PresentationDocument.Open(stream, false))
            {
                //Get Extension Uri value. (This element is P15.SlideGuideList parent element.)
                P15.SlideGuideList    slideGuideList = package.PresentationPart.RootElement.Descendants <P15.SlideGuideList>().Single();
                PresentationExtension slideGuidePresentationExtension = (PresentationExtension)slideGuideList.Parent;
                SldExtUri = slideGuidePresentationExtension.Uri;
                if (string.IsNullOrEmpty(SldExtUri))
                {
                    throw new Exception("Uri attribute value in Extension element is not set. It element of P15.SlideGuideList parent element.");
                }

                //Get Extension Uri value. (This element is P15.SlideGuideList parent element.)
                P15.NotesGuideList    notesGuideList = package.PresentationPart.RootElement.Descendants <P15.NotesGuideList>().Single();
                PresentationExtension notesGuidePresentationExtension = (PresentationExtension)notesGuideList.Parent;
                NotesExtUri = notesGuidePresentationExtension.Uri;
                if (string.IsNullOrEmpty(NotesExtUri))
                {
                    throw new Exception("Uri attribute value in Extension element is not set. It element of P15.SlideGuideList parent element.");
                }
            }
        }
Пример #5
0
        /// <summary>
        /// Constructor
        /// Get URI attribute value of CommentExtension
        /// </summary>
        /// <param name="filePath">Generated file path</param>
        public TestEntities(string filePath)
        {
            using (PresentationDocument package = PresentationDocument.Open(filePath, false))
            {
                try
                {
                    //Get Extension Uri value
                    Comment           comment          = GetComment(package.PresentationPart.SlideParts, 1);
                    P15.ThreadingInfo threadingInfo    = comment.CommentExtensionList.Descendants <P15.ThreadingInfo>().Single();
                    CommentExtension  commentExtension = (CommentExtension)threadingInfo.Parent;
                    this.ThreadingInfoExtUri = commentExtension.Uri;;

                    if (string.IsNullOrEmpty(ThreadingInfoExtUri))
                    {
                        throw new Exception("Uri attribute value in Extension element is not set.");
                    }
                }
                catch (Exception e)
                {
                    throw e;
                }
            }
        }
Пример #6
0
        public static void ValidateOfficeFile(string fileType, MemoryStream memoryStream)
        {
            // Validate the file by trying to open it.
            // Exception is thrown if it is not valid.
            switch (fileType)
            {
            // Each Office file type has its own *Document class in the OOXML SDK.
            case "Excel":
                using (var spreadsheet = SpreadsheetDocument.Open(memoryStream, true)) { }
                break;

            case "Word":
                using (var doc = WordprocessingDocument.Open(memoryStream, true)) { }
                break;

            case "PowerPoint":
                using (var slidedeck = PresentationDocument.Open(memoryStream, true)) { }
                break;

            default:
                throw new Exception("Only Excel, Word, and PowerPoint files can be validated.");
            }
        }
Пример #7
0
        public void GeneratePOC_Document(string inputPresentationFullPath, string slideImageDirectoryPath, string outputPOCFullPath)
        {
            using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(outputPOCFullPath, WordprocessingDocumentType.Document))
            {
                #region Init Document
                wordDocument.AddMainDocumentPart();
                wordDocument.MainDocumentPart.Document = new Document();
                var body = wordDocument.MainDocumentPart.Document.AppendChild(new Body());
                InitStylesFor(wordDocument);
                #endregion

                using (PresentationDocument inputPresentation = PresentationDocument.Open(inputPresentationFullPath, false))
                {
                    for (int currentSlide = 0; currentSlide < inputPresentation.PresentationPart.SlideParts.Count(); currentSlide++)
                    {
                        #region Read all Text from current slide
                        string[] allTextFromCurrentSlide = GetAllTextFromSlide(GetSlide(inputPresentation, currentSlide));
                        if (allTextFromCurrentSlide == null)
                        {
                            continue;
                        }
                        #endregion
                        InsertEachParagraphIntoWordDocument(wordDocument, allTextFromCurrentSlide, slideImageDirectoryPath, currentSlide);
                        InsertNotesIntoWordDocument(wordDocument, inputPresentation, currentSlide);
                        #region Insert PageBreak if Slide is not last
                        if (currentSlide != inputPresentation.PresentationPart.SlideParts.Count() - 1)
                        {
                            body.AppendChild(new Paragraph(new Run(new Break()
                            {
                                Type = BreakValues.Page
                            })));
                        }
                        #endregion
                    }
                }
            }
        }
Пример #8
0
        static void Run(string inputFile, string outputFile)
        {
            if (!File.Exists(inputFile))
            {
                throw new FileNotFoundException("FILE NOT FOUND", inputFile);
            }
            if (File.Exists(outputFile))
            {
                throw new InvalidOperationException($"FILE ALRADY EXIST : {outputFile}");
            }

            using var pptx = PresentationDocument.Open(inputFile, false);
            var presentationPart = pptx.PresentationPart;
            var presentation     = presentationPart.Presentation;

            StringBuilder builder = new StringBuilder();

            var sections = presentation.Descendants <Section>();

            foreach (var section in sections)
            {
                var slides = pptx.GetSlides(section).ToList();
                if (!slides.Any())
                {
                    continue;
                }

                builder.AppendLine($"{section.Name} /{pptx.RetrieveNumberOfSlide(slides.First())}");

                foreach (var slide in slides.Where(slide => slide.Show == null || (slide.Show.HasValue && slide.Show.Value)))
                {
                    builder.AppendLine($"\t{slide.GetSlideTitle()} /{pptx.RetrieveNumberOfSlide(slide)}");
                }
            }

            File.WriteAllText(outputFile, builder.ToString(), Encoding.UTF8);
        }
        public void TraversePPTDocument()
        {
            this.MyTestInitialize(TestContext.GetCurrentMethod());
            foreach (var testfile in CopyTestFiles(@"presentation\smallset", false, 3))
            {
                Log.BeginGroup(testfile.Name);
                Log.Comment("open test file {0} for traversing", testfile);
                using (PresentationDocument ppt = PresentationDocument.Open(testfile.FullName, false))
                {
                    Log.Comment("<<<<<<<<<<<<< Traverse PresentationPart >>>>>>>>>>>>");
                    Log.Comment("   <<<<<<< Traverse Down >>>>>>>>");
                    Log.Comment(" <<<<<< traversing Presentation >>>>>>");
                    TestTraverseDown <SlideIdList>(ppt.PresentationPart, ppt.PresentationPart.Presentation);

                    Log.Comment(" <<<<<< traversing SlideIdList >>>>>>");
                    TestTraverseDown <SlideId>(ppt.PresentationPart, ppt.PresentationPart.Presentation.GetFirstChild <SlideIdList>());

                    Log.Comment("   <<<<<<< Traverse Up >>>>>>>>> ");
                    TestTraverseUp <SlideIdList>(ppt.PresentationPart, ppt.PresentationPart.Presentation.LastChild);

                    Log.Comment("  <<<<<< Traverse Sibling  >>>>>>");
                    TestTraverseSibling <SlideIdList>(ppt.PresentationPart, ppt.PresentationPart.Presentation.FirstChild);

                    Log.Comment("<<<<<<<<<<<<< Traverse Non-PresentationPart >>>>>>>>>>>>");
                    Log.Comment("   <<<<<<< Traverse Down >>>>>>>>");
                    Log.Comment(" <<<<<< traversing Slide  >>>>>>");
                    TestTraverseDown <CommonSlideData>(ppt.PresentationPart.SlideParts.First(), ppt.PresentationPart.SlideParts.First().Slide);

                    Log.Comment("   <<<<<<< Traverse Up >>>>>>>>> ");
                    TestTraverseUp <CommonSlideData>(ppt.PresentationPart.SlideParts.First(), ppt.PresentationPart.SlideParts.First().Slide.LastChild);

                    Log.Comment("  <<<<<< Traverse Sibling  >>>>>>");
                    TestTraverseSibling <CommonSlideData>(ppt.PresentationPart.SlideParts.First(), ppt.PresentationPart.SlideParts.First().Slide.FirstChild);
                }
            }
        }
Пример #10
0
        /// <summary>
        /// Opens an existing document
        /// </summary>
        /// <param name="path">file path to open</param>
        /// <param name="enableEdit">open the file in writable mode</param>
        /// <returns>document package</returns>
        protected OpenXmlPackage OpenDocument(Stream stream, bool enableEdit)
        {
            OpenSettings settings = new OpenSettings()
            {
                MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(
                    MarkupCompatibilityProcessMode.ProcessAllParts,
                    DocumentFormat.OpenXml.FileFormatVersions.Office2013)
            };

            if (typeof(TPackage) == typeof(WordprocessingDocument))
            {
                return(WordprocessingDocument.Open(stream, enableEdit, settings));
            }
            else if (typeof(TPackage) == typeof(PresentationDocument))
            {
                return(PresentationDocument.Open(stream, enableEdit, settings));
            }
            else if (typeof(TPackage) == typeof(SpreadsheetDocument))
            {
                return(SpreadsheetDocument.Open(stream, enableEdit, settings));
            }

            throw new ArgumentOutOfRangeException(nameof(TPackage));
        }
Пример #11
0
        public static byte[] ProcessOpenXmlPackage(this WordTemplateEntity template, Action <OpenXmlPackage> processPackage)
        {
            var file = template.Template.Retrieve();

            using (var memory = new MemoryStream())
            {
                memory.WriteAllBytes(file.BinaryFile);

                var ext = Path.GetExtension(file.FileName).ToLower();

                var document =
                    ext == ".docx" ? (OpenXmlPackage)WordprocessingDocument.Open(memory, true) :
                    ext == ".pptx" ? (OpenXmlPackage)PresentationDocument.Open(memory, true) :
                    ext == ".xlsx" ? (OpenXmlPackage)SpreadsheetDocument.Open(memory, true) :
                    throw new InvalidOperationException("Extension '{0}' not supported".FormatWith(ext));

                using (document)
                {
                    processPackage(document);
                }

                return(memory.ToArray());
            }
        }
Пример #12
0
        private void insert(string filePath, List <string> imgList)
        {
            int imgId = 915;
            //Size max = new ImageInfoUtils().listMaxPPTSize(imgList);
            Size max = new ImageInfoUtils().getPPTSize(imgList.First());

            using (PresentationDocument presentationDocument = PresentationDocument.Open(filePath, true))
            {
                PresentationPart presentationPart = presentationDocument.PresentationPart;
                presentationPart.Presentation.SlideSize = new SlideSize()
                {
                    Cx = max.Width, Cy = max.Height, Type = SlideSizeValues.Custom
                };

                foreach (string img in imgList)
                {
                    Slide slide = insertSlide(presentationPart, imgId.ToString());
                    insertImageInLastSlide(slide, max, img, imgId++);
                    slide.Save();
                }

                presentationDocument.PresentationPart.Presentation.Save();
            }
        }
Пример #13
0
        /// <summary>
        /// Open specified existing package.
        /// </summary>
        /// <param name="file">File to be opened.</param>
        /// <param name="writable">Open package in read/write mode if true, false for readonly.</param>
        /// <param name="settings">Settings on AutoSave, MaxCharactersInPart, MarkupCompatibilityProcessSettings and ProcessMCInWholePackage.</param>
        /// <returns>OpenXmlPackage instance for opened package.</returns>
        public static OpenXmlPackage OpenPackage(this FileInfo file, bool writable, OpenSettings settings)
        {
            if (!file.Exists)
            {
                throw new FileNotFoundException(string.Format("Specified file {0} does not exist.", file.Name));
            }

            if (IsWordprocessingFile(file))
            {
                return(WordprocessingDocument.Open(file.FullName, writable, settings));
            }
            else if (IsSpreadsheetFile(file))
            {
                return(SpreadsheetDocument.Open(file.FullName, writable, settings));
            }
            else if (IsPresentationFile(file))
            {
                return(PresentationDocument.Open(file.FullName, writable, settings));
            }
            else
            {
                throw new Exception("Not Supported Document Type!");
            }
        }
Пример #14
0
        public void CreateShapesCollection_Test()
        {
            // ARRANGE
            var ms  = new MemoryStream(Properties.Resources._003);
            var doc = PresentationDocument.Open(ms, false);

            var sdkSldPart  = doc.PresentationPart.SlideParts.First();
            var preSettings = new PreSettings(doc.PresentationPart.Presentation, new Lazy <SlideSize>());
            var parser      = new ShapeFactory(preSettings);

            // ACT
            var candidates = parser.FromSldPart(sdkSldPart);

            // CLEAN
            doc.Dispose();
            ms.Dispose();

            // ASSERT
            Assert.Single(candidates.Where(c => c.ContentType.Equals(ShapeContentType.AutoShape)));
            Assert.Single(candidates.Where(c => c.ContentType.Equals(ShapeContentType.Picture)));
            Assert.Single(candidates.Where(c => c.ContentType.Equals(ShapeContentType.Table)));
            Assert.Single(candidates.Where(c => c.ContentType.Equals(ShapeContentType.Chart)));
            Assert.Single(candidates.Where(c => c.ContentType.Equals(ShapeContentType.Group)));
        }
Пример #15
0
        /// <summary>
        /// Append the chartTrackingReferenceBased element
        /// </summary>
        /// <param name="filePath">Target file path</param>
        /// <param name="log">Logger</param>
        public void AddElements(string filePath, VerifiableLog log)
        {
            using (PresentationDocument package = PresentationDocument.Open(filePath, true))
            {
                try
                {
                    PresentationPropertiesExtension presentationPropertiesExtension = new PresentationPropertiesExtension()
                    {
                        Uri = this.ChartTrackingReferenceBasedExtUri
                    };
                    P15.ChartTrackingReferenceBased chartTrackingReferenceBased = new P15.ChartTrackingReferenceBased();
                    chartTrackingReferenceBased.Val = true;

                    presentationPropertiesExtension.AppendChild <P15.ChartTrackingReferenceBased>(chartTrackingReferenceBased);
                    package.PresentationPart.PresentationPropertiesPart.PresentationProperties.PresentationPropertiesExtensionList.AppendChild <PresentationPropertiesExtension>(presentationPropertiesExtension);

                    log.Pass("Added ChartTrackingReferenceBased element.");
                }
                catch (Exception e)
                {
                    log.Fail(e.Message);
                }
            }
        }
Пример #16
0
        /// <summary>
        /// Verifying PresentationExtensionList element.
        /// </summary>
        /// <param name="filePath">Tartget file path</param>
        /// <param name="log">Logger</param>
        public void VerifyDeletedElement(string filePath, VerifiableLog log)
        {
            using (PresentationDocument package = PresentationDocument.Open(filePath, false))
            {
                try
                {
                    log.Verify(package.PresentationPart.RootElement.Descendants <PresentationExtensionList>().Count() == 0, "Exist PresentationExtensionList element.");

                    log.Verify(package.PresentationPart.RootElement.Descendants <PresentationExtension>().Count() == 0, "Exist PresentationExtension element.");

                    log.Verify(package.PresentationPart.RootElement.Descendants <P15.SlideGuideList>().Count() == 0, "Exist ExtendedGuideList element.");

                    log.Verify(package.PresentationPart.RootElement.Descendants <P15.ExtendedGuide>().Count() == 0, "Exist ExtendedGuide element.");

                    log.Verify(package.PresentationPart.RootElement.Descendants <P15.ColorType>().Count() == 0, "Exist ColorType element.");

                    log.Verify(package.PresentationPart.RootElement.Descendants <A.RgbColorModelHex>().Count() == 0, "Exist RgbColorModelHex element.");
                }
                catch (Exception e)
                {
                    log.Fail(e.Message);
                }
            }
        }
 static void Main(string[] args)
 {
     File.Delete("../../Test01out.pptx");
     File.Copy("../../Test01.pptx", "../../Test01out.pptx");
     using (PresentationDocument pDoc =
                PresentationDocument.Open("../../Test01out.pptx", true))
     {
         TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", true);
     }
     File.Delete("../../Test02out.pptx");
     File.Copy("../../Test02.pptx", "../../Test02out.pptx");
     using (PresentationDocument pDoc =
                PresentationDocument.Open("../../Test02out.pptx", true))
     {
         TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", true);
     }
     File.Delete("../../Test03out.pptx");
     File.Copy("../../Test03.pptx", "../../Test03out.pptx");
     using (PresentationDocument pDoc =
                PresentationDocument.Open("../../Test03out.pptx", true))
     {
         TextReplacer.SearchAndReplace(pDoc, "Hello", "Goodbye", false);
     }
 }
        public ToxySlide Parse(int slideIndex)
        {
            if (!File.Exists(Context.Path))
            {
                throw new FileNotFoundException("File " + Context.Path + " is not found");
            }

            using (PresentationDocument ppt = PresentationDocument.Open(Context.Path, false))
            {
                // Get the relationship ID of the first slide.
                PresentationPart part = ppt.PresentationPart;
                DocumentFormat.OpenXml.OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements;
                if (slideIds.Count - 1 < slideIndex)
                {
                    throw new ArgumentOutOfRangeException(string.Format("This file only contains {0} slide(s).", slideIds.Count));
                }
                string relId = (slideIds[slideIndex] as SlideId).RelationshipId;

                // Get the slide part from the relationship ID.
                SlidePart slide  = (SlidePart)part.GetPartById(relId);
                var       tslide = Parse(slide);
                return(tslide);
            }
        }
Пример #19
0
        //public void ExportToPPT(string folderPath, string themeFilePath)
        //{
        //    string pptFilePath = folderPath + @"\Report.pptx";
        //    if (DocumentFormat.OpenXml.Packaging.Extensions.PowerpointExtensions.CopyPresentation(themeFilePath, pptFilePath))
        //    {
        //        using (PresentationDocument presentationDocument = PresentationDocument.Open(pptFilePath, true))
        //        {
        //            DirectoryInfo imagesDirectory = new DirectoryInfo(folderPath);
        //            foreach (FileInfo file in imagesDirectory.GetFiles("*.png"))
        //            {
        //                Slide slide = presentationDocument.PresentationPart.InsertSlide("Title Only");
        //                Shape shape = slide.CommonSlideData.ShapeTree.Elements<Shape>().FirstOrDefault(
        //                    sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
        //                Picture pic = slide.AddPicture(shape, file.FullName);
        //                slide.CommonSlideData.ShapeTree.RemoveChild<Shape>(shape);
        //                slide.Save();
        //            }
        //            presentationDocument.PresentationPart.Presentation.Save();
        //            presentationDocument.Close();

        //        }
        //    }
        //}

        public void ExportToPPT(string folderPath, string themeFilePath)
        {
            string pptFilePath = folderPath + @"\Report.pptx";

            if (CopyPresentation(themeFilePath, pptFilePath))
            {
                using (PresentationDocument presentationDocument = PresentationDocument.Open(pptFilePath, true))
                {
                    DirectoryInfo imagesDirectory = new DirectoryInfo(folderPath);
                    int           position        = 7;
                    foreach (FileInfo file in imagesDirectory.GetFiles("*.png"))
                    {
                        Slide slide = InsertNewSlide(presentationDocument, position, file.Name);
                        Shape shape = slide.CommonSlideData.ShapeTree.Elements <Shape>().FirstOrDefault(
                            sh => sh.NonVisualShapeProperties.NonVisualDrawingProperties.Name.Value.ToLower().Equals("Content Placeholder 2".ToLower()));
                        Picture pic = slide.AddPicture(shape, file.FullName);
                        slide.CommonSlideData.ShapeTree.RemoveChild <Shape>(shape);
                        slide.Save();
                    }
                    presentationDocument.PresentationPart.Presentation.Save();
                    presentationDocument.Close();
                }
            }
        }
Пример #20
0
        /// <summary>
        /// Verifying PresentationExtensionList element.
        /// </summary>
        /// <param name="filePath">Tartget file path</param>
        /// <param name="log">Logger</param>
        public void VerifyAddedElemenet(string filePath, VerifiableLog log)
        {
            using (PresentationDocument package = PresentationDocument.Open(filePath, false))
            {
                PresentationExtensionList presentationExtensionList = package.PresentationPart.RootElement.Descendants <PresentationExtensionList>().Single();
                log.Verify(package.PresentationPart.RootElement.Descendants <PresentationExtensionList>().Count() == 1, "PresentationExtensionList element not exist.");

                PresentationExtension PresentationExtension1 = presentationExtensionList.Descendants <PresentationExtension>().Where(e => e.Uri == this.SldExtUri).Single();
                log.Verify(PresentationExtension1.Count() == 1, "PresentationExtension element not exist. By SlideGuide.");

                log.Verify(PresentationExtension1.Descendants <P15.SlideGuideList>().Count() == 1, "SlideGuideList element not exist. By SlideGuide.");
                log.Verify(PresentationExtension1.Descendants <P15.ExtendedGuide>().Count() == 1, "ExtendedGuide element not exist. By SlideGuide.");
                log.Verify(PresentationExtension1.Descendants <P15.ColorType>().Count() == 1, "ColorType element not exist. By SlideGuide.");
                log.Verify(PresentationExtension1.Descendants <A.RgbColorModelHex>().Count() == 1, "RgbColorModelHex element not exist. By SlideGuide.");

                PresentationExtension PresentationExtension2 = presentationExtensionList.Descendants <PresentationExtension>().Where(e => e.Uri == this.NotesExtUri).Single();
                log.Verify(PresentationExtension2.Count() == 1, "PresentationExtension element not exist. By NotesGuide.");

                log.Verify(PresentationExtension2.Descendants <P15.NotesGuideList>().Count() == 1, "SlideGuideList element not exist. By NotesGuide.");
                log.Verify(PresentationExtension2.Descendants <P15.ExtendedGuide>().Count() == 1, "ExtendedGuide element not exist. By NotesGuide.");
                log.Verify(PresentationExtension2.Descendants <P15.ColorType>().Count() == 1, "ColorType element not exist. By NotesGuide.");
                log.Verify(PresentationExtension2.Descendants <A.RgbColorModelHex>().Count() == 1, "RgbColorModelHex element not exist. By NotesGuide.");
            }
        }
        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);
                }
            }
        }
        private static void ProcessPowerPointDocument(string outputDocumentFullName, string sourceLanguage, string targetLanguage)
        {
            using (PresentationDocument doc = PresentationDocument.Open(outputDocumentFullName, true))
            {
                //doc.PresentationPart.PutXDocument();

                List <DocumentFormat.OpenXml.Drawing.Text>         texts       = new List <DocumentFormat.OpenXml.Drawing.Text>();
                List <DocumentFormat.OpenXml.Drawing.Text>         notes       = new List <DocumentFormat.OpenXml.Drawing.Text>();
                List <DocumentFormat.OpenXml.Presentation.Comment> lstComments = new List <DocumentFormat.OpenXml.Presentation.Comment>();

                var slideParts = doc.PresentationPart.SlideParts;
                if (slideParts != null)
                {
                    foreach (var slidePart in slideParts)
                    {
                        if (slidePart.Slide != null)
                        {
                            var slide = slidePart.Slide;
                            ExtractTextContent(texts, slide);

                            var commentsPart = slidePart.SlideCommentsPart;
                            if (commentsPart != null)
                            {
                                lstComments.AddRange(commentsPart.CommentList.Cast <DocumentFormat.OpenXml.Presentation.Comment>());
                            }

                            var notesPart = slidePart.NotesSlidePart;
                            if (notesPart != null)
                            {
                                ExtractTextContent(notes, notesPart.NotesSlide);
                            }
                        }
                    }

                    ReplaceTextsWithTranslation(texts, sourceLanguage, targetLanguage);
                    ReplaceTextsWithTranslation(notes, sourceLanguage, targetLanguage);

                    if (lstComments.Count() > 0)
                    {
                        // Extract Text for Translation
                        var batch = lstComments.Select(text => text.InnerText);

                        // Do Translation
                        var batchesComments = SplitList(batch, TranslationServiceFacade.maxelements, TranslationServiceFacade.maxrequestsize);

                        // Use ConcurrentQueue to enable safe enqueueing from multiple threads.
                        var exceptions = new ConcurrentQueue <Exception>();

                        Parallel.For(
                            0,
                            batchesComments.Count(),
                            new ParallelOptions {
                            MaxDegreeOfParallelism = 1
                        },
                            l =>
                        {
                            try
                            {
                                var translationOutput =
                                    TranslationServiceFacade.TranslateArray(
                                        batchesComments[l].ToArray(),
                                        sourceLanguage,
                                        targetLanguage);
                                int batchStartIndexInDocument = 0;
                                for (int i = 0; i < l; i++)
                                {
                                    batchStartIndexInDocument = batchStartIndexInDocument
                                                                + batchesComments[i].Count();
                                }

                                // Apply translated batch to document
                                for (int j = 0; j < translationOutput.Length; j++)
                                {
                                    int indexInDocument = j + batchStartIndexInDocument + 1;
                                    var newValue        = translationOutput[j];
                                    var commentPart     = lstComments.Take(indexInDocument).Last();
                                    commentPart.Text    = new DocumentFormat.OpenXml.Presentation.Text
                                    {
                                        Text = newValue
                                    };
                                }
                            }
                            catch (Exception ex)
                            {
                                exceptions.Enqueue(ex);
                            }
                        });

                        // Throw the exceptions here after the loop completes.
                        if (exceptions.Count > 0)
                        {
                            throw new AggregateException(exceptions);
                        }
                    }
                }

                //doc.PresentationPart.PutXDocument();
            }
        }
        private void ConvertToTransitional(string fileName, byte[] tempByteArray)
        {
            Type type;

            try
            {
                type = GetDocumentType(tempByteArray);
            }
            catch (FileFormatException)
            {
                throw new PowerToolsDocumentException("Not an Open XML document.");
            }

            using (MemoryStream ms = new MemoryStream())
            {
                ms.Write(tempByteArray, 0, tempByteArray.Length);
                if (type == typeof(WordprocessingDocument))
                {
                    using (WordprocessingDocument sDoc = WordprocessingDocument.Open(ms, true))
                    {
                        // following code forces the SDK to serialize
                        foreach (var part in sDoc.Parts)
                        {
                            try
                            {
                                var z = part.OpenXmlPart.RootElement;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
                else if (type == typeof(SpreadsheetDocument))
                {
                    using (SpreadsheetDocument sDoc = SpreadsheetDocument.Open(ms, true))
                    {
                        // following code forces the SDK to serialize
                        foreach (var part in sDoc.Parts)
                        {
                            try
                            {
                                var z = part.OpenXmlPart.RootElement;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
                else if (type == typeof(PresentationDocument))
                {
                    using (PresentationDocument sDoc = PresentationDocument.Open(ms, true))
                    {
                        // following code forces the SDK to serialize
                        foreach (var part in sDoc.Parts)
                        {
                            try
                            {
                                var z = part.OpenXmlPart.RootElement;
                            }
                            catch (Exception)
                            {
                                continue;
                            }
                        }
                    }
                }
                this.FileName     = fileName;
                DocumentByteArray = ms.ToArray();
            }
        }
Пример #24
0
        /// <summary>
        /// Adding PresentationExtensionList element.
        /// </summary>
        /// <param name="filePath">Tartget file path</param>
        /// <param name="log">Logger</param>
        public void AddElement(string filePath, VerifiableLog log)
        {
            using (PresentationDocument package = PresentationDocument.Open(filePath, true))
            {
                //Adding Guide element
                A.RgbColorModelHex rgbColorModelHex1 = new A.RgbColorModelHex()
                {
                    Val = this.Color3
                };
                P15.ColorType     colorType1     = new P15.ColorType();
                P15.ExtendedGuide ExtendedGuide1 = new P15.ExtendedGuide()
                {
                    Id = this.Id3, Position = this.position3, Orientation = this.directionValues2
                };
                P15.SlideGuideList    slideGuideList         = new P15.SlideGuideList();
                PresentationExtension presentationExtension1 = new PresentationExtension()
                {
                    Uri = this.SldExtUri
                };
                PresentationExtensionList presentationExtensionList = new PresentationExtensionList();

                colorType1.AppendChild <A.RgbColorModelHex>(rgbColorModelHex1);
                log.Pass("Added RgbColorModelHex element. It SlideGuideList.");

                ExtendedGuide1.AppendChild <P15.ColorType>(colorType1);
                log.Pass("Added ColorType element. It SlideGuideList.");

                slideGuideList.AppendChild <P15.ExtendedGuide>(ExtendedGuide1);
                log.Pass("Added ExtendedGuide element. It SlideGuideList.");

                presentationExtension1.AppendChild <P15.SlideGuideList>(slideGuideList);
                log.Pass("Added SlideGuideList element. It SlideGuideList.");

                presentationExtensionList.AppendChild <PresentationExtension>(presentationExtension1);
                log.Pass("Added PresentationExtension element. It SlideGuideList.");

                //Adding NotesGuide element
                A.RgbColorModelHex rgbColorModelHex2 = new A.RgbColorModelHex()
                {
                    Val = this.Color4
                };
                P15.ColorType     colorType2     = new P15.ColorType();
                P15.ExtendedGuide ExtendedGuide2 = new P15.ExtendedGuide()
                {
                    Id = this.Id4, Position = this.position4, Orientation = this.directionValues2
                };
                P15.NotesGuideList    NotesGuideList         = new P15.NotesGuideList();
                PresentationExtension presentationExtension2 = new PresentationExtension()
                {
                    Uri = this.NotesExtUri
                };

                colorType2.AppendChild <A.RgbColorModelHex>(rgbColorModelHex2);
                log.Pass("Added RgbColorModelHex element. It SlideGuideList.");

                ExtendedGuide2.AppendChild <P15.ColorType>(colorType2);
                log.Pass("Added ColorType element. It SlideGuideList.");

                NotesGuideList.AppendChild <P15.ExtendedGuide>(ExtendedGuide2);
                log.Pass("Added ExtendedGuide element. It SlideGuideList.");

                presentationExtension2.AppendChild <P15.NotesGuideList>(NotesGuideList);
                log.Pass("Added SlideGuideList element. It SlideGuideList.");

                presentationExtensionList.AppendChild <PresentationExtension>(presentationExtension2);
                log.Pass("Added PresentationExtension element. It SlideGuideList.");

                package.PresentationPart.Presentation.Append(presentationExtensionList);
                log.Pass("Added PresentationExtensionList element. It SlideGuideList.");
            }
        }
Пример #25
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();

            var sourceDi = new DirectoryInfo("../../");

            foreach (var file in sourceDi.GetFiles("*.docx"))
            {
                File.Copy(file.FullName, Path.Combine(tempDi.FullName, file.Name));
            }
            foreach (var file in sourceDi.GetFiles("*.pptx"))
            {
                File.Copy(file.FullName, Path.Combine(tempDi.FullName, file.Name));
            }

            var fileList = Directory.GetFiles(tempDi.FullName, "*.docx");

            foreach (var file in fileList)
            {
                var fi = new FileInfo(file);
                Console.WriteLine(fi.Name);
                var newFileName = "Updated-" + fi.Name;
                var fi2         = new FileInfo(Path.Combine(tempDi.FullName, newFileName));
                File.Copy(fi.FullName, fi2.FullName);

                using (var wDoc = WordprocessingDocument.Open(fi2.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);
                }
            }

            fileList = Directory.GetFiles(tempDi.FullName, "*.pptx");
            foreach (var file in fileList)
            {
                var fi = new FileInfo(file);
                Console.WriteLine(fi.Name);
                var newFileName = "Updated-" + fi.Name;
                var fi2         = new FileInfo(Path.Combine(tempDi.FullName, newFileName));
                File.Copy(fi.FullName, fi2.FullName);

                using (var pDoc = PresentationDocument.Open(fi2.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);
                }
            }
        }
Пример #26
0
        public static string GetCustomProperty(string fileName, string propertyName, string extension)
        {
            string returnValue = null;

            if (extension == ".docx" || extension == ".docm" || extension == ".dotx" || extension == ".dotm" || extension == ".docb")
            {
                using (var document = WordprocessingDocument.Open(fileName, true))
                {
                    var customProps = document.CustomFilePropertiesPart;
                    if (customProps == null)
                    {
                        customProps            = document.AddCustomFilePropertiesPart();
                        customProps.Properties =
                            new DocumentFormat.OpenXml.CustomProperties.Properties();
                    }

                    var props = customProps.Properties;
                    if (props != null)
                    {
                        var prop =
                            props.Where(
                                p => ((CustomDocumentProperty)p).Name.Value
                                == propertyName).FirstOrDefault();

                        if (prop != null)
                        {
                            returnValue = prop.InnerText;
                        }
                    }
                }
                return(returnValue);
            }
            else if (extension == ".xlsx" || extension == ".xlsm" || extension == ".xltx" || extension == ".xltm")
            {
                using (var document = SpreadsheetDocument.Open(fileName, true))
                {
                    var customProps = document.CustomFilePropertiesPart;
                    if (customProps == null)
                    {
                        customProps            = document.AddCustomFilePropertiesPart();
                        customProps.Properties =
                            new DocumentFormat.OpenXml.CustomProperties.Properties();
                    }

                    var props = customProps.Properties;
                    if (props != null)
                    {
                        var prop =
                            props.Where(
                                p => ((CustomDocumentProperty)p).Name.Value
                                == propertyName).FirstOrDefault();

                        if (prop != null)
                        {
                            returnValue = prop.InnerText;
                        }
                    }
                }
                return(returnValue);
            }
            else if (extension == ".pptx" || extension == "pptm" || extension == ".potx" || extension == "potm" || extension == ".ppam" || extension == ".ppsm" || extension == ".sldx" || extension == ".sldm")
            {
                using (var document = PresentationDocument.Open(fileName, true))
                {
                    var customProps = document.CustomFilePropertiesPart;
                    if (customProps == null)
                    {
                        customProps            = document.AddCustomFilePropertiesPart();
                        customProps.Properties =
                            new DocumentFormat.OpenXml.CustomProperties.Properties();
                    }

                    var props = customProps.Properties;
                    if (props != null)
                    {
                        var prop =
                            props.Where(
                                p => ((CustomDocumentProperty)p).Name.Value
                                == propertyName).FirstOrDefault();

                        if (prop != null)
                        {
                            returnValue = prop.InnerText;
                        }
                    }
                }
                return(returnValue);
            }
            return(null);
        }
Пример #27
0
        private static string SetCustomProperty(
            string fileName,
            string propertyName,
            object propertyValue,
            PropertyTypes propertyType,
            string extension)
        {
            string returnValue = null;

            var  newProp = new CustomDocumentProperty();
            bool propSet = false;

            switch (propertyType)
            {
            case PropertyTypes.Text:
                newProp.VTLPWSTR = new VTLPWSTR(propertyValue.ToString());
                propSet          = true;
                break;
            }

            if (!propSet)
            {
                throw new InvalidDataException("propertyValue");
            }

            newProp.FormatId = "{D5CDD505-2E9C-101B-9397-08002B2CF9AE}";
            newProp.Name     = propertyName;

            if (extension == ".docx" || extension == ".docm" || extension == ".dotx" || extension == ".dotm" || extension == ".docb")
            {
                using (var document = WordprocessingDocument.Open(fileName, true))
                {
                    var customProps = document.CustomFilePropertiesPart;
                    if (customProps == null)
                    {
                        customProps            = document.AddCustomFilePropertiesPart();
                        customProps.Properties =
                            new DocumentFormat.OpenXml.CustomProperties.Properties();
                    }

                    var props = customProps.Properties;
                    if (props != null)
                    {
                        var prop =
                            props.Where(
                                p => ((CustomDocumentProperty)p).Name.Value
                                == propertyName).FirstOrDefault();

                        if (prop != null)
                        {
                            returnValue = prop.InnerText;
                            prop.Remove();
                        }

                        props.AppendChild(newProp);
                        int pid = 2;
                        foreach (CustomDocumentProperty item in props)
                        {
                            item.PropertyId = pid++;
                        }
                        props.Save();
                    }
                }
                return(returnValue);
            }
            else if (extension == ".xlsx" || extension == ".xlsm" || extension == ".xltx" || extension == ".xltm")
            {
                using (var document = SpreadsheetDocument.Open(fileName, true))
                {
                    var customProps = document.CustomFilePropertiesPart;
                    if (customProps == null)
                    {
                        customProps            = document.AddCustomFilePropertiesPart();
                        customProps.Properties =
                            new DocumentFormat.OpenXml.CustomProperties.Properties();
                    }

                    var props = customProps.Properties;
                    if (props != null)
                    {
                        var prop =
                            props.Where(
                                p => ((CustomDocumentProperty)p).Name.Value
                                == propertyName).FirstOrDefault();

                        if (prop != null)
                        {
                            returnValue = prop.InnerText;
                            prop.Remove();
                        }

                        props.AppendChild(newProp);
                        int pid = 2;
                        foreach (CustomDocumentProperty item in props)
                        {
                            item.PropertyId = pid++;
                        }
                        props.Save();
                    }
                }
                return(returnValue);
            }
            else if (extension == ".pptx" || extension == "pptm" || extension == ".potx" || extension == "potm" || extension == ".ppam" || extension == ".ppsm" || extension == ".sldx" || extension == ".sldm")
            {
                using (var document = PresentationDocument.Open(fileName, true))
                {
                    var customProps = document.CustomFilePropertiesPart;
                    if (customProps == null)
                    {
                        customProps            = document.AddCustomFilePropertiesPart();
                        customProps.Properties =
                            new DocumentFormat.OpenXml.CustomProperties.Properties();
                    }

                    var props = customProps.Properties;
                    if (props != null)
                    {
                        var prop =
                            props.Where(
                                p => ((CustomDocumentProperty)p).Name.Value
                                == propertyName).FirstOrDefault();

                        if (prop != null)
                        {
                            returnValue = prop.InnerText;
                            prop.Remove();
                        }

                        props.AppendChild(newProp);
                        int pid = 2;
                        foreach (CustomDocumentProperty item in props)
                        {
                            item.PropertyId = pid++;
                        }
                        props.Save();
                    }
                }
                return(returnValue);
            }
            return(null);
        }
Пример #28
0
        public static void Main(string[] args)
        {
            File.Copy(TemplatePath, OutputPath, true);

            using (PresentationDocument presentationDoc = PresentationDocument.Open(OutputPath, true))
            {
                PresentationPart presPart = presentationDoc.PresentationPart;

                // Step 1: Identify the proper Part Id
                SlidePart contentSlidePart = (SlidePart)presPart.GetPartById("rId2");

                // Step 2: Replace one image with external file
                //string imageRel = "rIdImg";
                //int imageRelId = 1;
                //var imgId = imageRel + imageRelId;

                //ImagePart imagePart = contentSlidePart.AddImagePart(ImagePartType.Jpeg, imgId);

                //using (Image image = Image.FromFile(ImagePath))
                //{
                //    using (MemoryStream m = new MemoryStream())
                //    {
                //        image.Save(m, image.RawFormat);
                //        m.Position = 0;
                //        imagePart.FeedData(m);

                //        SwapPhoto(contentSlidePart, imgId);
                //    }
                //}

                // Step 3: Replace text matched by the key
                SwapPlaceholderText(contentSlidePart, "{{Title}}", "Testing Title for IBM");

                // Step 4: Fill out multi value fields by table
                var tupleList = new List <(string category, string model, string price)>
                {
                    ("Automobile", "Ford", "$25K"),
                    ("Automobile", "Toyota", "$30K"),
                    ("Computer", "IBM PC", "$2.5K"),
                    ("Laptop", "Dell", "$1K"),
                    ("Laptop", "Microsoft", "$2K")
                };

                Drawing.Table tbl = contentSlidePart.Slide.Descendants <Drawing.Table>().First();

                foreach (var row in tupleList)
                {
                    Drawing.TableRow tr = new Drawing.TableRow();
                    tr.Height = 100;
                    tr.Append(CreateTextCell(row.category));
                    tr.Append(CreateTextCell(row.model));
                    tr.Append(CreateTextCell(row.price));
                    tbl.Append(tr);
                }

                // Step 5: Save the presentation
                presPart.Presentation.Save();
            }

            CreateHostBuilder(args).Build().Run();
        }
Пример #29
0
        public static void AddImage(string file, string image)
        {
            using (var presentation = PresentationDocument.Open(file, true))
            {
                var slidePart = presentation
                                .PresentationPart
                                .SlideParts
                                .ElementAt(u);
                //.First();

                var part = slidePart
                           .AddImagePart(ImagePartType.Png);

                using (var stream = File.OpenRead(image))
                {
                    part.FeedData(stream);
                }

                var tree = slidePart
                           .Slide
                           .Descendants <DocumentFormat.OpenXml.Presentation.ShapeTree>()
                           .First();

                var picture = new DocumentFormat.OpenXml.Presentation.Picture();

                picture.NonVisualPictureProperties = new DocumentFormat.OpenXml.Presentation.NonVisualPictureProperties();
                picture.NonVisualPictureProperties.Append(new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties
                {
                    Name = "My Shape",
                    Id   = (UInt32)tree.ChildElements.Count - 1
                });

                var nonVisualPictureDrawingProperties = new DocumentFormat.OpenXml.Presentation.NonVisualPictureDrawingProperties();
                nonVisualPictureDrawingProperties.Append(new DocumentFormat.OpenXml.Drawing.PictureLocks()
                {
                    NoChangeAspect = true
                });
                picture.NonVisualPictureProperties.Append(nonVisualPictureDrawingProperties);
                picture.NonVisualPictureProperties.Append(new DocumentFormat.OpenXml.Presentation.ApplicationNonVisualDrawingProperties());

                var blipFill = new DocumentFormat.OpenXml.Presentation.BlipFill();
                var blip1    = new DocumentFormat.OpenXml.Drawing.Blip()
                {
                    Embed = slidePart.GetIdOfPart(part)
                };
                var blipExtensionList1 = new DocumentFormat.OpenXml.Drawing.BlipExtensionList();
                var blipExtension1     = new DocumentFormat.OpenXml.Drawing.BlipExtension()
                {
                    Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
                };
                var useLocalDpi1 = new DocumentFormat.OpenXml.Office2010.Drawing.UseLocalDpi()
                {
                    Val = false
                };
                useLocalDpi1.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
                blipExtension1.Append(useLocalDpi1);
                blipExtensionList1.Append(blipExtension1);
                blip1.Append(blipExtensionList1);
                var stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
                stretch.Append(new DocumentFormat.OpenXml.Drawing.FillRectangle());
                blipFill.Append(blip1);
                blipFill.Append(stretch);
                picture.Append(blipFill);

                picture.ShapeProperties             = new DocumentFormat.OpenXml.Presentation.ShapeProperties();
                picture.ShapeProperties.Transform2D = new DocumentFormat.OpenXml.Drawing.Transform2D();
                picture.ShapeProperties.Transform2D.Append(new DocumentFormat.OpenXml.Drawing.Offset
                {
                    X = 0,
                    Y = 0,
                });
                picture.ShapeProperties.Transform2D.Append(new DocumentFormat.OpenXml.Drawing.Extents
                {
                    Cx = 1000000,
                    Cy = 1000000,
                });
                picture.ShapeProperties.Append(new DocumentFormat.OpenXml.Drawing.PresetGeometry
                {
                    Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle
                });

                tree.Append(picture);
            }
        }
Пример #30
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();

        var sourceDoc = new FileInfo("../../TestDocument.docx");
        var newDoc    = new FileInfo(Path.Combine(tempDi.FullName, "Modified.docx"));

        File.Copy(sourceDoc.FullName, newDoc.FullName);
        using (WordprocessingDocument wDoc = WordprocessingDocument.Open(newDoc.FullName, true))
        {
            int   count;
            var   xDoc = wDoc.MainDocumentPart.GetXDocument();
            Regex regex;
            IEnumerable <XElement> content;

            // Match content (paragraph 1)
            content = xDoc.Descendants(W.p).Take(1);
            regex   = new Regex("Video");
            count   = OpenXmlRegex.Match(content, regex);
            Console.WriteLine("Example #1 Count: {0}", count);

            // Match content, case insensitive (paragraph 1)
            content = xDoc.Descendants(W.p).Take(1);
            regex   = new Regex("video", RegexOptions.IgnoreCase);
            count   = OpenXmlRegex.Match(content, regex);
            Console.WriteLine("Example #2 Count: {0}", count);

            // Match content, with callback (paragraph 1)
            content = xDoc.Descendants(W.p).Take(1);
            regex   = new Regex("video", RegexOptions.IgnoreCase);
            count   = OpenXmlRegex.Match(content, regex, (element, match) =>
                                         Console.WriteLine("Example #3 Found value: >{0}<", match.Value));

            // Replace content, beginning of paragraph (paragraph 2)
            content = xDoc.Descendants(W.p).Skip(1).Take(1);
            regex   = new Regex("^Video provides");
            count   = OpenXmlRegex.Replace(content, regex, "Audio gives", null);
            Console.WriteLine("Example #4 Replaced: {0}", count);

            // Replace content, middle of paragraph (paragraph 3)
            content = xDoc.Descendants(W.p).Skip(2).Take(1);
            regex   = new Regex("powerful");
            count   = OpenXmlRegex.Replace(content, regex, "good", null);
            Console.WriteLine("Example #5 Replaced: {0}", count);

            // Replace content, end of paragraph (paragraph 4)
            content = xDoc.Descendants(W.p).Skip(3).Take(1);
            regex   = new Regex(" [a-z.]*$");
            count   = OpenXmlRegex.Replace(content, regex, " super good point!", null);
            Console.WriteLine("Example #6 Replaced: {0}", count);

            // Delete content, beginning of paragraph (paragraph 5)
            content = xDoc.Descendants(W.p).Skip(4).Take(1);
            regex   = new Regex("^Video provides");
            count   = OpenXmlRegex.Replace(content, regex, "", null);
            Console.WriteLine("Example #7 Deleted: {0}", count);

            // Delete content, middle of paragraph (paragraph 6)
            content = xDoc.Descendants(W.p).Skip(5).Take(1);
            regex   = new Regex("powerful ");
            count   = OpenXmlRegex.Replace(content, regex, "", null);
            Console.WriteLine("Example #8 Deleted: {0}", count);

            // Delete content, end of paragraph (paragraph 7)
            content = xDoc.Descendants(W.p).Skip(6).Take(1);
            regex   = new Regex("[.]$");
            count   = OpenXmlRegex.Replace(content, regex, "", null);
            Console.WriteLine("Example #9 Deleted: {0}", count);

            // Replace content in inserted text, same author (paragraph 8)
            content = xDoc.Descendants(W.p).Skip(7).Take(1);
            regex   = new Regex("Video");
            count   = OpenXmlRegex.Replace(content, regex, "Audio", null, true, "Eric White");
            Console.WriteLine("Example #10 Deleted: {0}", count);

            // Delete content in inserted text, same author (paragraph 9)
            content = xDoc.Descendants(W.p).Skip(8).Take(1);
            regex   = new Regex("powerful ");
            count   = OpenXmlRegex.Replace(content, regex, "", null, true, "Eric White");
            Console.WriteLine("Example #11 Deleted: {0}", count);

            // Replace content partially in inserted text, same author (paragraph 10)
            content = xDoc.Descendants(W.p).Skip(9).Take(1);
            regex   = new Regex("Video provides ");
            count   = OpenXmlRegex.Replace(content, regex, "Audio gives ", null, true, "Eric White");
            Console.WriteLine("Example #12 Replaced: {0}", count);

            // Delete content partially in inserted text, same author (paragraph 11)
            content = xDoc.Descendants(W.p).Skip(10).Take(1);
            regex   = new Regex(" to help you prove your point");
            count   = OpenXmlRegex.Replace(content, regex, "", null, true, "Eric White");
            Console.WriteLine("Example #13 Deleted: {0}", count);

            // Replace content in inserted text, different author (paragraph 12)
            content = xDoc.Descendants(W.p).Skip(11).Take(1);
            regex   = new Regex("Video");
            count   = OpenXmlRegex.Replace(content, regex, "Audio", null, true, "John Doe");
            Console.WriteLine("Example #14 Deleted: {0}", count);

            // Delete content in inserted text, different author (paragraph 13)
            content = xDoc.Descendants(W.p).Skip(12).Take(1);
            regex   = new Regex("powerful ");
            count   = OpenXmlRegex.Replace(content, regex, "", null, true, "John Doe");
            Console.WriteLine("Example #15 Deleted: {0}", count);

            // Replace content partially in inserted text, different author (paragraph 14)
            content = xDoc.Descendants(W.p).Skip(13).Take(1);
            regex   = new Regex("Video provides ");
            count   = OpenXmlRegex.Replace(content, regex, "Audio gives ", null, true, "John Doe");
            Console.WriteLine("Example #16 Replaced: {0}", count);

            // Delete content partially in inserted text, different author (paragraph 15)
            content = xDoc.Descendants(W.p).Skip(14).Take(1);
            regex   = new Regex(" to help you prove your point");
            count   = OpenXmlRegex.Replace(content, regex, "", null, true, "John Doe");
            Console.WriteLine("Example #17 Deleted: {0}", count);

            wDoc.MainDocumentPart.PutXDocument();
        }

        var sourcePres = new FileInfo("../../TestPresentation.pptx");
        var newPres    = new FileInfo(Path.Combine(tempDi.FullName, "Modified.pptx"));

        File.Copy(sourcePres.FullName, newPres.FullName);
        using (PresentationDocument pDoc = PresentationDocument.Open(newPres.FullName, true))
        {
            foreach (var slidePart in pDoc.PresentationPart.SlideParts)
            {
                int   count;
                var   xDoc = slidePart.GetXDocument();
                Regex regex;
                IEnumerable <XElement> content;

                // Replace content
                content = xDoc.Descendants(A.p);
                regex   = new Regex("Hello");
                count   = OpenXmlRegex.Replace(content, regex, "H e l l o", null);
                Console.WriteLine("Example #18 Replaced: {0}", count);

                // If you absolutely want to preserve compatibility with PowerPoint 2007, then you will need to strip the xml:space="preserve" attribute throughout.
                // This is an issue for PowerPoint only, not Word, and for 2007 only.
                // The side-effect of this is that if a run has space at the beginning or end of it, the space will be stripped upon loading, and content/layout will be affected.
                xDoc.Descendants().Attributes(XNamespace.Xml + "space").Remove();

                slidePart.PutXDocument();
            }
        }
    }