예제 #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);
            }
        }
예제 #2
0
        /// <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));
        }
예제 #3
0
        public static void AddImagePart(SlidePart slidePart, ImagePartType imagePartType, string id, Stream stream)
        {
            stream.Seek(0, SeekOrigin.Begin);
            ImagePart imagePart = slidePart.AddImagePart(imagePartType, id);

            imagePart.FeedData(stream);
        }
예제 #4
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();
            }
        }
        private static List <SlidePart> CreateImageSlideParts(PresentationPart presentationPart, List <SvgDocument> svgDocs)
        {
            int           id = 256;
            string        relId;
            SlideId       newSlideId;
            SlideLayoutId newSlideLayoutId;
            uint          uniqueId   = GetMaxUniqueId(presentationPart);
            uint          maxSlideId = GetMaxSlideId(presentationPart.Presentation.SlideIdList);
            // get first slide master part: template
            SlideMasterPart slideMasterPart = presentationPart.SlideMasterParts.First();

            List <SlidePart> slideParts = new List <SlidePart>();

            for (int i = 0; i < svgDocs.Count; i++)
            {
                id++;
                using (MemoryStream ms = new MemoryStream())
                {
                    using (System.Drawing.Bitmap image = svgDocs[i].Draw())
                    {
                        image.Save(ms, ImageFormat.Bmp);
                        ms.Seek(0, SeekOrigin.Begin);
                        relId = "rId" + id;
                        // add new slide part
                        SlidePart slidePart = presentationPart.AddNewPart <SlidePart>(relId);

                        // add image part to slide part
                        ImagePart imagePart = slidePart.AddImagePart(ImagePartType.Bmp, relId);
                        imagePart.FeedData(ms);
                        // add image slide
                        CreateImageSlide(relId).Save(slidePart);

                        // add slide layout part to slide part
                        SlideLayoutPart slideLayoutPart = slidePart.AddNewPart <SlideLayoutPart>();
                        CreateSlideLayoutPart().Save(slideLayoutPart);
                        slideMasterPart.AddPart(slideLayoutPart);
                        slideLayoutPart.AddPart(slideMasterPart);

                        uniqueId++;
                        newSlideLayoutId = new SlideLayoutId();
                        newSlideLayoutId.RelationshipId = slideMasterPart.GetIdOfPart(slideLayoutPart);
                        newSlideLayoutId.Id             = uniqueId;
                        slideMasterPart.SlideMaster.SlideLayoutIdList.Append(newSlideLayoutId);

                        // add slide part to presentaion slide list
                        maxSlideId++;
                        newSlideId = new SlideId();
                        newSlideId.RelationshipId = relId;
                        newSlideId.Id             = maxSlideId;
                        presentationPart.Presentation.SlideIdList.Append(newSlideId);
                    }
                }
            }
            slideMasterPart.SlideMaster.Save();
            return(slideParts);
        }
예제 #6
0
        public void Generate(Partner partner, string quarter, SlidePart slide)
        {
            var    list        = GetData(partner.PartnerId, quarter);
            var    tbl         = slide.Slide.Descendants <Table>().First();
            var    rows        = tbl.Descendants <TableRow>().ToList();
            var    templateRow = rows[1];
            string imageRel    = "imageRelId";
            int    imageRelId  = 0;

            var categoryItems = (from b in list
                                 group b by b.CategoryName into g
                                 select new { Name = g.First().CategoryName, ItemCount = g.Count() }).ToList();

            foreach (var item in list)
            {
                var placeHolders = new Dictionary <string, string>();
                placeHolders.Add("varCategory", item.CategoryName);
                placeHolders.Add("varCompetitor", item.CompetitorName);
                placeHolders.Add("varShare", item.Share.ToString());
                placeHolders.Add("varPresence", item.BrandPresenc.ToString());
                placeHolders.Add("varPriceStrategy", item.PriceStrategy);
                placeHolders.Add("varInvestment", item.StoreInvestment);
                placeHolders.Add("varComments", item.AdditionalComment);

                TableRow newRow = (TableRow)templateRow.Clone();
                PptHelper.ReplaceRowContent(newRow, placeHolders);

                var fileName    = "/Content/images/hp.gif";
                var imgPartType = ImagePartType.Jpeg;
                var imgArr      = PptHelper.GetImageData(fileName, ref imgPartType);

                ImagePart imagePart = slide.AddImagePart(imgPartType, imageRel + imageRelId);
                PptHelper.GenerateImagePart(imagePart, imgArr);


                var cells = newRow.Descendants <TableCell>().ToList();
                //cells[2].Remove();

                var newImgCell = PptHelper.CreateDrawingCell(imageRel + imageRelId);
                //newRow.InsertAt(newImgCell, 2);

                if (categoryItems.Any(c => c.Name == item.CategoryName))
                {
                    var categoryItem = categoryItems.First(c => c.Name == item.CategoryName);
                    cells[0].VerticalMerge = true;
                    cells[0].RowSpan       = categoryItem.ItemCount;
                    categoryItems.Remove(categoryItem);
                }

                tbl.Append(newRow);

                imageRelId++;
            }
            rows[1].Remove();
        }
