Example #1
0
        public bool ReplaceImageInSlide(SlidePart slidePart, string imageFileLocation)
        {
            this.Logger.Log("Trying to replace image in slide Part");
            var       mySlideLayoutPart = slidePart.SlideLayoutPart;
            ImagePart imagePart         = slidePart.AddImagePart("image/png");
            var       imgRelId          = slidePart.GetIdOfPart(imagePart);

            FileStream stream = new FileStream(imageFileLocation, FileMode.Open);

            imagePart.FeedData(stream);

            stream.Close();


            // https://blogs.msdn.microsoft.com/brian_jones/2008/11/18/creating-a-presentation-report-based-on-data/

            // Find the first image element and replace
            try
            {
                Drawing.Blip blip = slidePart.Slide.Descendants <Blip>().First();
                blip.Embed = imgRelId;
                this.Logger.Log("Saving slide Part");
                slidePart.Slide.Save();
                return(true);
            }
            catch (Exception)
            {
                return(false);
            }
        }
 public void Create()
 {
     NewSlidePart = _doc.PresentationPart.AddNewPart <SlidePart>(NewSlideName + _slideId++);
     //copy the contents of the template slide to the new slide and attach the appropriate layout
     NewSlidePart.FeedData(_teplateSlide.GetStream(FileMode.Open));
     NewSlidePart.AddPart(_teplateSlide.SlideLayoutPart,
                          _teplateSlide.GetIdOfPart(_teplateSlide.SlideLayoutPart));
 }
Example #3
0
        /// <summary>
        /// Replaces a picture by another inside the slide.
        /// </summary>
        /// <param name="tag">The tag associated with the original picture so it can be found, if null or empty do nothing.</param>
        /// <param name="newPicture">The new picture (as a byte array) to replace the original picture with, if null do nothing.</param>
        /// <param name="contentType">The picture content type: image/png, image/jpeg...</param>
        /// <remarks>
        /// <see href="http://stackoverflow.com/questions/7070074/how-can-i-retrieve-images-from-a-pptx-file-using-ms-open-xml-sdk">How can I retrieve images from a .pptx file using MS Open XML SDK?</see>
        /// <see href="http://stackoverflow.com/questions/7137144/how-can-i-retrieve-some-image-data-and-format-using-ms-open-xml-sdk">How can I retrieve some image data and format using MS Open XML SDK?</see>
        /// <see href="http://msdn.microsoft.com/en-us/library/office/bb497430.aspx">How to: Insert a Picture into a Word Processing Document</see>
        /// </remarks>
        private void ReplacePicture(string tag, byte[] newPicture, string contentType, SlidePart diapositiva)
        {
            ImagePart imagePart = AddPicture(newPicture, contentType, diapositiva);

            foreach (Picture pic in diapositiva.Slide.Descendants <Picture>())
            {
                var cNvPr = pic.NonVisualPictureProperties.NonVisualDrawingProperties;
                if (cNvPr.Name != null)
                {
                    string title = cNvPr.Name.Value;
                    string rId   = diapositiva.GetIdOfPart(imagePart);
                    pic.BlipFill.Blip.Embed.Value = rId;
                }
            }
        }
