public static void MoveSlide(PresentationDocument presentationDocument, int from, int to) { Repository.Utility.WriteLog("MoveSlide started", System.Diagnostics.EventLogEntryType.Information); if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = CountSlides(presentationDocument); if (from < 0 || from >= slidesCount) throw new ArgumentOutOfRangeException("from"); if (to < 0 || from >= slidesCount || to == from) throw new ArgumentOutOfRangeException("to"); PresentationPart presentationPart = presentationDocument.PresentationPart; Presentation presentation = presentationPart.Presentation; SlideIdList slideIdList = presentation.SlideIdList; SlideId sourceSlide = slideIdList.ChildElements[from] as SlideId; SlideId targetSlide = null; if (to == 0) targetSlide = null; if (from < to) targetSlide = slideIdList.ChildElements[to] as SlideId; else targetSlide = slideIdList.ChildElements[to - 1] as SlideId; sourceSlide.Remove(); slideIdList.InsertAfter(sourceSlide, targetSlide); presentation.Save(); Repository.Utility.WriteLog("MoveSlide completed successfully", System.Diagnostics.EventLogEntryType.Information); }
public static void MoveSlide(PresentationDocument presentationDocument, int from, int to) { if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = CountSlides(presentationDocument); if (from < 0 || from >= slidesCount) throw new ArgumentOutOfRangeException("from"); if (to < 0 || from >= slidesCount || to == from) throw new ArgumentOutOfRangeException("to"); PresentationPart presentationPart = presentationDocument.PresentationPart; Presentation presentation = presentationPart.Presentation; SlideIdList slideIdList = presentation.SlideIdList; SlideId sourceSlide = slideIdList.ChildElements[from] as SlideId; SlideId targetSlide = null; if (to == 0) targetSlide = null; if (from < to) targetSlide = slideIdList.ChildElements[to] as SlideId; else targetSlide = slideIdList.ChildElements[to - 1] as SlideId; sourceSlide.Remove(); slideIdList.InsertAfter(sourceSlide, targetSlide); presentation.Save(); }
// Move a slide to a different position in the slide order in the presentation. public static void MoveSlide(PresentationDocument presentationDocument, int from, int to) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } // Call the CountSlides method to get the number of slides in the presentation. int slidesCount = CountSlides(presentationDocument); // Verify that both from and to positions are within range and different from one another. if (from < 0 || from >= slidesCount) { throw new ArgumentOutOfRangeException("from"); } if (to < 0 || from >= slidesCount || to == from) { throw new ArgumentOutOfRangeException("to"); } // Get the presentation part from the presentation document. PresentationPart presentationPart = presentationDocument.PresentationPart; // The slide count is not zero, so the presentation must contain slides. Presentation presentation = presentationPart.Presentation; SlideIdList slideIdList = presentation.SlideIdList; // Get the slide ID of the source slide. SlideId sourceSlide = slideIdList.ChildElements[from] as SlideId; SlideId targetSlide = null; // Identify the position of the target slide after which to move the source slide. if (to == 0) { targetSlide = null; } if (from < to) { targetSlide = slideIdList.ChildElements[to] as SlideId; } else { targetSlide = slideIdList.ChildElements[to - 1] as SlideId; } // Remove the source slide from its current position. sourceSlide.Remove(); // Insert the source slide at its new position after the target slide. slideIdList.InsertAfter(sourceSlide, targetSlide); // Save the modified presentation. presentation.Save(); }
// Get the slide part of the first slide in the presentation document. public static SlidePart GetFirstSlide(PresentationDocument presentationDocument) { // Get relationship ID of the first slide PresentationPart part = presentationDocument.PresentationPart; SlideId slideId = part.Presentation.SlideIdList.GetFirstChild<SlideId>(); string relId = slideId.RelationshipId; // Get the slide part by the relationship ID. SlidePart slidePart = (SlidePart)part.GetPartById(relId); return slidePart; }
public static string[] GetAllTextInSlide(PresentationDocument presentationDocument, int slideIndex) { // Verify that the presentation document exists. if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } // Verify that the slide index is not out of range. if (slideIndex < 0) { throw new ArgumentOutOfRangeException("slideIndex"); } // Get the presentation part of the presentation document. PresentationPart presentationPart = presentationDocument.PresentationPart; // Verify that the presentation part and presentation exist. if (presentationPart != null && presentationPart.Presentation != null) { // Get the Presentation object from the presentation part. Presentation presentation = presentationPart.Presentation; // Verify that the slide ID list exists. if (presentation.SlideIdList != null) { // Get the collection of slide IDs from the slide ID list. DocumentFormat.OpenXml.OpenXmlElementList slideIds = presentation.SlideIdList.ChildElements; // If the slide ID is in range... if (slideIndex < slideIds.Count) { // Get the relationship ID of the slide. string slidePartRelationshipId = (slideIds[slideIndex] as SlideId).RelationshipId; // Get the specified slide part from the relationship ID. SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId); // Pass the slide part to the next method, and // then return the array of strings that method // returns to the previous method. return GetAllTextInSlide(slidePart); } } } // Else, return null. return null; }
public static int CountSlides(PresentationDocument presentationDocument) { if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = 0; PresentationPart presentationPart = presentationDocument.PresentationPart; if (presentationPart != null) slidesCount = presentationPart.SlideParts.Count(); return slidesCount; }
public static int CountSlides(PresentationDocument presentationDocument) { Repository.Utility.WriteLog("CountSlides started", System.Diagnostics.EventLogEntryType.Information); if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = 0; PresentationPart presentationPart = presentationDocument.PresentationPart; if (presentationPart != null) slidesCount = presentationPart.SlideParts.Count(); Repository.Utility.WriteLog("CountSlides completed successfully", System.Diagnostics.EventLogEntryType.Information); return slidesCount; }
/// <summary> /// Initializes a new instance of the <see cref="Pptx"/> class. /// </summary> /// <param name="stream">The PowerPoint stream.</param> /// <param name="access">Access mode to use to open the PowerPoint file.</param> /// <remarks>Opens a PowerPoint stream in read-write (default) or read only mode.</remarks> public Pptx(Stream stream, FileAccess access) { bool isEditable = false; switch (access) { case FileAccess.Read: isEditable = false; break; case FileAccess.Write: case FileAccess.ReadWrite: isEditable = true; break; } this.presentationDocument = PresentationDocument.Open(stream, isEditable); }
private static int SlidesCount(PresentationDocument document) { document.CheckForNull("presentation"); int slidesCount = 0; PresentationPart presentationPart = document.PresentationPart; if (presentationPart != null) { slidesCount = presentationPart.SlideParts.Count(); } return slidesCount; }
/// <summary> /// Editing ThreadingInfo element /// </summary> /// <param name="filePath">Target Excel file path</param> /// <param name="log">Logger</param> public void EditElements(string filePath, VerifiableLog log) { using (PresentationDocument package = PresentationDocument.Open(filePath, true)) { try { Comment comment = GetComment(package.PresentationPart.SlideParts, 1); P15.ThreadingInfo threadingInfo = comment.CommentExtensionList.Descendants <P15.ThreadingInfo>().Single(); threadingInfo.TimeZoneBias.Value = this.timeZoneBiasValue; log.Pass("Edited ThreadingInfo value."); } catch (Exception e) { log.Fail(e.Message); } } }
private static void SetImageSource(Image image) { ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var presentation = new PresentationDocument(); var slide = presentation.Slides.AddNew(SlideLayoutType.Custom); var textBox = slide.Content.AddTextBox(ShapeGeometryType.Rectangle, 2, 2, 8, 4, LengthUnit.Centimeter); textBox.Shape.Format.Outline.Fill.SetSolid(Color.FromName(ColorName.DarkGray)); var run = textBox.AddParagraph().AddRun("Hello World!"); run.Format.Fill.SetSolid(Color.FromName(ColorName.Black)); image.Source = presentation.ConvertToImageSource(SaveOptions.Image); }
/// <summary> /// Verifying the chartTrackingReferenceBased element the deleting /// </summary> /// <param name="filePath">Target file path</param> /// <param name="log">Logger</param> public void VerifyDeleteElements(string filePath, VerifiableLog log) { using (PresentationDocument package = PresentationDocument.Open(filePath, false)) { try { int chartTrackingReferenceBasedExtCount = package.PresentationPart.PresentationPropertiesPart.PresentationProperties.PresentationPropertiesExtensionList.Descendants <PresentationPropertiesExtension>().Where(e => e.Uri == this.ChartTrackingReferenceBasedExtUri).Count(); log.Verify(chartTrackingReferenceBasedExtCount == 0, "ChartTrackingReferenceBased extension element is not deleted."); int chartTrackingReferenceBasedCount = package.PresentationPart.PresentationPropertiesPart.PresentationProperties.PresentationPropertiesExtensionList.Descendants <P15.ChartTrackingReferenceBased>().Count(); log.Verify(chartTrackingReferenceBasedCount == 0, "ChartTrackingReferenceBased element is not deleted."); } catch (Exception e) { log.Fail(e.Message); } } }
public void P005_PptxCreation_Package_Settings() { using (var stream = GetStream(TestFiles.Presentation)) using (var package = Package.Open(stream)) { var openSettings = new OpenSettings { MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2013), }; using (var doc = PresentationDocument.Open(package, openSettings)) { var v = new OpenXmlValidator(FileFormatVersions.Office2013); Assert.Empty(v.Validate(doc)); } } }
static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); string inputPassword = "******"; string outputPassword = "******"; var presentation = PresentationDocument.Load("PptxEncryption.pptx", new PptxLoadOptions() { Password = inputPassword }); presentation.Save("PPTX Encryption.pptx", new PptxSaveOptions() { Password = outputPassword }); }
public void CanDoStreamBasedCloningPowerpoint() { using (var stream = GetStream(TestFiles.Presentation)) using (var source = PresentationDocument.Open(stream, false)) using (var memoryStream = new MemoryStream()) { using (source.Clone(memoryStream, false)) { } memoryStream.Position = 0; using (var dest = PresentationDocument.Open(memoryStream, false)) { PackageAssert.Equal(source, dest); } } }
/// <summary> /// Gets the titles of all the slides /// </summary> /// <returns></returns> public List <string> GetAllSlideTitles() { var titles = new List <string>(); using (var pDoc = PresentationDocument.Open(_mPath, false)) { if (pDoc.PresentationPart != null) { foreach (var relsId in GetSlideRIds(pDoc)) { SlidePart slidePart = pDoc.PresentationPart.GetPartById(relsId) as SlidePart; titles.Add(GetSlideTitle(slidePart)); } } } return(titles); }
public void Get_Test() { var ms = new MemoryStream(Properties.Resources._008); var xmlDoc = PresentationDocument.Open(ms, false); var sldPart = xmlDoc.PresentationPart.SlideParts.First(); var spId3 = sldPart.Slide.CommonSlideData.ShapeTree.Elements <DocumentFormat.OpenXml.Presentation.Shape>().Single(sp => sp.GetId() == 3); var sldLtPart = sldPart.SlideLayoutPart; var phService = new PlaceholderService(sldLtPart); // ACT var type = phService.TryGet(spId3).PlaceholderType; // CLOSE xmlDoc.Close(); // ASSERT Assert.Equal(PlaceholderType.DateAndTime, type); }
public void SaveDocument(PresentationGenerationData data, string filePath, string fileName) { using (var mem = new MemoryStream()) { using (var package = PresentationDocument.Create(mem, PresentationDocumentType.Presentation, true)) { CreateParts(package, data); } mem.Position = 0; using (var file = new FileStream($"{filePath}\\{fileName}", FileMode.CreateNew, FileAccess.Write)) { mem.CopyTo(file); } } }
public void AddElement_Valid() { PresentationDocument pres = PowerpointHelper.CreatePresentationWithOneEmptySlide("./testFile3.pptx"); ShapeTree shapeTree = PowerpointHelper.GetShapeTreeOfFirstSlide(pres); List <int[]> list = new List <int[]>(); list.Add(new int[] { 1, 2 }); list.Add(new int[] { 3, 4 }); list.Add(new int[] { 5, 6 }); Shape polygon = PowerpointHelper.CreatePolygon(list); PowerpointHelper.AddElement(shapeTree, polygon); var errors = validator.Validate(pres); Assert.IsTrue(errors.Count() == 0); Assert.IsTrue(shapeTree.Count() > 0); }
private WeakReference RunPresentation(OpenXmlValidator validator) { using (var ms = new MemoryStream()) { using (var presentation = PresentationDocument.Create(ms, PresentationDocumentType.Presentation)) { var presentationPart = presentation.AddPresentationPart(); presentationPart.Presentation = new Presentation.Presentation(); } using (var presentation = PresentationDocument.Open(ms, false)) { validator.Validate(presentation); return(new WeakReference(presentation)); } } }
public static IEnumerable <Slide> GetSlides(this PresentationDocument document, Section section) { var presentationPart = document.PresentationPart; var presentation = presentationPart.Presentation; foreach (var entry in section.SectionSlideIdList.Elements <SectionSlideIdListEntry>()) { var slideId = presentation.SlideIdList.Cast <SlideId>().FirstOrDefault(x => x.Id == entry.Id); if (slideId != null) { var slidePart = presentationPart.GetPartById(slideId.RelationshipId) as SlidePart; if (slidePart?.Slide != null) { yield return(slidePart.Slide); } } } }
public void AddImage_Valid() { PresentationDocument pres = PowerpointHelper.CreatePresentationWithOneEmptySlide("./testFileI.pptx"); ShapeTree shapeTree = PowerpointHelper.GetShapeTreeOfFirstSlide(pres); GroupShape groupShape = PowerpointHelper.CreateGroupShape(50, 50, 50, 50); PowerpointHelper.AddElement(shapeTree, groupShape); Bitmap logo = Resx.klee; int oldNbPicture = groupShape.Descendants <Picture>().Count(); using (MemoryStream ms = new MemoryStream()) { logo.Save(ms, System.Drawing.Imaging.ImageFormat.Png); PowerpointHelper.AddImage(groupShape, ms, 50, 50, 50, 50); } Assert.IsTrue(groupShape.Descendants <Picture>().Count() - oldNbPicture == 1); }
public void ReadFromPptx(MemoryStream ms, StringBuilder sb) { try { using (PresentationDocument document = PresentationDocument.Open(ms, false)) { var converter = new PptxToTextConverter(); converter.ExtractTextFromPresentation(document, sb); } } catch (Exception ex) { LogHelper.Error( System.Reflection.MethodBase.GetCurrentMethod().DeclaringType, "Error when try extract zipped pptx file content", ex); } }
private void AutoSaveStream(bool edit, bool save, FileAccess read) { var testfiles = CopyTestFiles(@"bvt") .Where(f => f.IsOpenXmlFile()); foreach (var testfile in testfiles) { string logGroupName = testfile.FullName; Log.BeginGroup(logGroupName); Log.Comment("Opening stream with {0}...", read); Stream st = testfile.Open(FileMode.Open, read); Log.Comment("Opening Package with AutoSave:{0}...", save); if (testfile.IsWordprocessingFile()) { var package = WordprocessingDocument.Open(st, edit, new OpenSettings() { AutoSave = save }); package.MainPart().RootElement.FirstChild.Remove(); package.Close(); } if (testfile.IsSpreadsheetFile()) { var package = SpreadsheetDocument.Open(st, edit, new OpenSettings() { AutoSave = save }); package.MainPart().RootElement.FirstChild.Remove(); package.Close(); } if (testfile.IsPresentationFile()) { var package = PresentationDocument.Open(st, edit, new OpenSettings() { AutoSave = save }); package.MainPart().RootElement.FirstChild.Remove(); package.Close(); } Log.Pass("Package closed without any errors."); } }
private static void processFile(String InputFile) { // copy processing file ProcessingFile procFile = new ProcessingFile(InputFile); //make output file name if (ChoosenOutputFile == null) { if (InputFile.Contains(".")) { ChoosenOutputFile = InputFile.Remove(InputFile.LastIndexOf(".")) + ".pptx"; } else { ChoosenOutputFile = InputFile + ".pptx"; } } //open the reader using (StructuredStorageReader reader = new StructuredStorageReader(procFile.File.FullName)) { // parse the ppt document PowerpointDocument ppt = new PowerpointDocument(reader); // detect document type and name OpenXmlPackage.DocumentType outType = Converter.DetectOutputType(ppt); string conformOutputFile = Converter.GetConformFilename(ChoosenOutputFile, outType); // create the pptx document PresentationDocument pptx = PresentationDocument.Create(conformOutputFile, outType); //start time DateTime start = DateTime.Now; TraceLogger.Info("Converting file {0} into {1}", InputFile, conformOutputFile); // convert Converter.Convert(ppt, pptx); // stop time DateTime end = DateTime.Now; TimeSpan diff = end.Subtract(start); TraceLogger.Info("Conversion of file {0} finished in {1} seconds", InputFile, diff.TotalSeconds.ToString(CultureInfo.InvariantCulture)); } }
/// <summary> /// RetrieveTOC /// </summary> /// <param name="fileStream">stream containing the docx file contents</param> /// <returns>List of DocumentSection objects</returns> public IList <DocumentSection> RetrieveTOC(Stream fileStream, string requestId = "") { _logger.LogInformation($"RequestId: {requestId} - RetrieveTOC called."); try { // Open the presentation as read-only. using (PresentationDocument presentationDocument = PresentationDocument.Open(fileStream, false)) { return(GetSlideTitles(presentationDocument)); } } catch (Exception ex) { _logger.LogError($"RequestId: {requestId} - RetrieveTOC PowerPoint Service Exception: {ex}"); throw new ResponseException($"RequestId: {requestId} - RetrieveTOC PowerPoint Service Exception: {ex}"); } }
private void OpenPackage(FileAccess access, bool edit) // no editable argument needed to Open() Package. { var testfiles = CopyTestFiles(@"bvt") .Where(f => f.IsOpenXmlFile()); foreach (var testfile in testfiles) { Log.BeginGroup(testfile.FullName); Log.Comment("Opening System.IO.Package with FileAccess: {0}...", access); Package p = Package.Open(testfile.FullName, FileMode.Open, access); Log.Comment("Opening SDK Package from System.IO.Package..."); if (testfile.IsWordprocessingFile()) { using (var package = WordprocessingDocument.Open(p)) { package.MainPart().RootElement.FirstChild.Remove(); Log.Comment("AutoSave: {0}", package.AutoSave); Log.Comment("ProcessMode: {0}", package.MarkupCompatibilityProcessSettings.ProcessMode); Log.Comment("FileFormat: {0}", package.MarkupCompatibilityProcessSettings.TargetFileFormatVersions); package.Close(); } } if (testfile.IsSpreadsheetFile()) { using (var package = SpreadsheetDocument.Open(p)) { package.MainPart().RootElement.FirstChild.Remove(); package.Close(); } } if (testfile.IsPresentationFile()) { using (var package = PresentationDocument.Open(p)) { package.MainPart().RootElement.FirstChild.Remove(); package.Close(); } } Log.Pass("Package closed without any error."); } }
public void CanDoPackageBasedCloningPowerpoint() { using (var stream = GetStream(TestFiles.Presentation, true)) using (var source = PresentationDocument.Open(stream, true)) using (var ms = new MemoryStream()) { using (var package = Package.Open(ms, FileMode.Create)) { source.Clone(package).Close(); } ms.Position = 0; using (var destination = PresentationDocument.Open(ms, true)) { PackageAssert.Equal(source, destination); } } }
// Moves a paragraph range in a TextBody shape in the source document // to another TextBody shape in the target document. public static void MoveParagraphToPresentation(string sourceFile, string targetFile) { // Open the source file as read/write. using (PresentationDocument sourceDoc = PresentationDocument.Open(sourceFile, true)) { // Open the target file as read/write. using (PresentationDocument targetDoc = PresentationDocument.Open(targetFile, true)) { // Get the first slide in the source presentation. SlidePart slide1 = GetFirstSlide(sourceDoc); // Get the first TextBody shape in it. TextBody textBody1 = slide1.Slide.Descendants <TextBody>().First(); // Get the first paragraph in the TextBody shape. // Note: "Drawing" is the alias of namespace DocumentFormat.OpenXml.Drawing Drawing.Paragraph p1 = textBody1.Elements <Drawing.Paragraph>().First(); // Get the first slide in the target presentation. SlidePart slide2 = GetFirstSlide(targetDoc); // Get the first TextBody shape in it. TextBody textBody2 = slide2.Slide.Descendants <TextBody>().First(); // Clone the source paragraph and insert the cloned. paragraph into the target TextBody shape. // Passing "true" creates a deep clone, which creates a copy of the // Paragraph object and everything directly or indirectly referenced by that object. textBody2.Append(p1.CloneNode(true)); // Remove the source paragraph from the source file. textBody1.RemoveChild <Drawing.Paragraph>(p1); // Replace the removed paragraph with a placeholder. textBody1.AppendChild <Drawing.Paragraph>(new Drawing.Paragraph()); // Save the slide in the source file. slide1.Slide.Save(); // Save the slide in the target file. slide2.Slide.Save(); } } }
public bool WriteOnSlide() { string filePath = System.Web.HttpContext.Current.Server.MapPath("~/TemplatePPT/Plantilla1.pptx"); try { using (PresentationDocument presentationDocument = PresentationDocument.Open(filePath, true)) { PresentationPart presentationPart = presentationDocument.PresentationPart; Presentation presentation = presentationPart.Presentation; } } catch (Exception ex) { return(false); } return(true); }
static void Main() { // If using Professional version, put your serial key below. ComponentInfo.SetLicense("FREE-LIMITED-KEY"); var presentation = PresentationDocument.Load("Reading.pptx"); string password = "******"; string ownerPassword = ""; var options = new PdfSaveOptions() { DocumentOpenPassword = password, PermissionsPassword = ownerPassword, Permissions = PdfPermissions.None }; presentation.Save("PDF Encryption.pdf", options); }
private static OpenXmlPackage Open(Stream stream, bool isEditable, string path) { path = path.ToLowerInvariant(); if (path.EndsWith(".docx")) { return(WordprocessingDocument.Open(stream, isEditable)); } if (path.EndsWith(".pptx")) { return(PresentationDocument.Open(stream, isEditable)); } if (path.EndsWith(".xlsx")) { return(SpreadsheetDocument.Open(stream, isEditable)); } throw new NotSupportedException(); }
/// <summary> /// Gets the notes of all the slides /// </summary> /// <returns></returns> public List <string> GetAllSlideNotes() { var notes = new List <string>(); using (var pDoc = PresentationDocument.Open(_mPath, false)) { if (pDoc.PresentationPart != null) { List <StringValue> slideRIds = GetSlideRIds(pDoc); foreach (var relsId in slideRIds) { SlidePart slidePart = pDoc.PresentationPart.GetPartById(relsId) as SlidePart; notes.Add(GetSlideNotes(slidePart)); } } } return(notes); }
private static Dictionary <int, string> ExtractText(string source) { Dictionary <int, string> TextContent = new Dictionary <int, string>(); int index = 1; using (PresentationDocument ppt = PresentationDocument.Open(source, false)) { // Get the relationship ID of the first slide. PresentationPart part = ppt.PresentationPart; OpenXmlElementList slideIds = part.Presentation.SlideIdList.ChildElements; foreach (SlideId slideID in slideIds) { //get the right content according to type. for now only text is getting through string relId = slideID.RelationshipId; // Get the slide part from the relationship ID. SlidePart slide = (SlidePart)part.GetPartById(relId); // Build a StringBuilder object. StringBuilder paragraphText = new StringBuilder(); // Get the inner text of the slide: IEnumerable <A.Text> texts = slide.Slide.Descendants <A.Text>(); var videos = slide.Slide.Descendants <Video>(); var videos2 = slide.Slide.CommonSlideData.ShapeTree.Descendants <DocumentFormat.OpenXml.Drawing.VideoFromFile>(); foreach (A.Text text in texts) { if (text.Text.Length > 1) { paragraphText.Append(text.Text + " "); } else { paragraphText.Append(text.Text); } } string slideText = paragraphText.ToString(); TextContent.Add(index, slideText); index++; } } return(TextContent); }
internal static OpenXmlPackage Open(this IFile file, bool isEditable, OpenSettings settings) { if (file.IsWordprocessingFile()) { return(WordprocessingDocument.Open(file.Open(), isEditable, settings)); } else if (file.IsSpreadsheetFile()) { return(SpreadsheetDocument.Open(file.Open(), isEditable, settings)); } else if (file.IsPresentationFile()) { return(PresentationDocument.Open(file.Open(), isEditable, settings)); } else { throw new ArgumentException(); } }
public void Theme01EditAttribute() { string originalFilepath = GetTestFilePath(generateDocumentFilePath); string editFilePath = GetTestFilePath(editDocumentFilePath); System.IO.File.Copy(originalFilepath, editFilePath, true); // Adding ThemeId using (PresentationDocument doc = PresentationDocument.Open(editFilePath, true)) { doc.PresentationPart.SlideMasterParts.First().ThemePart.Theme.ThemeId = new DocumentFormat.OpenXml.StringValue("TEST"); } TestEntities testEntities = new TestEntities(); testEntities.EditAttribute(editFilePath, Log); testEntities.VerifyAttribute(editFilePath, Log); }
public TempData[] ReadFileFromDownloadUriToStream(byte[] data) { try { using (PresentationDocument presentationDocument = PresentationDocument.Open(new MemoryStream(data), false)) { List <TempData> result = new List <TempData>(); PresentationPart part = presentationDocument.PresentationPart; OpenXmlElementList childElements = part.Presentation.SlideIdList.ChildElements; var slideParts = from item in childElements select(SlidePart) part.GetPartById((item as SlideId).RelationshipId); var slideText = from item in slideParts select(WriteToFile.GetSlideText(item)); result.AddRange(TempData.GetTempDataIEnumerable(StorageType.TextType, slideText)); Stream stream = null; byte[] streamByteArr = null; foreach (var slide in slideParts) { result.AddRange(slide.ImageParts.Select(m => { stream = m.GetStream(); streamByteArr = new byte[stream.Length]; stream.Read(streamByteArr, 0, (int)stream.Length); return(new TempData { StorageType = StorageType.ImageType, Data = Convert.ToBase64String(streamByteArr) }); }).ToArray()); } return(result.ToArray()); } } catch (Exception ex) { throw ex; } }
/// <summary> /// Append the ThreadingInfo element /// </summary> public void AddElements(Stream stream, VerifiableLog log) { using (PresentationDocument package = PresentationDocument.Open(stream, true)) { Comment comment = GetComment(package.PresentationPart.SlideParts, 1); CommentExtension commentExtension = new CommentExtension() { Uri = ThreadingInfoExtUri }; P15.ThreadingInfo threadingInfo = new P15.ThreadingInfo() { TimeZoneBias = timeZoneBiasValue }; commentExtension.AppendChild <P15.ThreadingInfo>(threadingInfo); comment.CommentExtensionList.AppendChild <CommentExtension>(commentExtension); log.Pass("Added ThreadingInfo element."); } }
/// <summary> /// Handle client event of Insert button /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void btnInsert_Click(object sender, EventArgs e) { string pptFilePath = txbPPtPath.Text.Trim(); string imagefilePath = txbImagePath.Text.Trim(); string imageExt = Path.GetExtension(imagefilePath); if (imageExt.Equals("jpg", StringComparison.OrdinalIgnoreCase)) { imageExt = "image/jpeg"; } else { imageExt = "image/png"; } bool condition = string.IsNullOrEmpty(pptFilePath) || !File.Exists(pptFilePath) || string.IsNullOrEmpty(imagefilePath) || !File.Exists(imagefilePath); if (condition) { MessageBox.Show("The PowerPoint or iamge file is invalid,Please select an existing file again", "Error", MessageBoxButtons.OK, MessageBoxIcon.Warning); return; } try { using (PresentationDocument presentationDocument = PresentationDocument.Open(pptFilePath, true)) { // Get the presentation Part of the presentation document PresentationPart presentationPart = presentationDocument.PresentationPart; Slide slide = new InsertImage().InsertSlide(presentationPart, "Title Only"); new InsertImage().InsertImageInLastSlide(slide, imagefilePath, imageExt); slide.Save(); presentationDocument.PresentationPart.Presentation.Save(); MessageBox.Show("Insert Image Successfully,you can check with opening PowerPoint"); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } }
// Count the slides in the presentation. public static int CountSlides(PresentationDocument presentationDocument) { // Check for a null document object. if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } int slidesCount = 0; // Get the presentation part of document. PresentationPart presentationPart = presentationDocument.PresentationPart; // Get the slide count from the SlideParts. if (presentationPart != null) { slidesCount = presentationPart.SlideParts.Count(); } // Return the slide count to the previous method. return slidesCount; }
public static void DeleteSlide(PresentationDocument presentationDocument, int slideIndex) { Repository.Utility.WriteLog("DeleteSlide started ", System.Diagnostics.EventLogEntryType.Information); if (presentationDocument == null) throw new ArgumentNullException("presentationDocument"); int slidesCount = CountSlides(presentationDocument); if (slideIndex < 0 || slideIndex >= slidesCount) throw new ArgumentOutOfRangeException("slideIndex"); PresentationPart presentationPart = presentationDocument.PresentationPart; Presentation presentation = presentationPart.Presentation; SlideIdList slideIdList = presentation.SlideIdList; SlideId slideId = slideIdList.ChildElements[slideIndex] as SlideId; string slideRelId = slideId.RelationshipId; slideIdList.RemoveChild(slideId); if (presentation.CustomShowList != null) { foreach (var customShow in presentation.CustomShowList.Elements<CustomShow>()) { if (customShow.SlideList != null) { LinkedList<SlideListEntry> slideListEntries = new LinkedList<SlideListEntry>(); foreach (SlideListEntry slideListEntry in customShow.SlideList.Elements()) if (slideListEntry.Id != null && slideListEntry.Id == slideRelId) slideListEntries.AddLast(slideListEntry); foreach (SlideListEntry slideListEntry in slideListEntries) customShow.SlideList.RemoveChild(slideListEntry); } } } presentation.Save(); SlidePart slidePart = presentationPart.GetPartById(slideRelId) as SlidePart; presentationPart.DeletePart(slidePart); Repository.Utility.WriteLog("DeleteSlide completed successfully ", System.Diagnostics.EventLogEntryType.Information); }
private static Stream PresentationDocumentToStream(PresentationDocument pptxDoc) { MemoryStream mem = new MemoryStream(); using (var resultDoc = PresentationDocument.Create(mem, pptxDoc.DocumentType)) { // copy parts from source document to new document foreach (var part in pptxDoc.Parts) { OpenXmlPart targetPart = resultDoc.AddPart(part.OpenXmlPart, part.RelationshipId); // that's recursive :-) } resultDoc.Package.Flush(); } //resultDoc.Package.Close(); // must do this (or using), or the zip won't get created properly mem.Position = 0; return mem; }
// Get a list of the titles of all the slides in the presentation. public static IList<string> GetSlideTitles(PresentationDocument presentationDocument) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } // Get a PresentationPart object from the PresentationDocument object. PresentationPart presentationPart = presentationDocument.PresentationPart; if (presentationPart != null && presentationPart.Presentation != null) { // Get a Presentation object from the PresentationPart object. Presentation presentation = presentationPart.Presentation; if (presentation.SlideIdList != null) { List<string> titlesList = new List<string>(); // Get the title of each slide in the slide order. foreach (var slideId in presentation.SlideIdList.Elements<SlideId>()) { SlidePart slidePart = presentationPart.GetPartById(slideId.RelationshipId) as SlidePart; // Get the slide title. string title = GetSlideTitle(slidePart); // An empty title can also be added. titlesList.Add(title); } return titlesList; } } return null; }
private static string GetSlideNotes(PresentationDocument document, int index) { var part = document.PresentationPart; var slideIds = part.Presentation.SlideIdList.ChildElements; string notes = null; SlideId slideId = slideIds[index] as SlideId; if (slideId != null) { string relId = slideId.RelationshipId; SlidePart slide = (SlidePart)part.GetPartById(relId); StringBuilder paragraphText = new StringBuilder(); var notesPart = slide.NotesSlidePart; if (slide.NotesSlidePart != null) { var notesSlide = notesPart.NotesSlide; if (notesSlide != null) { var texts = notesSlide.Descendants<Drawing.Text>(); foreach (var text in texts) { paragraphText.Append(text.Text); } notes = paragraphText.ToString(); } } } return notes; }
// Adds child parts and generates content of the specified part. private void CreateParts(PresentationDocument document) { ThumbnailPart thumbnailPart1 = document.AddNewPart<ThumbnailPart>("image/jpeg", "rId2"); GenerateThumbnailPart1Content(thumbnailPart1); PresentationPart presentationPart1 = document.AddPresentationPart(); GeneratePresentationPart1Content(presentationPart1); NotesMasterPart notesMasterPart1 = presentationPart1.AddNewPart<NotesMasterPart>("rId3"); GenerateNotesMasterPart1Content(notesMasterPart1); ThemePart themePart1 = notesMasterPart1.AddNewPart<ThemePart>("rId1"); GenerateThemePart1Content(themePart1); TableStylesPart tableStylesPart1 = presentationPart1.AddNewPart<TableStylesPart>("rId7"); GenerateTableStylesPart1Content(tableStylesPart1); SlidePart slidePart1 = presentationPart1.AddNewPart<SlidePart>("rId2"); GenerateSlidePart1Content(slidePart1); SlideLayoutPart slideLayoutPart1 = slidePart1.AddNewPart<SlideLayoutPart>("rId1"); GenerateSlideLayoutPart1Content(slideLayoutPart1); SlideMasterPart slideMasterPart1 = slideLayoutPart1.AddNewPart<SlideMasterPart>("rId1"); GenerateSlideMasterPart1Content(slideMasterPart1); SlideLayoutPart slideLayoutPart2 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId8"); GenerateSlideLayoutPart2Content(slideLayoutPart2); slideLayoutPart2.AddPart(slideMasterPart1, "rId1"); SlideLayoutPart slideLayoutPart3 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId3"); GenerateSlideLayoutPart3Content(slideLayoutPart3); slideLayoutPart3.AddPart(slideMasterPart1, "rId1"); SlideLayoutPart slideLayoutPart4 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId7"); GenerateSlideLayoutPart4Content(slideLayoutPart4); slideLayoutPart4.AddPart(slideMasterPart1, "rId1"); ThemePart themePart2 = slideMasterPart1.AddNewPart<ThemePart>("rId12"); GenerateThemePart2Content(themePart2); SlideLayoutPart slideLayoutPart5 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId2"); GenerateSlideLayoutPart5Content(slideLayoutPart5); slideLayoutPart5.AddPart(slideMasterPart1, "rId1"); slideMasterPart1.AddPart(slideLayoutPart1, "rId1"); SlideLayoutPart slideLayoutPart6 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId6"); GenerateSlideLayoutPart6Content(slideLayoutPart6); slideLayoutPart6.AddPart(slideMasterPart1, "rId1"); SlideLayoutPart slideLayoutPart7 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId11"); GenerateSlideLayoutPart7Content(slideLayoutPart7); slideLayoutPart7.AddPart(slideMasterPart1, "rId1"); SlideLayoutPart slideLayoutPart8 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId5"); GenerateSlideLayoutPart8Content(slideLayoutPart8); slideLayoutPart8.AddPart(slideMasterPart1, "rId1"); SlideLayoutPart slideLayoutPart9 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId10"); GenerateSlideLayoutPart9Content(slideLayoutPart9); slideLayoutPart9.AddPart(slideMasterPart1, "rId1"); SlideLayoutPart slideLayoutPart10 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId4"); GenerateSlideLayoutPart10Content(slideLayoutPart10); slideLayoutPart10.AddPart(slideMasterPart1, "rId1"); SlideLayoutPart slideLayoutPart11 = slideMasterPart1.AddNewPart<SlideLayoutPart>("rId9"); GenerateSlideLayoutPart11Content(slideLayoutPart11); slideLayoutPart11.AddPart(slideMasterPart1, "rId1"); presentationPart1.AddPart(slideMasterPart1, "rId1"); presentationPart1.AddPart(themePart2, "rId6"); ViewPropertiesPart viewPropertiesPart1 = presentationPart1.AddNewPart<ViewPropertiesPart>("rId5"); GenerateViewPropertiesPart1Content(viewPropertiesPart1); PresentationPropertiesPart presentationPropertiesPart1 = presentationPart1.AddNewPart<PresentationPropertiesPart>("rId4"); GeneratePresentationPropertiesPart1Content(presentationPropertiesPart1); ExtendedFilePropertiesPart extendedFilePropertiesPart1 = document.AddNewPart<ExtendedFilePropertiesPart>("rId4"); GenerateExtendedFilePropertiesPart1Content(extendedFilePropertiesPart1); SetPackageProperties(document); }
private static void BuildPresentation(List<SlideSource> sources, PresentationDocument output) { if (RelationshipMarkup == null) RelationshipMarkup = new Dictionary<XName, XName[]>() { { A.audioFile, new [] { R.link }}, { A.videoFile, new [] { R.link }}, { A.quickTimeFile, new [] { R.link }}, { A.wavAudioFile, new [] { R.embed }}, { A.blip, new [] { R.embed, R.link }}, { A.hlinkClick, new [] { R.id }}, { A.hlinkMouseOver, new [] { R.id }}, { A.hlinkHover, new [] { R.id }}, { A.relIds, new [] { R.cs, R.dm, R.lo, R.qs }}, { C.chart, new [] { R.id }}, { C.externalData, new [] { R.id }}, { C.userShapes, new [] { R.id }}, { DGM.relIds, new [] { R.cs, R.dm, R.lo, R.qs }}, { A14.imgLayer, new [] { R.embed }}, { P14.media, new [] { R.embed, R.link }}, { P.oleObj, new [] { R.id }}, { P.externalData, new [] { R.id }}, { P.control, new [] { R.id }}, { P.snd, new [] { R.embed }}, { P.sndTgt, new [] { R.embed }}, { PAV.srcMedia, new [] { R.embed, R.link }}, { P.contentPart, new [] { R.id }}, { VML.fill, new [] { R.id }}, { VML.imagedata, new [] { R.href, R.id, R.pict, O.relid }}, { VML.stroke, new [] { R.id }}, { WNE.toolbarData, new [] { R.id }}, { Plegacy.textdata, new [] { XName.Get("id") }}, }; List<ImageData> images = new List<ImageData>(); List<MediaData> mediaList = new List<MediaData>(); XDocument mainPart = output.PresentationPart.GetXDocument(); mainPart.Declaration.Standalone = "yes"; mainPart.Declaration.Encoding = "UTF-8"; output.PresentationPart.PutXDocument(); int sourceNum = 0; SlideMasterPart currentMasterPart = null; foreach (SlideSource source in sources) { using (OpenXmlMemoryStreamDocument streamDoc = new OpenXmlMemoryStreamDocument(source.PmlDocument)) using (PresentationDocument doc = streamDoc.GetPresentationDocument()) { try { if (sourceNum == 0) CopyPresentationParts(doc, output, images, mediaList); currentMasterPart = AppendSlides(doc, output, source.Start, source.Count, source.KeepMaster, images, currentMasterPart, mediaList); } catch (PresentationBuilderInternalException dbie) { if (dbie.Message.Contains("{0}")) throw new PresentationBuilderException(string.Format(dbie.Message, sourceNum)); else throw dbie; } } sourceNum++; } foreach (var part in output.GetAllParts()) { if (part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.slide+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.handoutMaster+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.theme+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.drawingml.chart+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml" || part.ContentType == "application/vnd.ms-office.drawingml.diagramDrawing+xml") { XDocument xd = part.GetXDocument(); xd.Descendants().Attributes("smtClean").Remove(); part.PutXDocument(); } else if (part.Annotation<XDocument>() != null) part.PutXDocument(); } }
/// <summary> /// Get the slides in a given section /// </summary> /// <param name="pDoc">the current presentation document</param> /// <param name="section">the section of interest</param> /// <returns>list of integers representating the slides in each section /// the slides are given by their slide number (one-indexed)</returns> private List<int> GetSlidesInSection(PresentationDocument pDoc, Section section) { var slides = new List<int>(); if (section.SectionSlideIdList == null) { return slides; } List<UInt32Value> slideIds = GetSlideIds(pDoc); foreach (SectionSlideIdListEntry slideId in section.SectionSlideIdList) { int index = slideIds.FindIndex(id => id.Value.Equals(slideId.Id.Value)); if (index != -1) { int slideNumber = index + 1; slides.Add(slideNumber); } } return slides; }
public static bool UpdateChart(PresentationDocument pDoc, int slideNumber, ChartData chartData) { var presentationPart = pDoc.PresentationPart; var pXDoc = presentationPart.GetXDocument(); var sldIdElement = pXDoc.Root.Elements(P.sldIdLst).Elements(P.sldId).Skip(slideNumber - 1).FirstOrDefault(); if (sldIdElement != null) { var rId = (string)sldIdElement.Attribute(R.id); var slidePart = presentationPart.GetPartById(rId); var sXDoc = slidePart.GetXDocument(); var chartRid = (string)sXDoc.Descendants(C.chart).Attributes(R.id).FirstOrDefault(); if (chartRid != null) { ChartPart chartPart = (ChartPart)slidePart.GetPartById(chartRid); UpdateChart(chartPart, chartData); return true; } return true; } return false; }
private int GetHBSlideStatus(PresentationDocument presentationDocument, int slideIndex) { int retVal = 0; if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } if (slideIndex < 0) { throw new ArgumentOutOfRangeException("slideIndex"); } PresentationPart presentationPart = presentationDocument.PresentationPart; if (presentationPart != null && presentationPart.Presentation != null) { P.Presentation presentation = presentationPart.Presentation; if (presentation.SlideIdList != null) { OpenXmlElementList slideIds = presentation.SlideIdList.ChildElements; if (slideIndex < slideIds.Count) { string slidePartRelationshipId = (slideIds[slideIndex] as P.SlideId).RelationshipId; SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId); NotesSlidePart notesSlidePart1 = slidePart.NotesSlidePart; if (notesSlidePart1 == null) return 0; P.NotesSlide notesSlide = notesSlidePart1.NotesSlide; P.CommonSlideData csldData = notesSlide.CommonSlideData; P.ShapeTree shpTree = csldData.ShapeTree; P.Shape shp = null; try { shp = shpTree.Elements<P.Shape>().ElementAt(1); } catch { } if(shp==null) { AlternateContent ac= shpTree.Elements<AlternateContent>().ElementAt(0); shp = ac.Elements<AlternateContentFallback>().ElementAt(0).Elements<P.Shape>().ElementAt(0); } P.TextBody tb = shp.Elements<P.TextBody>().ElementAt(0); Drawing.Paragraph para = tb.Elements<Drawing.Paragraph>().ElementAt(0); string tempStr = ""; foreach (Drawing.Run r in para.Elements<Drawing.Run>()) { tempStr += r.InnerText; } if(tempStr.Contains("*hbno*")) { retVal = 2; } else if(tempStr.Contains("*hbyes*")) { retVal = 1; } } } } return retVal; }
// Delete the specified slide from the presentation. public static void DeleteSlide(PresentationDocument presentationDocument, int slideIndex) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } // Use the CountSlides sample to get the number of slides in the presentation. int slidesCount = CountSlides(presentationDocument); if (slideIndex < 0 || slideIndex >= slidesCount) { throw new ArgumentOutOfRangeException("slideIndex"); } // Get the presentation part from the presentation document. PresentationPart presentationPart = presentationDocument.PresentationPart; // Get the presentation from the presentation part. Presentation presentation = presentationPart.Presentation; // Get the list of slide IDs in the presentation. SlideIdList slideIdList = presentation.SlideIdList; // Get the slide ID of the specified slide SlideId slideId = slideIdList.ChildElements[slideIndex] as SlideId; // Get the relationship ID of the slide. string slideRelId = slideId.RelationshipId; // Remove the slide from the slide list. slideIdList.RemoveChild(slideId); // // Remove references to the slide from all custom shows. if (presentation.CustomShowList != null) { // Iterate through the list of custom shows. foreach (var customShow in presentation.CustomShowList.Elements<CustomShow>()) { if (customShow.SlideList != null) { // Declare a link list of slide list entries. LinkedList<SlideListEntry> slideListEntries = new LinkedList<SlideListEntry>(); foreach (SlideListEntry slideListEntry in customShow.SlideList.Elements()) { // Find the slide reference to remove from the custom show. if (slideListEntry.Id != null && slideListEntry.Id == slideRelId) { slideListEntries.AddLast(slideListEntry); } } // Remove all references to the slide from the custom show. foreach (SlideListEntry slideListEntry in slideListEntries) { customShow.SlideList.RemoveChild(slideListEntry); } } } } // Save the modified presentation. presentation.Save(); // Get the slide part for the specified slide. SlidePart slidePart = presentationPart.GetPartById(slideRelId) as SlidePart; // Remove the slide part. presentationPart.DeletePart(slidePart); }
private static bool ValidateAgainstSpecificVersion(PresentationDocument pDoc, List<XElement> metrics, DocumentFormat.OpenXml.FileFormatVersions versionToValidateAgainst, XName versionSpecificMetricName) { OpenXmlValidator validator = new OpenXmlValidator(versionToValidateAgainst); var errors = validator.Validate(pDoc); bool valid = errors.Count() == 0; if (!valid) { if (!metrics.Any(e => e.Name == H.SdkValidationError)) metrics.Add(new XElement(H.SdkValidationError, new XAttribute(H.Val, true))); metrics.Add(new XElement(versionSpecificMetricName, new XAttribute(H.Val, true), errors.Take(3).Select(err => { StringBuilder sb = new StringBuilder(); if (err.Description.Length > 300) sb.Append(PtUtils.MakeValidXml(err.Description.Substring(0, 300) + " ... elided ...") + Environment.NewLine); else sb.Append(PtUtils.MakeValidXml(err.Description) + Environment.NewLine); sb.Append(" in part " + PtUtils.MakeValidXml(err.Part.Uri.ToString()) + Environment.NewLine); sb.Append(" at " + PtUtils.MakeValidXml(err.Path.XPath) + Environment.NewLine); return sb.ToString(); }))); } return valid; }
private string GetSlideLayoutName(PresentationDocument presentationDocument, int slideIndex) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } if (slideIndex < 0) { throw new ArgumentOutOfRangeException("slideIndex"); } PresentationPart presentationPart = presentationDocument.PresentationPart; if (presentationPart != null && presentationPart.Presentation != null) { P.Presentation presentation = presentationPart.Presentation; if (presentation.SlideIdList != null) { OpenXmlElementList slideIds = presentation.SlideIdList.ChildElements; if (slideIndex < slideIds.Count) { string slidePartRelationshipId = (slideIds[slideIndex] as P.SlideId).RelationshipId; SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId); try { if (slidePart != null) { SlideLayoutPart slPart = slidePart.SlideLayoutPart; if(slPart!=null) { return slPart.SlideLayout.CommonSlideData.Name.ToString(); } } } catch { return string.Empty; } } } } return string.Empty; }
private void NotesInSlideToWord(PresentationDocument presentationDocument, int slideIndex, WordprocessingDocument wordprocessingDocument, bool instructorGuide) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } if (slideIndex < 0) { throw new ArgumentOutOfRangeException("slideIndex"); } PresentationPart presentationPart = presentationDocument.PresentationPart; if (presentationPart != null && presentationPart.Presentation != null) { P.Presentation presentation = presentationPart.Presentation; if (presentation.SlideIdList != null) { OpenXmlElementList slideIds = presentation.SlideIdList.ChildElements; if (slideIndex < slideIds.Count) { string slidePartRelationshipId = (slideIds[slideIndex] as P.SlideId).RelationshipId; SlidePart slidePart = (SlidePart)presentationPart.GetPartById(slidePartRelationshipId); NotesSlidePart notesSlidePart1 = slidePart.NotesSlidePart; if (notesSlidePart1 == null) return; P.NotesSlide notesSlide = notesSlidePart1.NotesSlide; P.CommonSlideData csldData = notesSlide.CommonSlideData; P.ShapeTree shpTree = csldData.ShapeTree; P.Shape shp = null; try { shp = shpTree.Elements<P.Shape>().ElementAt(1); } catch { } if (shp == null) { AlternateContent ac = shpTree.Elements<AlternateContent>().ElementAt(0); shp = ac.Elements<AlternateContentFallback>().ElementAt(0).Elements<P.Shape>().ElementAt(0); } P.TextBody tb = shp.Elements<P.TextBody>().ElementAt(0); string collectedText = ""; int numberingID = -1; bool h1open = false; bool h2open = false; bool h3open = false; bool instrNotesopen = false; bool collectText = false; int heading = 0; string firstParaText = ""; string paragraphText = ""; foreach (Drawing.Paragraph para in tb.Elements<Drawing.Paragraph>()) { paragraphText = ""; foreach (Drawing.Run r in para.Elements<Drawing.Run>()) { firstParaText += r.InnerText; paragraphText += r.InnerText; } if (firstParaText.Contains("*hbno*") || firstParaText.Contains("*hbyes*")) { firstParaText = ""; continue; } bool b = false; bool i = false; bool u = false; Drawing.ParagraphProperties pp = null; foreach (OpenXmlElement el in para.Elements<Drawing.ParagraphProperties>()) { if (el.GetType() == typeof(Drawing.ParagraphProperties)) { pp = (Drawing.ParagraphProperties)el; } } Drawing.CharacterBullet cb = null; Drawing.AutoNumberedBullet anb = null; if (pp != null) { OpenXmlElementList li = pp.ChildElements; foreach (OpenXmlElement el in li) { if (el.GetType() == typeof(Drawing.CharacterBullet)) { cb = (Drawing.CharacterBullet)el; } if (el.GetType() == typeof(Drawing.AutoNumberedBullet)) { anb = (Drawing.AutoNumberedBullet)el; } } } if (cb != null && !instrNotesopen) { AddParagraphToWordBullet(wordprocessingDocument, cb.Char); } else if (anb != null && !instrNotesopen) { numberingID = AddParagraphToWordNumbering(wordprocessingDocument, numberingID); } else if (!instrNotesopen && !paragraphText.Contains("**") && !paragraphText.Contains("*h1*") && !paragraphText.Contains("*h2*") && !paragraphText.Contains("*h3*")) { AddParagraphToWord(wordprocessingDocument); numberingID = -1; } foreach (Drawing.Run r in para.Elements<Drawing.Run>()) { b = false; i = false; u = false; string addedText = ""; string tempStr = r.InnerText; collectedText += r.InnerText; tempStr = collectedText; string textToWrite = ""; int astLoc = tempStr.IndexOf("*"); if (astLoc != -1) { if (astLoc > 0) { textToWrite = tempStr.Substring(0, astLoc); } if (tempStr.Length > astLoc + 1) { if (tempStr.Substring(astLoc, 2) == "**") { if (!instructorGuide) { if (!instrNotesopen) { collectedText = tempStr.Substring(astLoc + 2); int a = collectedText.IndexOf("**"); if (a != -1) { int a1 = collectedText.IndexOf("**"); if (collectedText.Length > a + 2) addedText = collectedText.Substring(a + 2); collectedText = collectedText.Remove(collectedText.IndexOf("**"), 2); instrNotesopen = !instrNotesopen; collectText = !collectText; } if (instrNotesopen) { collectedText = ""; } } else { int a = collectedText.IndexOf("**"); if (collectedText.Length > a + 2) addedText = collectedText.Substring(a + 2); collectedText = collectedText.Remove(collectedText.IndexOf("**")); collectedText = ""; } instrNotesopen = !instrNotesopen; collectText = !collectText; } else { collectedText = collectedText.Replace("**", ""); } } } else { collectText = true; } if (tempStr.Length > astLoc + 3) { if (tempStr.Substring(astLoc, 4) == "*h1*") { if (!h1open) { collectedText = tempStr.Substring(astLoc + 4); int a = collectedText.IndexOf("*h1*"); collectText = false; //20.01. testing added this if (a != -1) { int a1 = collectedText.IndexOf("*h1*"); if (collectedText.Length > a1 + 4) addedText = collectedText.Substring(a1 + 4); collectedText = collectedText.Remove(collectedText.IndexOf("*h1*")); h1open = !h1open; collectText = !collectText; heading = 1; } } else { int a = collectedText.IndexOf("*h1*"); if (collectedText.Length > a + 4) addedText = collectedText.Substring(a + 4); collectedText = collectedText.Remove(collectedText.IndexOf("*h1*")); heading = 1; } h1open = !h1open; collectText = !collectText; } else if (tempStr.Substring(astLoc, 4) == "*h2*") { if (!h2open) { collectedText = tempStr.Substring(astLoc + 4); int a = collectedText.IndexOf("*h2*"); collectText = false; //20.01. testing added this if (a != -1) { int a1 = collectedText.IndexOf("*h2*"); if (collectedText.Length > a1 + 4) addedText = collectedText.Substring(a1 + 4); collectedText = collectedText.Remove(collectedText.IndexOf("*h2*")); h1open = !h1open; collectText = !collectText; heading = 2; } } else { int a = collectedText.IndexOf("*h2*"); if (collectedText.Length > a + 4) addedText = collectedText.Substring(a + 4); collectedText = collectedText.Remove(collectedText.IndexOf("*h2*")); heading = 2; } h2open = !h2open; collectText = !collectText; } else if (tempStr.Substring(astLoc, 4) == "*h3*") { if (!h3open) { collectedText = tempStr.Substring(astLoc + 4); int a = collectedText.IndexOf("*h3*"); collectText = false; //20.01. testing added this if (a != -1) { int a1 = collectedText.IndexOf("*h3*"); if (collectedText.Length > a1 + 4) addedText = collectedText.Substring(a1 + 4); collectedText = collectedText.Remove(collectedText.IndexOf("*h3*")); h1open = !h1open; collectText = !collectText; heading = 3; } } else { int a = collectedText.IndexOf("*h3*"); if (collectedText.Length > a + 4) addedText = collectedText.Substring(a + 4); collectedText = collectedText.Remove(collectedText.IndexOf("*h3*")); heading = 3; } h3open = !h3open; collectText = !collectText; } } //if (tempStr.Length > astLoc + 1) //{ // if (tempStr.Substring(astLoc, 2) == "**") // { // int a = collectedText.IndexOf("**"); // if (collectedText.Length > a + 2) // addedText = collectedText.Substring(a + 2); // collectedText = collectedText.Remove(collectedText.IndexOf("**"), 2); // instrNotesopen = !instrNotesopen; // collectText = !collectText; // if (!instrNotesopen) // { // collectedText = ""; // } // } //} //else //{ // collectText = true; //} } Drawing.RunProperties rp = r.RunProperties; b = false; i = false; u = false; if (rp.Bold != null && rp.Bold.ToString() != "0") b = true; if (rp.Italic != null && rp.Italic.ToString() != "0") i = true; if (rp.Underline != null && rp.Underline != "none") u = true; if (!collectText && collectedText.Length > 0) { AddTextToWord(wordprocessingDocument, collectedText, b, i, u, heading, slideIndex); heading = 0; collectedText = ""; } else { } if (addedText.Length > 0) collectedText = addedText; } if (!collectText && collectedText.Length > 0 && collectedText.IndexOf("*") == -1) { AddTextToWord(wordprocessingDocument, collectedText, b, i, u, heading, slideIndex); heading = 0; collectedText = ""; } } if (collectedText.Length > 0) { AddParagraphToWord(wordprocessingDocument); AddTextToWord(wordprocessingDocument, collectedText, false, false, false, 0, slideIndex); collectedText = ""; } } } } }
// Insert the specified slide into the presentation at the specified position. public static void InsertNewSlide(PresentationDocument presentationDocument, int position, string slideTitle) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } if (slideTitle == null) { throw new ArgumentNullException("slideTitle"); } PresentationPart presentationPart = presentationDocument.PresentationPart; // Verify that the presentation is not empty. if (presentationPart == null) { throw new InvalidOperationException("The presentation document is empty."); } // Declare and instantiate a new slide. Slide slide = new Slide(new CommonSlideData(new ShapeTree())); uint drawingObjectId = 1; // Construct the slide content. // Specify the non-visual properties of the new slide. NonVisualGroupShapeProperties nonVisualProperties = slide.CommonSlideData.ShapeTree.AppendChild(new NonVisualGroupShapeProperties()); nonVisualProperties.NonVisualDrawingProperties = new NonVisualDrawingProperties() { Id = 1, Name = "" }; nonVisualProperties.NonVisualGroupShapeDrawingProperties = new NonVisualGroupShapeDrawingProperties(); nonVisualProperties.ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties(); // Specify the group shape properties of the new slide. slide.CommonSlideData.ShapeTree.AppendChild(new GroupShapeProperties()); // Declare and instantiate the title shape of the new slide. Shape titleShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape()); drawingObjectId++; // Specify the required shape properties for the title shape. titleShape.NonVisualShapeProperties = new NonVisualShapeProperties (new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Title" }, new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Type = PlaceholderValues.Title })); titleShape.ShapeProperties = new ShapeProperties(); // Specify the text of the title shape. titleShape.TextBody = new TextBody(new Drawing.BodyProperties(), new Drawing.ListStyle(), new Drawing.Paragraph(new Drawing.Run(new Drawing.Text() { Text = slideTitle }))); // Declare and instantiate the body shape of the new slide. Shape bodyShape = slide.CommonSlideData.ShapeTree.AppendChild(new Shape()); drawingObjectId++; // Specify the required shape properties for the body shape. bodyShape.NonVisualShapeProperties = new NonVisualShapeProperties(new NonVisualDrawingProperties() { Id = drawingObjectId, Name = "Content Placeholder" }, new NonVisualShapeDrawingProperties(new Drawing.ShapeLocks() { NoGrouping = true }), new ApplicationNonVisualDrawingProperties(new PlaceholderShape() { Index = 1 })); bodyShape.ShapeProperties = new ShapeProperties(); // Specify the text of the body shape. bodyShape.TextBody = new TextBody(new Drawing.BodyProperties(), new Drawing.ListStyle(), new Drawing.Paragraph()); // Create the slide part for the new slide. SlidePart slidePart = presentationPart.AddNewPart<SlidePart>(); // Save the new slide part. slide.Save(slidePart); // Modify the slide ID list in the presentation part. // The slide ID list should not be null. SlideIdList slideIdList = presentationPart.Presentation.SlideIdList; // Find the highest slide ID in the current list. uint maxSlideId = 1; SlideId prevSlideId = null; foreach (SlideId slideId in slideIdList.ChildElements) { if (slideId.Id > maxSlideId) { maxSlideId = slideId.Id; } position--; if (position == 0) { prevSlideId = slideId; } } maxSlideId++; // Get the ID of the previous slide. SlidePart lastSlidePart; if (prevSlideId != null) { lastSlidePart = (SlidePart)presentationPart.GetPartById(prevSlideId.RelationshipId); } else { lastSlidePart = (SlidePart)presentationPart.GetPartById(((SlideId)(slideIdList.ChildElements[0])).RelationshipId); } // Use the same slide layout as that of the previous slide. if (null != lastSlidePart.SlideLayoutPart) { slidePart.AddPart(lastSlidePart.SlideLayoutPart); } // Insert the new slide into the slide list after the previous slide. SlideId newSlideId = slideIdList.InsertAfter(new SlideId(), prevSlideId); newSlideId.Id = maxSlideId; newSlideId.RelationshipId = presentationPart.GetIdOfPart(slidePart); // Save the modified presentation. presentationPart.Presentation.Save(); }
// Apply a new theme to the presentation. public static void ApplyThemeToPresentation(PresentationDocument presentationDocument, PresentationDocument themeDocument) { if (presentationDocument == null) { throw new ArgumentNullException("presentationDocument"); } if (themeDocument == null) { throw new ArgumentNullException("themeDocument"); } // Get the presentation part of the presentation document. PresentationPart presentationPart = presentationDocument.PresentationPart; // Get the existing slide master part. SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.ElementAt(0); string relationshipId = presentationPart.GetIdOfPart(slideMasterPart); // Get the new slide master part. SlideMasterPart newSlideMasterPart = themeDocument.PresentationPart.SlideMasterParts.ElementAt(0); // Remove the existing theme part. presentationPart.DeletePart(presentationPart.ThemePart); // Remove the old slide master part. presentationPart.DeletePart(slideMasterPart); // Import the new slide master part, and reuse the old relationship ID. newSlideMasterPart = presentationPart.AddPart(newSlideMasterPart, relationshipId); // Change to the new theme part. presentationPart.AddPart(newSlideMasterPart.ThemePart); Dictionary<string, SlideLayoutPart> newSlideLayouts = new Dictionary<string, SlideLayoutPart>(); foreach (var slideLayoutPart in newSlideMasterPart.SlideLayoutParts) { newSlideLayouts.Add(GetSlideLayoutType(slideLayoutPart), slideLayoutPart); } string layoutType = null; SlideLayoutPart newLayoutPart = null; // Insert the code for the layout for this example. string defaultLayoutType = "Title and Content"; // Remove the slide layout relationship on all slides. foreach (var slidePart in presentationPart.SlideParts) { layoutType = null; if (slidePart.SlideLayoutPart != null) { // Determine the slide layout type for each slide. layoutType = GetSlideLayoutType(slidePart.SlideLayoutPart); // Delete the old layout part. slidePart.DeletePart(slidePart.SlideLayoutPart); } if (layoutType != null && newSlideLayouts.TryGetValue(layoutType, out newLayoutPart)) { // Apply the new layout part. slidePart.AddPart(newLayoutPart); } else { newLayoutPart = newSlideLayouts[defaultLayoutType]; // Apply the new default layout part. slidePart.AddPart(newLayoutPart); } } }
/// <summary> /// Get list of all the sections /// </summary> /// <param name="pDoc"></param> /// <returns></returns> private List<Section> GetListOfSections(PresentationDocument pDoc) { var sections = new List<Section>(); if (pDoc.PresentationPart == null) { return sections; } SectionList sectionList = pDoc.PresentationPart.Presentation.PresentationExtensionList.Descendants<SectionList>().FirstOrDefault(); if (sectionList == null) { return sections; } sections.AddRange(sectionList.Select(section => section as Section)); return sections; }
public static void SearchAndReplace(PresentationDocument pDoc, string search, string replace, bool matchCase) { PresentationPart presentationPart = pDoc.PresentationPart; foreach (var slidePart in presentationPart.SlideParts) { XDocument slideXDoc = slidePart.GetXDocument(); XElement root = slideXDoc.Root; XElement newRoot = (XElement)PmlReplaceTextTransform(root, search, replace, matchCase); slidePart.PutXDocument(new XDocument(newRoot)); } }
/// <summary> /// Gets the SlidePart based on the slide number /// </summary> /// <param name="pDoc"></param> /// <param name="slideNumber"></param> /// <returns></returns> private SlidePart GetSlidePart(PresentationDocument pDoc, int slideNumber) { int index = slideNumber - 1; if (pDoc.PresentationPart != null) { List<StringValue> slideRIds = GetSlideRIds(pDoc); if (0 <= index && index < slideRIds.Count) { return pDoc.PresentationPart.GetPartById(slideRIds[index]) as SlidePart; } } return null; }
public static void FixUpPresentationDocument(PresentationDocument pDoc) { foreach (var part in pDoc.GetAllParts()) { if (part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.slide+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.slideMaster+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.slideLayout+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.notesMaster+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.notesSlide+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.presentationml.handoutMaster+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.theme+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.drawingml.chart+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.drawingml.diagramData+xml" || part.ContentType == "application/vnd.openxmlformats-officedocument.drawingml.chartshapes+xml" || part.ContentType == "application/vnd.ms-office.drawingml.diagramDrawing+xml") { XDocument xd = part.GetXDocument(); xd.Descendants().Attributes("smtClean").Remove(); xd.Descendants().Attributes("smtId").Remove(); part.PutXDocument(); } if (part.ContentType == "application/vnd.openxmlformats-officedocument.vmlDrawing") { string fixedContent = null; using (var stream = part.GetStream(FileMode.Open, FileAccess.ReadWrite)) { using (var sr = new StreamReader(stream)) { //string input = @" <![if gte mso 9]><v:imagedata o:relid=""rId15"""; var input = sr.ReadToEnd(); string pattern = @"<!\[(?<test>.*)\]>"; //string replacement = "<![CDATA[${test}]]>"; //fixedContent = Regex.Replace(input, pattern, replacement, RegexOptions.Multiline); fixedContent = Regex.Replace(input, pattern, m => { var g = m.Groups[1].Value; if (g.StartsWith("CDATA[")) return "<![" + g + "]>"; else return "<![CDATA[" + g + "]]>"; }, RegexOptions.Multiline); //var input = @"xxxxx o:relid=""rId1"" o:relid=""rId1"" xxxxx"; pattern = @"o:relid=[""'](?<id1>.*)[""'] o:relid=[""'](?<id2>.*)[""']"; fixedContent = Regex.Replace(fixedContent, pattern, m => { var g = m.Groups[1].Value; return @"o:relid=""" + g + @""""; }, RegexOptions.Multiline); fixedContent = fixedContent.Replace("</xml>ml>", "</xml>"); stream.SetLength(fixedContent.Length); } } using (var ms = new MemoryStream(Encoding.UTF8.GetBytes(fixedContent))) part.FeedData(ms); } } }
/// <summary> /// Get the ids of the slides /// </summary> /// <param name="pDoc"></param> /// <returns>list of ids for slides</returns> private List<UInt32Value> GetSlideIds(PresentationDocument pDoc) { var ids = new List<UInt32Value>(); if (pDoc.PresentationPart == null || pDoc.PresentationPart.Presentation == null || pDoc.PresentationPart.Presentation.SlideIdList == null) { return ids; } ids.AddRange(from SlideId slideId in pDoc.PresentationPart.Presentation.SlideIdList select slideId.Id); return ids; }