예제 #7
0
        private ImagePart AddPicture(byte[] picture, string contentType, SlidePart diapositiva)
        {
            ImagePartType type = 0;

            switch (contentType)
            {
            case "image/bmp":
                type = ImagePartType.Bmp;
                break;

            case "image/emf":
                type = ImagePartType.Emf;
                break;

            case "image/gif":
                type = ImagePartType.Gif;
                break;

            case "image/ico":
                type = ImagePartType.Icon;
                break;

            case "image/jpeg":
                type = ImagePartType.Jpeg;
                break;

            case "image/pcx":
                type = ImagePartType.Pcx;
                break;

            case "image/png":
                type = ImagePartType.Png;
                break;

            case "image/tiff":
                type = ImagePartType.Tiff;
                break;

            case "image/wmf":
                type = ImagePartType.Wmf;
                break;
            }

            ImagePart imagePart = diapositiva.AddImagePart(type);

            // FeedData() closes the stream and we cannot reuse it (ObjectDisposedException)
            // solution: copy the original stream to a MemoryStream
            using (MemoryStream stream = new MemoryStream(picture))
            {
                imagePart.FeedData(stream);
            }

            return(imagePart);
        }
예제 #8
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;
                }
            }
        }
예제 #9
0
        public static void InsertAnimatedModel3D(string pptxPath, string pngPath, string glbPath)
        {
            if (pptxPath == null)
            {
                throw new ArgumentNullException("pptxPath");
            }

            if (pngPath == null)
            {
                throw new ArgumentNullException("pngPath");
            }

            if (glbPath == null)
            {
                throw new ArgumentNullException("glbPath");
            }

            // mc:AternateContent & p:timing
            // Open the presentation document
            using PresentationDocument presentationDocument = PresentationDocument.Open(pptxPath, true);

            // Get the relationship ID of the first slide.
            PresentationPart presentationPart = presentationDocument.PresentationPart;

            // Verify that the presentation part and presentation exist.
            if (presentationPart != null && presentationPart.Presentation != null)
            {
                OpenXmlElementList slideIds = presentationPart.Presentation.SlideIdList.ChildElements;

                if (slideIds.Count > 0)
                {
                    string    relId      = (slideIds[0] as SlideId).RelationshipId;
                    SlidePart slidePart  = (SlidePart)presentationPart.GetPartById(relId);
                    int       partsCount = slidePart.Parts.Count();

                    // Add the .png and .glb files for the 3D image
                    using FileStream glbFileStream = new FileStream(glbPath, FileMode.Open, FileAccess.Read);
                    glbFileStream.Seek(0, SeekOrigin.Begin);
                    string glbId = $"rId{++partsCount}";
                    Model3DReferenceRelationshipPart glbImagePart = slidePart.AddNewPart <Model3DReferenceRelationshipPart>(glbId);
                    glbImagePart.FeedData(glbFileStream);

                    using FileStream pngFileStream = new FileStream(pngPath, FileMode.Open, FileAccess.Read);
                    pngFileStream.Seek(0, SeekOrigin.Begin);
                    string    pngId        = $"rId{++partsCount}";
                    ImagePart pngImagePart = slidePart.AddImagePart(ImagePartType.Png, pngId);
                    pngImagePart.FeedData(pngFileStream);

                    CommonSlideData commonSlideDataPart = slidePart.RootElement.Descendants <CommonSlideData>().FirstOrDefault();

                    // Add an AlternateContent element to the shape tree
                    AlternateContent alternateContent = commonSlideDataPart.ShapeTree.AppendChild(new AlternateContent());

                    // Add mc:Choice element to AlternateContent
                    AlternateContentChoice alternateContentChoice = alternateContent.AppendChild(new AlternateContentChoice());
                    alternateContentChoice.Requires = "am3d";
                    alternateContentChoice.AddNamespaceDeclaration("am3d", "http://schemas.microsoft.com/office/drawing/2017/model3d");

                    // Add mc:Fallback element to AlternateContent
                    AlternateContentFallback alternateContentFallback = alternateContent.AppendChild(new AlternateContentFallback());

                    // Create a creationId with the correct namespace
                    string guidId = "{" + System.Guid.NewGuid().ToString().ToUpper() + "}";
                    DocumentFormat.OpenXml.Office2016.Drawing.CreationId creationId = new DocumentFormat.OpenXml.Office2016.Drawing.CreationId();
                    creationId.AddNamespaceDeclaration("a16", "http://schemas.microsoft.com/office/drawing/2014/main");
                    creationId.Id = guidId;

                    // Clone the creationId
                    DocumentFormat.OpenXml.Office2016.Drawing.CreationId creationId2 = (DocumentFormat.OpenXml.Office2016.Drawing.CreationId)creationId.Clone();
                    string      creationIdPartenId = guidId;
                    UInt32Value threeDModelId      = new UInt32Value(2U);

                    // Create modId in with the correct namespace xmlns:p14="http://schemas.microsoft.com/office/powerpoint/2010/main" val="3636546711"
                    DocumentFormat.OpenXml.Office2010.PowerPoint.ModificationId modificationId = new DocumentFormat.OpenXml.Office2010.PowerPoint.ModificationId();
                    modificationId.AddNamespaceDeclaration("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
                    modificationId.Val = 3636546711;

                    // Create a aExtension in with the correct attributes
                    DocumentFormat.OpenXml.Drawing.Extension aExtension = new DocumentFormat.OpenXml.Drawing.Extension();

                    aExtension.SetAttributes(
                        new OpenXmlAttribute[]
                    {
                        new OpenXmlAttribute("cx", string.Empty, "4158691"),
                        new OpenXmlAttribute("cy", string.Empty, "3460830"),
                    });

                    // Create a clone of a:ext for am3d:spPr
                    DocumentFormat.OpenXml.Drawing.Extension aExtension2 = (DocumentFormat.OpenXml.Drawing.Extension)aExtension.Clone();

                    // Create a a3damin:posterFrame and add the namespace
                    DocumentFormat.OpenXml.Office2019.Drawing.Animation.Model3D.PosterFrame model3dPosterFrame = new DocumentFormat.OpenXml.Office2019.Drawing.Animation.Model3D.PosterFrame()
                    {
                        AnimId = 0
                    };
                    model3dPosterFrame.AddNamespaceDeclaration("a3danim", "http://schemas.microsoft.com/office/drawing/2018/animation/model3d");

                    // Create a clone of a:ext for p:spPr
                    DocumentFormat.OpenXml.Drawing.Extension aExtension3 = (DocumentFormat.OpenXml.Drawing.Extension)aExtension.Clone();

                    // Create a:off
                    DocumentFormat.OpenXml.Drawing.Offset offset = new DocumentFormat.OpenXml.Drawing.Offset()
                    {
                        X = 4016654, Y = 1698584
                    };
                    DocumentFormat.OpenXml.Drawing.Offset offset2 = (DocumentFormat.OpenXml.Drawing.Offset)offset.Clone();

                    // Create a3danim:embedAnim and assign its namespace
                    DocumentFormat.OpenXml.Office2019.Drawing.Animation.Model3D.EmbeddedAnimation embeddedAnimation = new DocumentFormat.OpenXml.Office2019.Drawing.Animation.Model3D.EmbeddedAnimation()
                    {
                        AnimId = 0
                    };
                    embeddedAnimation.AddNamespaceDeclaration("a3danim", "http://schemas.microsoft.com/office/drawing/2018/animation/model3d");
                    embeddedAnimation.AppendChild(new DocumentFormat.OpenXml.Office2019.Drawing.Animation.Model3D.AnimationProperties()
                    {
                        Length = "1899", Count = "indefinite"
                    });

                    // Create the mc:AlternateContent element
                    alternateContentChoice.AppendChild(
                        new GraphicFrame(
                            new NonVisualGraphicFrameProperties(
                                new NonVisualDrawingProperties(
                                    new DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList(
                                        new DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtension(
                                            creationId)
                    {
                        Uri = "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}"
                    }))
                    {
                        Id = threeDModelId, Name = "3D Model 1", Description = "Flying bee"
                    },
                                new NonVisualGraphicFrameDrawingProperties(),
                                new ApplicationNonVisualDrawingProperties(
                                    new ApplicationNonVisualDrawingPropertiesExtensionList(
                                        new ApplicationNonVisualDrawingPropertiesExtension(
                                            modificationId)
                    {
                        Uri = "{D42A27DB-BD31-4B8C-83A1-F6EECF244321}"
                    }))),
                            new Transform(
                                offset,
                                aExtension),
                            new DocumentFormat.OpenXml.Drawing.Graphic(
                                new DocumentFormat.OpenXml.Drawing.GraphicData(
                                    new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Model3D(
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.ShapeProperties(
                                            new DocumentFormat.OpenXml.Drawing.Transform2D(
                                                new DocumentFormat.OpenXml.Drawing.Offset()
                    {
                        X = 0, Y = 0
                    },
                                                aExtension2),
                                            new DocumentFormat.OpenXml.Drawing.PresetGeometry(
                                                new DocumentFormat.OpenXml.Drawing.AdjustValueList())
                    {
                        Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle
                    }),
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Model3DCamera(
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PosPoint3D()
                    {
                        X = 0, Y = 0, Z = 67740115
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.UpVector3D()
                    {
                        Dx = 0, Dy = 36000000, Dz = 0
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.LookAtPoint3D()
                    {
                        X = 0, Y = 0, Z = 0
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PerspectiveProjection()
                    {
                        Fov = 2700000
                    }),
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Model3DTransform(
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.MeterPerModelUnitPositiveRatio()
                    {
                        N = 30569, D = 1000000
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PreTransVector3D()
                    {
                        Dx = -98394, Dy = -14223043, Dz = -1124542
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Scale3D(
                                                new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.SxRatio()
                    {
                        Numerator = 1000000, Denominator = 1000000
                    },
                                                new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.SyRatio()
                    {
                        Numerator = 1000000, Denominator = 1000000
                    },
                                                new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.SzRatio()
                    {
                        Numerator = 1000000, Denominator = 1000000
                    }),
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Rotate3D(),
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PostTransVector3D()
                    {
                        Dx = 0, Dy = 0, Dz = 0
                    }),
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Model3DRaster(
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Blip()
                    {
                        Embed = pngId
                    })
                    {
                        RName = "Office3DRenderer", RVer = "16.0.8326"
                    },
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.Model3DExtensionList(
                                            new DocumentFormat.OpenXml.Drawing.Extension(
                                                embeddedAnimation)
                    {
                        Uri = "{9A65AA19-BECB-4387-8358-8AD5134E1D82}"
                    },
                                            new DocumentFormat.OpenXml.Drawing.Extension(
                                                model3dPosterFrame)
                    {
                        Uri = "{E9DE012E-A134-456F-84FE-255F9AAD75C6}"
                    }),
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.ObjectViewport()
                    {
                        ViewportSz = 5418666
                    },
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.AmbientLight(
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.ColorType(
                                                new DocumentFormat.OpenXml.Drawing.RgbColorModelPercentage()
                    {
                        RedPortion = 50000, GreenPortion = 50000, BluePortion = 50000
                    }),
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.IlluminancePositiveRatio()
                    {
                        N = 500000, D = 1000000
                    }),
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PointLight(
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.ColorType(
                                                new DocumentFormat.OpenXml.Drawing.RgbColorModelPercentage()
                    {
                        RedPortion = 100000, GreenPortion = 75000, BluePortion = 50000
                    }),
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.IntensityPositiveRatio()
                    {
                        N = 9765625, D = 1000000
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PosPoint3D()
                    {
                        X = 21959998, Y = 70920001, Z = 16344003
                    })
                    {
                        Rad = 0
                    },
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PointLight(
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.ColorType(
                                                new DocumentFormat.OpenXml.Drawing.RgbColorModelPercentage()
                    {
                        RedPortion = 40000, GreenPortion = 60000, BluePortion = 95000
                    }),
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.IntensityPositiveRatio()
                    {
                        N = 12250000, D = 1000000
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PosPoint3D()
                    {
                        X = -37964106, Y = 51130435, Z = 57631972
                    })
                    {
                        Rad = 0
                    },
                                        new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PointLight(
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.ColorType(
                                                new DocumentFormat.OpenXml.Drawing.RgbColorModelPercentage()
                    {
                        RedPortion = 86837, GreenPortion = 72700, BluePortion = 100000
                    }),
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.IntensityPositiveRatio()
                    {
                        N = 3125000, D = 1000000
                    },
                                            new DocumentFormat.OpenXml.Office2019.Drawing.Model3D.PosPoint3D()
                    {
                        X = -37739122, Y = 58056624, Z = -34769649
                    })
                    {
                        Rad = 0
                    })
                    {
                        Embed = glbId
                    })
                    {
                        Uri = "http://schemas.microsoft.com/office/drawing/2017/model3d"
                    })));

                    // Add children to mc:Fallback
                    alternateContentFallback.AppendChild(
                        new DocumentFormat.OpenXml.Presentation.Picture(
                            new NonVisualPictureProperties(
                                new NonVisualDrawingProperties(
                                    new DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtensionList(
                                        new DocumentFormat.OpenXml.Drawing.NonVisualDrawingPropertiesExtension(
                                            creationId2)
                    {
                        Uri = "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}"
                    }))
                    {
                        Id = threeDModelId, Name = "3D Model 1", Description = "Flying bee"
                    },
                                new DocumentFormat.OpenXml.Presentation.NonVisualPictureDrawingProperties(
                                    new DocumentFormat.OpenXml.Drawing.PictureLocks()
                    {
                        NoGrouping = true, NoRotation = true, NoChangeAspect = true, NoMove = true, NoResize = true, NoEditPoints = true, NoAdjustHandles = true, NoChangeArrowheads = true, NoChangeShapeType = true, NoCrop = true
                    }),
                                new DocumentFormat.OpenXml.Presentation.ApplicationNonVisualDrawingProperties()),
                            new DocumentFormat.OpenXml.Presentation.BlipFill(
                                new DocumentFormat.OpenXml.Drawing.Blip()
                    {
                        Embed = pngId
                    },
                                new DocumentFormat.OpenXml.Drawing.Stretch(
                                    new DocumentFormat.OpenXml.Drawing.FillRectangle())),
                            new DocumentFormat.OpenXml.Presentation.ShapeProperties(
                                new DocumentFormat.OpenXml.Drawing.Transform2D(
                                    offset2,
                                    aExtension3),
                                new DocumentFormat.OpenXml.Drawing.PresetGeometry(
                                    new DocumentFormat.OpenXml.Drawing.AdjustValueList())
                    {
                        Preset = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle
                    })));

                    // DocumentFormat.OpenXml.Presentation.AttributeName attributeName = new DocumentFormat.OpenXml.Presentation.AttributeName();
                    // attributeName.InnerXml = "embedded1";

                    // Append the p:timing to the p:sld
                    slidePart.RootElement.AppendChild(
                        new DocumentFormat.OpenXml.Presentation.Timing(
                            new DocumentFormat.OpenXml.Presentation.TimeNodeList(
                                new DocumentFormat.OpenXml.Presentation.ParallelTimeNode(
                                    new DocumentFormat.OpenXml.Presentation.CommonTimeNode(
                                        new DocumentFormat.OpenXml.Presentation.ChildTimeNodeList(
                                            new DocumentFormat.OpenXml.Presentation.SequenceTimeNode(
                                                new DocumentFormat.OpenXml.Presentation.CommonTimeNode(
                                                    new DocumentFormat.OpenXml.Presentation.ChildTimeNodeList(
                                                        new DocumentFormat.OpenXml.Presentation.ParallelTimeNode(
                                                            new DocumentFormat.OpenXml.Presentation.CommonTimeNode(
                                                                new DocumentFormat.OpenXml.Presentation.StartConditionList(
                                                                    new DocumentFormat.OpenXml.Presentation.Condition()
                    {
                        Delay = "indefinite"
                    },
                                                                    new DocumentFormat.OpenXml.Presentation.Condition(
                                                                        new DocumentFormat.OpenXml.Presentation.TimeNode()
                    {
                        Val = 2
                    })
                    {
                        Event = DocumentFormat.OpenXml.Presentation.TriggerEventValues.OnBegin, Delay = "0"
                    }),
                                                                new DocumentFormat.OpenXml.Presentation.ChildTimeNodeList(
                                                                    new DocumentFormat.OpenXml.Presentation.ParallelTimeNode(
                                                                        new DocumentFormat.OpenXml.Presentation.CommonTimeNode(
                                                                            new DocumentFormat.OpenXml.Presentation.StartConditionList(
                                                                                new DocumentFormat.OpenXml.Presentation.Condition()
                    {
                        Delay = "0"
                    }),
                                                                            new DocumentFormat.OpenXml.Presentation.ChildTimeNodeList(
                                                                                new DocumentFormat.OpenXml.Presentation.ParallelTimeNode(
                                                                                    new DocumentFormat.OpenXml.Presentation.CommonTimeNode(
                                                                                        new DocumentFormat.OpenXml.Presentation.StartConditionList(
                                                                                            new DocumentFormat.OpenXml.Presentation.Condition()
                    {
                        Delay = "0"
                    }),
                                                                                        new DocumentFormat.OpenXml.Presentation.ChildTimeNodeList(
                                                                                            new DocumentFormat.OpenXml.Presentation.Animate(
                                                                                                new DocumentFormat.OpenXml.Presentation.CommonBehavior(
                                                                                                    new DocumentFormat.OpenXml.Presentation.CommonTimeNode()
                    {
                        Id = 6, Duration = "1900", Fill = DocumentFormat.OpenXml.Presentation.TimeNodeFillValues.Hold
                    },
                                                                                                    new DocumentFormat.OpenXml.Presentation.TargetElement(
                                                                                                        new DocumentFormat.OpenXml.Presentation.ShapeTarget()
                    {
                        ShapeId = "2"
                    }),
                                                                                                    new DocumentFormat.OpenXml.Presentation.AttributeNameList(
                                                                                                        new DocumentFormat.OpenXml.Presentation.AttributeName("embedded1"))),
                                                                                                new DocumentFormat.OpenXml.Presentation.TimeAnimateValueList(
                                                                                                    new DocumentFormat.OpenXml.Presentation.TimeAnimateValue(
                                                                                                        new DocumentFormat.OpenXml.Presentation.VariantValue(
                                                                                                            new DocumentFormat.OpenXml.Presentation.FloatVariantValue()
                    {
                        Val = DocumentFormat.OpenXml.SingleValue.FromSingle(0)
                    }))
                    {
                        Time = "0"
                    },
                                                                                                    new DocumentFormat.OpenXml.Presentation.TimeAnimateValue(
                                                                                                        new DocumentFormat.OpenXml.Presentation.VariantValue(
                                                                                                            new DocumentFormat.OpenXml.Presentation.FloatVariantValue()
                    {
                        Val = DocumentFormat.OpenXml.SingleValue.FromSingle(1)
                    }))
                    {
                        Time = "100000"
                    }))
                    {
                        CalculationMode = DocumentFormat.OpenXml.Presentation.AnimateBehaviorCalculateModeValues.Linear, ValueType = DocumentFormat.OpenXml.Presentation.AnimateBehaviorValues.Number
                    }))
                    {
                        Id = 5, PresetId = 100, PresetClass = DocumentFormat.OpenXml.Presentation.TimeNodePresetClassValues.Emphasis, PresetSubtype = 1, RepeatCount = "indefinite", Fill = DocumentFormat.OpenXml.Presentation.TimeNodeFillValues.Hold, NodeType = DocumentFormat.OpenXml.Presentation.TimeNodeValues.WithEffect
                    })))
                    {
                        Id = 4, Fill = DocumentFormat.OpenXml.Presentation.TimeNodeFillValues.Hold
                    })))
                    {
                        Id = 3, Fill = DocumentFormat.OpenXml.Presentation.TimeNodeFillValues.Hold
                    })))
                    {
                        Id = 2, Duration = "indefinite", NodeType = DocumentFormat.OpenXml.Presentation.TimeNodeValues.MainSequence
                    },
                                                new DocumentFormat.OpenXml.Presentation.PreviousConditionList(
                                                    new DocumentFormat.OpenXml.Presentation.Condition(
                                                        new DocumentFormat.OpenXml.Presentation.TargetElement(
                                                            new DocumentFormat.OpenXml.Presentation.SlideTarget()))
                    {
                        Event = DocumentFormat.OpenXml.Presentation.TriggerEventValues.OnPrevious, Delay = "0"
                    }),
                                                new DocumentFormat.OpenXml.Presentation.NextConditionList(
                                                    new DocumentFormat.OpenXml.Presentation.Condition(
                                                        new DocumentFormat.OpenXml.Presentation.TargetElement(
                                                            new DocumentFormat.OpenXml.Presentation.SlideTarget()))
                    {
                        Event = DocumentFormat.OpenXml.Presentation.TriggerEventValues.OnNext, Delay = "0"
                    }))
                    {
                        Concurrent = true, NextAction = DocumentFormat.OpenXml.Presentation.NextActionValues.Seek
                    }))
                    {
                        Id = 1, Duration = "indefinite", Restart = DocumentFormat.OpenXml.Presentation.TimeNodeRestartValues.Never, NodeType = DocumentFormat.OpenXml.Presentation.TimeNodeValues.TmingRoot
                    }))));
                }
            }
        }
예제 #10
0
        public void AddVideo(SlidePart slidepart, string videoFilePath, string videoCoverPath, D.Transform2D transform)
        {
            Slide     slide        = slidepart.Slide;
            ShapeTree shapeTree1   = slidepart.Slide.CommonSlideData.ShapeTree;
            var       ptrlid       = Doc.PresentationPart.GetIdOfPart(slidepart);
            var       picID        = AnalysisHelper.GetMaxId(shapeTree1);
            string    imgEmbedId   = string.Format("imgId{0}{1}{2}", ptrlid, picID, 1);
            string    videoEmbedId = string.Format("vidId{0}{1}{2}", ptrlid, picID, 2);
            string    mediaEmbedId = string.Format("medId{0}{1}{2}", ptrlid, picID, 3);

            Picture picture1 = new Picture();
            NonVisualPictureProperties nonVisualPictureProperties1 = new NonVisualPictureProperties();

            NonVisualDrawingProperties nonVisualDrawingProperties2 =
                new NonVisualDrawingProperties()
            {
                Id = (UInt32Value)3U, Name = videoEmbedId + ""
            };

            D.HyperlinkOnClick hyperlinkOnClick1 = new D.HyperlinkOnClick()
            {
                Id = "", Action = "ppaction://media"
            };
            nonVisualDrawingProperties2.Append(hyperlinkOnClick1);

            NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties1 = new NonVisualPictureDrawingProperties();

            D.PictureLocks pictureLocks1 = new D.PictureLocks()
            {
                NoChangeAspect = true
            };
            nonVisualPictureDrawingProperties1.Append(pictureLocks1);

            ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties2 = new ApplicationNonVisualDrawingProperties();

            D.VideoFromFile videoFromFile1 = new D.VideoFromFile()
            {
                Link = videoEmbedId
            };

            ApplicationNonVisualDrawingPropertiesExtensionList applicationNonVisualDrawingPropertiesExtensionList1 =
                new ApplicationNonVisualDrawingPropertiesExtensionList();
            ApplicationNonVisualDrawingPropertiesExtension applicationNonVisualDrawingPropertiesExtension1 =
                new ApplicationNonVisualDrawingPropertiesExtension()
            {
                Uri = "{DAA4B4D4-6D71-4841-9C94-3DE7FCFB9230}"
            };

            P14.Media media1 = new P14.Media()
            {
                Embed = mediaEmbedId
            };
            media1.AddNamespaceDeclaration("p14", "http://schemas.microsoft.com/office/powerpoint/2010/main");
            applicationNonVisualDrawingPropertiesExtension1.Append(media1);
            applicationNonVisualDrawingPropertiesExtensionList1.Append(applicationNonVisualDrawingPropertiesExtension1);

            applicationNonVisualDrawingProperties2.Append(videoFromFile1);
            applicationNonVisualDrawingProperties2.Append(applicationNonVisualDrawingPropertiesExtensionList1);

            nonVisualPictureProperties1.Append(nonVisualDrawingProperties2);
            nonVisualPictureProperties1.Append(nonVisualPictureDrawingProperties1);
            nonVisualPictureProperties1.Append(applicationNonVisualDrawingProperties2);

            BlipFill blipFill1 = new BlipFill();

            D.Blip blip1 = new D.Blip()
            {
                Embed = imgEmbedId
            };

            D.Stretch       stretch1       = new D.Stretch();
            D.FillRectangle fillRectangle1 = new D.FillRectangle();

            stretch1.Append(fillRectangle1);

            blipFill1.Append(blip1);
            blipFill1.Append(stretch1);

            ShapeProperties shapeProperties1 = new ShapeProperties();

            D.PresetGeometry presetGeometry1 = new D.PresetGeometry()
            {
                Preset = D.ShapeTypeValues.Rectangle
            };
            D.AdjustValueList adjustValueList1 = new D.AdjustValueList();

            presetGeometry1.Append(adjustValueList1);

            shapeProperties1.Append(transform);
            shapeProperties1.Append(presetGeometry1);

            picture1.Append(nonVisualPictureProperties1);
            picture1.Append(blipFill1);
            picture1.Append(shapeProperties1);

            shapeTree1.Append(picture1);

            if (!(slide.Timing?.ChildElements?.Count > 0))
            {
                AnalysisHelper.InitTiming(slide);
            }

            ImagePart imagePart = slidepart.AddImagePart(AnalysisHelper.GetImagePartType(videoCoverPath), imgEmbedId);

            using (var data = File.OpenRead(videoCoverPath))
            {
                imagePart.FeedData(data);
            };

            Doc.PartExtensionProvider.AddPartExtension("video/mp4", ".mp4");
            MediaDataPart mediaDataPart1 = Doc.CreateMediaDataPart("video/mp4", ".mp4");

            using (System.IO.Stream mediaDataPart1Stream = File.OpenRead(videoFilePath))
            {
                mediaDataPart1.FeedData(mediaDataPart1Stream);
            }
            slidepart.AddVideoReferenceRelationship(mediaDataPart1, videoEmbedId);
            slidepart.AddMediaReferenceRelationship(mediaDataPart1, mediaEmbedId);
            slide.Save();
        }
예제 #11
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);
        }
예제 #12
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);
                }
            }
        }
        /// <summary>
        /// Builds out image as a Picture shape using BlipFill and appends it to the slide shapetree, using a shape from SlideLayout to determine size and location of image.
        /// </summary>
        /// <param name="slide">The slide to insert the image</param>
        /// <param name="layoutPlaceholderShape">The shape where the image will be inserted</param>
        /// <param name="imageLocation">URL to the local image file</param>
        /// <param name="shapeNumber">A unique positive integer for the shape relationship ID</param>
        public static void AddImageToSlide(this SlidePart slide, Shape layoutPlaceholderShape, string imageLocation, uint shapeNumber)
        {
            ShapeProperties shapeProperties = new ShapeProperties();

            // Generate a unique relationship ID to avoid collision
            string embedId = "rId" + (slide.Slide.Elements().Count() + 100 + shapeNumber).ToString();

            // Determine the image location from layout placeholder shape
            Drawing.Offset      imageOffset    = (Drawing.Offset)(layoutPlaceholderShape).ShapeProperties.Transform2D.Offset.Clone();
            Drawing.Extents     imageExtents   = (Drawing.Extents)(layoutPlaceholderShape).ShapeProperties.Transform2D.Extents.Clone();
            Drawing.Transform2D imageTransform = new Drawing.Transform2D();

            imageTransform.Append(imageExtents);
            imageTransform.Offset = imageOffset;
            shapeProperties.Append(imageTransform);

            // Preset geometry
            Drawing.PresetGeometry presetGeometry = new Drawing.PresetGeometry()
            {
                Preset = Drawing.ShapeTypeValues.Rectangle
            };
            Drawing.AdjustValueList adjustValueList = new Drawing.AdjustValueList();

            presetGeometry.Append(adjustValueList);
            shapeProperties.Append(presetGeometry);

            // Generate blip extension
            Drawing.BlipExtensionList blipExtensionList = new Drawing.BlipExtensionList();
            Drawing.BlipExtension     blipExtension     = new Drawing.BlipExtension()
            {
                Uri = $"{{{Guid.NewGuid().ToString()}}}"
            };

            // Local DPI (dots per square inch)
            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);

            // Set up blipfill for image
            Drawing.Blip    imageBlip = new Drawing.Blip();
            Drawing.Stretch stretch   = new Drawing.Stretch(new Drawing.FillRectangle());
            BlipFill        blipFill  = new BlipFill();

            imageBlip.Append(blipExtensionList);
            blipFill.Append(imageBlip);
            blipFill.Append(stretch);

            // Set up picture and nonvisual properties
            Picture picture = new Picture();
            NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties(
                new NonVisualDrawingProperties()
            {
                Id = (50U + shapeNumber), Name = "Picture " + shapeNumber
            },
                new NonVisualPictureDrawingProperties(new Drawing.PictureLocks()
            {
                NoChangeAspect = true
            }),
                new ApplicationNonVisualDrawingProperties()
                );

            picture.Append(nonVisualPictureProperties);
            picture.Append(blipFill);
            picture.Append(shapeProperties);

            //s.Parent.ReplaceChild(P, s);
            slide.Slide.CommonSlideData.ShapeTree.AppendChild(picture);

            // Determine ImagePart type
            ImagePart imagePart;

            switch (Path.GetExtension(imageLocation))
            {
            case ".jpg":
            case ".jpeg": imagePart = slide.AddImagePart(ImagePartType.Jpeg, embedId); break;

            case ".png": imagePart = slide.AddImagePart(ImagePartType.Png, embedId); break;

            case ".gif": imagePart = slide.AddImagePart(ImagePartType.Gif, embedId); break;

            case ".ico": imagePart = slide.AddImagePart(ImagePartType.Icon, embedId); break;

            default: throw new ArgumentException($"Error: Image file type '{Path.GetExtension(imageLocation)}' for file '{Path.GetFileNameWithoutExtension(imageLocation)}' not recognized!");
            }

            // Read the image file as a stream to ImagePart
            using (FileStream fs = File.OpenRead(imageLocation))
            {
                fs.Seek(0, SeekOrigin.Begin);
                imagePart.FeedData(fs);
            }

            imageBlip.Embed = embedId;
        }
예제 #14
0
        private static SlidePart CreateSlidePart(PresentationPart presentationPart)
        {
            SlidePart  slidePart1 = presentationPart.AddNewPart <SlidePart>("rId2");
            ImagePart  image      = slidePart1.AddImagePart(ImagePartType.Png, "relId12");
            FileStream fs         = new FileStream("d:\\2.jpg", FileMode.Open);

            image.FeedData(fs);
            fs.Close();

            slidePart1.Slide =
                new Slide(
                    new CommonSlideData(
                        new ShapeTree(
                            new P.NonVisualGroupShapeProperties(
                                new P.NonVisualDrawingProperties()
            {
                Id = (UInt32Value)1U, Name = ""
            },
                                new P.NonVisualGroupShapeDrawingProperties(),
                                new ApplicationNonVisualDrawingProperties()),
                            new GroupShapeProperties(
                                new D.TransformGroup(
                                    new D.Offset()
            {
                X = 0L, Y = 0L
            },
                                    new D.Extents()
            {
                Cx = 0L, Cy = 0L
            },
                                    new D.ChildOffset()
            {
                X = 0L, Y = 0L
            },
                                    new D.ChildExtents()
            {
                Cx = 0L, Cy = 0L
            })),
                            new P.Picture(
                                new P.NonVisualPictureProperties(
                                    new P.NonVisualDrawingProperties()
            {
                Id          = (UInt32Value)4U,
                Name        = "aa",
                Description = "aa"
            },
                                    new P.NonVisualPictureDrawingProperties(
                                        new D.PictureLocks()
            {
                NoChangeAspect = true
            }),
                                    new ApplicationNonVisualDrawingProperties()),
                                new P.BlipFill(
                                    new D.Blip()
            {
                Embed = "relId12"
            },
                                    new D.Stretch(
                                        new D.FillRectangle())),
                                new P.ShapeProperties(
                                    new D.Transform2D(
                                        new D.Offset()
            {
                X = 0L, Y = 0L
            },
                                        new D.Extents()
            {
                Cx = 9144000,
                Cy = 6858000
            }),
                                    new D.PresetGeometry(
                                        new D.AdjustValueList())
            {
                Preset = D.ShapeTypeValues.Rectangle
            }
                                    )))),
                    new ColorMapOverride(
                        new D.MasterColorMapping()));
            return(slidePart1);
        }
예제 #15
0
        public static void AddSvg(string docPath, string svgPath)
        {
            if (docPath == null)
            {
                throw new ArgumentNullException(nameof(docPath));
            }

            if (svgPath == null)
            {
                throw new ArgumentNullException(nameof(svgPath));
            }

            using (PresentationDocument presentationDocument = PresentationDocument.Open(docPath, true))
            {
                // Get the relationship ID of the first slide.
                PresentationPart presentationPart = presentationDocument.PresentationPart;

                // Verify that the presentation part and presentation exist.
                if (presentationPart != null && presentationPart.Presentation != null)
                {
                    OpenXmlElementList slideIds = presentationPart.Presentation.SlideIdList.ChildElements;

                    if (slideIds.Count > 0)
                    {
                        string    relId     = (slideIds[0] as SlideId).RelationshipId;
                        SlidePart slidePart = (SlidePart)presentationPart.GetPartById(relId);

                        // Get count of relationships and increment by one to make next unique id
                        int    partsCount = slidePart.Parts.Count();
                        string pngId      = $"rId{++partsCount}";
                        string svgId      = $"rId{++partsCount}";

                        var creationId = new DocumentFormat.OpenXml.Office2016.Drawing.CreationId();
                        creationId.AddNamespaceDeclaration("a16", "http://schemas.microsoft.com/office/drawing/2014/main");
                        creationId.Id = "{E36DC281-2F17-44E3-80EA-AB5BFA90E4D7}";

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

                        // add non visual properties to picture
                        picture.NonVisualPictureProperties = new DocumentFormat.OpenXml.Presentation.NonVisualPictureProperties();
                        picture.NonVisualPictureProperties.NonVisualDrawingProperties = new DocumentFormat.OpenXml.Presentation.NonVisualDrawingProperties()
                        {
                            Id = new UInt32Value((uint)++partsCount), Name = "Picture 1"
                        };
                        picture.NonVisualPictureProperties.NonVisualDrawingProperties.AppendChild(new DocumentFormat.OpenXml.Drawing.ExtensionList(
                                                                                                      new Extension(
                                                                                                          creationId)
                        {
                            Uri = "{FF2B5EF4-FFF2-40B4-BE49-F238E27FC236}"
                        }));
                        picture.NonVisualPictureProperties.NonVisualPictureDrawingProperties              = new DocumentFormat.OpenXml.Presentation.NonVisualPictureDrawingProperties();
                        picture.NonVisualPictureProperties.ApplicationNonVisualDrawingProperties          = new ApplicationNonVisualDrawingProperties();
                        picture.NonVisualPictureProperties.NonVisualPictureDrawingProperties.PictureLocks = new PictureLocks()
                        {
                            NoChangeAspect = true
                        };

                        // add blipfill
                        picture.BlipFill      = new DocumentFormat.OpenXml.Presentation.BlipFill();
                        picture.BlipFill.Blip = new Blip()
                        {
                            Embed = svgId
                        };
                        picture.BlipFill.AppendChild(new Stretch(
                                                         new FillRectangle()));
                        BlipExtensionList blipExtensionList = new BlipExtensionList();
                        Extension         ext = blipExtensionList.AppendChild(new Extension());
                        ext.Uri = string.Empty;
                        ext.AppendChild(new SVGBlip());
                        picture.BlipFill.Blip.AppendChild(blipExtensionList);
                        picture.ShapeProperties                        = new DocumentFormat.OpenXml.Presentation.ShapeProperties();
                        picture.ShapeProperties.Transform2D            = new Transform2D();
                        picture.ShapeProperties.Transform2D.Offset     = new Offset();
                        picture.ShapeProperties.Transform2D.Offset.X   = new Int64Value(5638800L);
                        picture.ShapeProperties.Transform2D.Offset.Y   = new Int64Value(2971800L);
                        picture.ShapeProperties.Transform2D.Extents    = new Extents();
                        picture.ShapeProperties.Transform2D.Extents.Cx = new Int64Value(914400L);
                        picture.ShapeProperties.Transform2D.Extents.Cy = new Int64Value(914400L);
                        picture.ShapeProperties.AppendChild(new PresetGeometry(
                                                                new AdjustValueList())
                        {
                            Preset = ShapeTypeValues.Rectangle
                        });

                        // Create a temporary in memory png file from the svg (inserting svg requires a png copy to be visible)
                        // Using https://www.nuget.org/packages/Svg/ to convert svg to png
                        SvgDocument svgDocument = SvgDocument.Open(svgPath);
                        using System.Drawing.Bitmap bitmap = svgDocument.Draw();
                        string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".png";
                        bitmap.Save(fileName, ImageFormat.Png);

                        // Add png to slidePart
                        using FileStream pngFileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                        pngFileStream.Seek(0, SeekOrigin.Begin);
                        ImagePart pngImagePart = slidePart.AddImagePart(ImagePartType.Png, pngId);
                        pngImagePart.FeedData(pngFileStream);
                        picture.BlipFill.Blip.Embed = pngId;

                        // Add image part with new svg id
                        using FileStream svgFileStream = new FileStream(svgPath, FileMode.Open, FileAccess.Read);
                        svgFileStream.Seek(0, SeekOrigin.Begin);
                        ImagePart svgImgPart = slidePart.AddImagePart(ImagePartType.Svg, svgId);
                        svgImgPart.FeedData(svgFileStream);
                        IEnumerable <SVGBlip> sVGBlips = blipExtensionList.Descendants <SVGBlip>();
                        sVGBlips.First().Embed         = svgId;
                        slidePart.Slide.CommonSlideData.ShapeTree.AppendChild(picture);
                    }
                }
            }
        }