Example #4
0
        /// <summary>
        /// Replaces slidePart images
        /// </summary>
        /// <param name="presentationDocument"></param>
        /// <param name="slidePart"></param>
        void ReplaceImages(PresentationDocument presentationDocument, SlidePart slidePart)
        {
            // get all images in the slide
            var imagesToReplace = slidePart.Slide.Descendants <Blip>().ToList();

            if (imagesToReplace.Any())
            {
                var index = 0;//image index within the slide

                //find all image names in the slide
                var slidePartImageNames = slidePart.Slide.Descendants <DocumentFormat.OpenXml.Presentation.Picture>()
                                          .Where(a => a.NonVisualPictureProperties.NonVisualDrawingProperties.Title.HasValue)
                                          .Select(a => a.NonVisualPictureProperties.NonVisualDrawingProperties.Title.Value).Distinct().ToList();

                //check all images in the slide and replace them if it matches our parameter
                foreach (var imagePlaceHolder in slidePartImageNames)
                {
                    //check if we have image parameter that matches slide part image
                    foreach (var param in PowerPointParameters)
                    {
                        //replace it if found by image name
                        if (param.Image != null && param.Name.ToLower() == imagePlaceHolder.ToLower())
                        {
                            var imagePart = slidePart.AddImagePart(ImagePartType.Jpeg); //add image to document

                            using (FileStream imgStream = new FileStream(param.Image.FullName, FileMode.Open))
                            {
                                imagePart.FeedData(imgStream); //feed it with data
                            }

                            var relID = slidePart.GetIdOfPart(imagePart);      // get relationship ID

                            imagesToReplace.Skip(index).First().Embed = relID; //assign new relID, skip if this is another image in one slide part
                        }
                    }
                    index += 1;
                }
            }
        }
        /// <summary>
        /// Clones this slide.
        /// </summary>
        /// <returns>The clone.</returns>
        /// <remarks>
        /// <see href="http://blogs.msdn.com/b/brian_jones/archive/2009/08/13/adding-repeating-data-to-powerpoint.aspx">Adding Repeating Data to PowerPoint</see>
        /// <see href="http://startbigthinksmall.wordpress.com/2011/05/17/cloning-a-slide-using-open-xml-sdk-2-0/">Cloning a Slide using Open Xml SDK 2.0</see>
        /// <see href="http://www.exsilio.com/blog/post/2011/03/21/Cloning-Slides-including-Images-and-Charts-in-PowerPoint-presentations-Using-Open-XML-SDK-20-Productivity-Tool.aspx">See Cloning Slides including Images and Charts in PowerPoint presentations and Using Open XML SDK 2.0 Productivity Tool</see>
        /// </remarks>
        public PowerpointSlide Clone()
        {
            SlidePart slideTemplate = this.slidePart;

            // Clone slide contents
            SlidePart slidePartClone = this.presentationPart.AddNewPart <SlidePart>();

            using (var templateStream = slideTemplate.GetStream(FileMode.Open))
            {
                slidePartClone.FeedData(templateStream);
            }

            // Copy layout part
            slidePartClone.AddPart(slideTemplate.SlideLayoutPart);

            // Copy the image parts
            foreach (ImagePart image in slideTemplate.ImageParts)
            {
                ImagePart imageClone = slidePartClone.AddImagePart(image.ContentType, slideTemplate.GetIdOfPart(image));
                using (var imageStream = image.GetStream())
                {
                    imageClone.FeedData(imageStream);
                }
            }

            return(new PowerpointSlide(this.presentationPart, slidePartClone));
        }
Example #6
0
        /// <summary>
        /// 在指定位置添加图片 支持 png jpeg gif.
        /// </summary>
        public Picture AddPicture(SlidePart sldpart, string filePath, D.Transform2D transform)
        {
            if (!File.Exists(filePath))
            {
                return(null);
            }

            var     imgprt = sldpart.AddImagePart(AnalysisHelper.GetImagePartType(filePath));
            string  rlid   = sldpart.GetIdOfPart(imgprt);
            var     tree   = sldpart.Slide.CommonSlideData.ShapeTree;
            uint    maxid  = AnalysisHelper.GetMaxId(tree);
            Picture pic    = new Picture();

            pic.NonVisualPictureProperties = new NonVisualPictureProperties
                                             (
                new P.NonVisualDrawingProperties()
            {
                Id   = maxid + 1,
                Name = $"PIC{maxid + 1}"
            },
                new P.NonVisualPictureDrawingProperties()
            {
                PictureLocks = new D.PictureLocks()
                {
                    NoChangeAspect = true
                }
            },
                //必须指定元素的类型,否则会报错。
                new ApplicationNonVisualDrawingProperties
                (
                    new PlaceholderShape()
            {
                Type = PlaceholderValues.Picture
            }
                )
                                             );

            P.BlipFill blipFill = new P.BlipFill();
            D.Blip     blip     = new D.Blip()
            {
                Embed = rlid
            };
            D.BlipExtensionList blipExtensionList = new D.BlipExtensionList();
            D.BlipExtension     blipExtension     = new D.BlipExtension()
            {
                Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
            };
            DocumentFormat.OpenXml.Office2010.Drawing.UseLocalDpi useLocalDpi =
                new DocumentFormat.OpenXml.Office2010.Drawing.UseLocalDpi()
            {
                Val = false
            };
            useLocalDpi.AddNamespaceDeclaration("a14",
                                                "http://schemas.microsoft.com/office/drawing/2010/main");

            blipExtension.Append(useLocalDpi);
            blipExtensionList.Append(blipExtension);
            blip.Append(blipExtensionList);

            D.Stretch       stretch       = new D.Stretch();
            D.FillRectangle fillRectangle = new D.FillRectangle();
            stretch.Append(fillRectangle);

            blipFill.Append(blip);
            blipFill.Append(stretch);
            pic.Append(blipFill);
            pic.ShapeProperties = new P.ShapeProperties
                                  (
                new D.PresetGeometry(new D.AdjustValueList())
            {
                Preset = D.ShapeTypeValues.Rectangle
            }
                                  )
            {
                Transform2D = transform
            };
            tree.AppendChild(pic);

            using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
            {
                imgprt.FeedData(fileStream);
            }

            return(pic);
        }
Example #7
0
        private static void AddImage(string file, List <ImagePath> image)
        {
            using (var presentationDocument = PresentationDocument.Open(file, true))
            {
                var                slideCount       = presentationDocument.PresentationPart.SlideParts.Count();
                SlideIdList        slideIdList      = presentationDocument.PresentationPart.Presentation.SlideIdList;
                Presentation       presentation     = presentationDocument.PresentationPart.Presentation;
                PresentationPart   presentationPart = presentationDocument.PresentationPart;
                OpenXmlElementList slideIds         = presentationPart.Presentation.SlideIdList.ChildElements;

                int cnt = 0;             // 画像の添付数

                int       j         = 0; // 画像添付スライド位置
                string    relId     = (slideIds[j] as SlideId).RelationshipId;
                SlidePart slidePart = (SlidePart)presentationPart.GetPartById(relId);

                foreach (ImagePath imgPath in image)
                {
                    ImagePart part = slidePart
                                     .AddImagePart(ImagePartType.Png);

                    using (var stream = File.OpenRead(imgPath.Path))
                    {
                        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 Drawing2.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 Drawing2.Blip()
                    {
                        Embed = slidePart.GetIdOfPart(part)
                    };
                    var blipExtensionList1 = new Drawing2.BlipExtensionList();
                    var blipExtension1     = new Drawing2.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 Drawing2.Stretch();
                    stretch.Append(new Drawing2.FillRectangle());
                    blipFill.Append(blip1);
                    blipFill.Append(stretch);
                    picture.Append(blipFill);

                    picture.ShapeProperties             = new DocumentFormat.OpenXml.Presentation.ShapeProperties();
                    picture.ShapeProperties.Transform2D = new Drawing2.Transform2D();

                    int rotation = 0;
                    switch (imgPath.Rot)
                    {
                    case RotateFlipType.RotateNoneFlipNone:
                        rotation = 0;
                        picture.ShapeProperties.Transform2D.Append(new Drawing2.Offset
                        {
                            X = POSITION0[cnt % 6].X,
                            Y = POSITION0[cnt % 6].Y,
                        });
                        break;

                    case RotateFlipType.Rotate180FlipNone:     // 時計回りに180度回転しているので、180度回転して戻す
                        rotation = 60000 * 180;
                        picture.ShapeProperties.Transform2D.Append(new Drawing2.Offset
                        {
                            X = POSITION0[cnt % 6].X,
                            Y = POSITION0[cnt % 6].Y,
                        });
                        break;

                    case RotateFlipType.Rotate90FlipNone:     // 時計回りに270度回転しているので、90度回転して戻す
                        rotation = 60000 * 90;
                        picture.ShapeProperties.Transform2D.Append(new Drawing2.Offset
                        {
                            X = POSITION90[cnt % 6].X,
                            Y = POSITION90[cnt % 6].Y,
                        });
                        break;

                    case RotateFlipType.Rotate270FlipNone:     // 時計回りに90度回転しているので、270度回転して戻す
                        rotation = 60000 * 270;
                        picture.ShapeProperties.Transform2D.Append(new Drawing2.Offset
                        {
                            X = POSITION90[cnt % 6].X,
                            Y = POSITION90[cnt % 6].Y,
                        });
                        break;

                    default:
                        rotation = 0;
                        picture.ShapeProperties.Transform2D.Append(new Drawing2.Offset
                        {
                            X = POSITION0[cnt % 6].X,
                            Y = POSITION0[cnt % 6].Y,
                        });
                        break;
                    }
                    picture.ShapeProperties.Transform2D.Rotation = rotation;

                    // 縦向き
                    picture.ShapeProperties.Transform2D.Append(new Drawing2.Extents
                    {
                        Cx = imgPath.Size.Width,
                        Cy = imgPath.Size.Height,
                    });

                    picture.ShapeProperties.Append(new Drawing2.PresetGeometry
                    {
                        Preset = Drawing2.ShapeTypeValues.Rectangle
                    });

                    tree.Append(picture);

                    if (cnt % 6 == 5)
                    {
                        if (j < slideCount - 1)
                        {
                            j++;
                            relId     = (slideIds[j] as SlideId).RelationshipId;
                            slidePart = (SlidePart)presentationPart.GetPartById(relId);
                        }
                        else
                        {
                            // 画像ループを抜ける
                            break;
                        }
                    }
                    cnt++;
                }

                // スライドを削除する
                for (int i = slideCount - 1; i > j; i--)
                {
                    //Console.WriteLine(i);
                    SlideId slideId    = slideIds[i] as SlideId;
                    string  slideRelId = slideId.RelationshipId;
                    slideIdList.RemoveChild(slideId);

                    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);
                                }
                            }
                        }
                    }
                    presentation.Save();

                    SlidePart slidePart2 = presentationPart.GetPartById(slideRelId) as SlidePart;

                    presentationPart.DeletePart(slidePart2);
                }
            }
        }
Example #8
0
 private string GetIdOfImagePart(ImagePart imagePart, SlidePart diapositiva)
 {
     return(diapositiva.GetIdOfPart(imagePart));
 }