Exemplo n.º 1
0
 internal override void BeforeSave()
 {
     if (_patternFill != null)
     {
         PatternFill.UpdateXml();
     }
     else if (_blipFill != null)
     {
         BlipFill.UpdateXml();
     }
     else
     {
         base.BeforeSave();
     }
 }
Exemplo n.º 2
0
        private void LoadImage(Worksheet ws, WorksheetPart wsp, WorkbookPart wp)
        {
            string       path = System.IO.Path.Combine(Server.MapPath("~/Scripts/Images"), "unnamed.png").ToString();
            DrawingsPart dp   = wsp.AddNewPart <DrawingsPart>();
            ImagePart    imgp = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));

            using (FileStream fs = new FileStream(path, FileMode.Open))
            {
                imgp.FeedData(fs);
            }

            NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();

            nvdp.Id          = 1025;
            nvdp.Name        = "Picture 1";
            nvdp.Description = "polymathlogo";
            DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
            picLocks.NoChangeAspect     = true;
            picLocks.NoChangeArrowheads = true;
            NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();

            nvpdp.PictureLocks = picLocks;
            NonVisualPictureProperties nvpp = new NonVisualPictureProperties();

            nvpp.NonVisualDrawingProperties        = nvdp;
            nvpp.NonVisualPictureDrawingProperties = nvpdp;

            DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
            stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

            BlipFill blipFill = new BlipFill();

            DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
            blip.Embed               = dp.GetIdOfPart(imgp);
            blip.CompressionState    = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
            blipFill.Blip            = blip;
            blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
            blipFill.Append(stretch);

            DocumentFormat.OpenXml.Drawing.Transform2D t2d    = new DocumentFormat.OpenXml.Drawing.Transform2D();
            DocumentFormat.OpenXml.Drawing.Offset      offset = new DocumentFormat.OpenXml.Drawing.Offset();
            offset.X   = 0;
            offset.Y   = 0;
            t2d.Offset = offset;
            System.Drawing.Bitmap bm = new System.Drawing.Bitmap(path);
            //http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
            //http://stackoverflow.com/questions/1341930/pixel-to-centimeter
            //http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
            DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
            extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
            extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
            bm.Dispose();
            t2d.Extents = extents;
            ShapeProperties sp = new ShapeProperties();

            sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
            sp.Transform2D    = t2d;
            DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
            prstGeom.Preset          = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
            prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
            sp.Append(prstGeom);
            sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

            DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
            picture.NonVisualPictureProperties = nvpp;
            picture.BlipFill        = blipFill;
            picture.ShapeProperties = sp;

            Position pos = new Position();

            pos.X = 0;
            pos.Y = 0;
            Extent ext = new Extent();

            ext.Cx = extents.Cx;
            ext.Cy = extents.Cy;
            AbsoluteAnchor anchor = new AbsoluteAnchor();

            anchor.Position = pos;
            anchor.Extent   = ext;
            anchor.Append(picture);
            anchor.Append(new ClientData());
            WorksheetDrawing wsd = new WorksheetDrawing();

            wsd.Append(anchor);
            Drawing drawing = new Drawing();

            drawing.Id = dp.GetIdOfPart(imgp);

            wsd.Save(dp);
            ws.Append(drawing);
        }
Exemplo n.º 3
0
        /// <summary>
        /// Lấy màu Image Slide
        /// </summary>
        /// <param name="slide"></param>
        /// <param name="openXmlPart"></param>
        /// <param name="blipFill"></param>
        /// <returns></returns>
        private ImageColor GetImageColor(pp.FillFormat fill, OpenXmlPart openXmlPart, BlipFill blipFill)
        {
            ImagePart part = null;
            IEnumerable <DocumentFormat.OpenXml.Presentation.Picture> lstPic = null;

            if (openXmlPart is SlidePart slidePart)
            {
                lstPic = slidePart.Slide.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);
                if (lstPic != null)
                {
                    string rID = blipFill.Blip.Embed.Value;
                    part = (ImagePart)slidePart.GetPartById(rID);
                }
            }
            else if (openXmlPart is SlideMasterPart slideMasterPart)
            {
                lstPic = slideMasterPart.SlideMaster.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);
                if (lstPic != null)
                {
                    string rID = blipFill.Blip.Embed.Value;
                    part = (ImagePart)slideMasterPart.GetPartById(rID);
                }
            }
            else if (openXmlPart is SlideLayoutPart slideLayoutPart)
            {
                lstPic = slideLayoutPart.SlideLayout.Descendants <DocumentFormat.OpenXml.Presentation.Picture>().Select(p => p);
                if (lstPic != null)
                {
                    string rID = blipFill.Blip.Embed.Value;
                    part = (ImagePart)slideLayoutPart.GetPartById(rID);
                }
            }
            if (lstPic != null && part != null)
            {
                string pathImage = System.IO.Path.Combine((System.Windows.Application.Current as IAppGlobal).DocumentTempFolder, ObjectElementsHelper.RandomString(13) + System.IO.Path.GetExtension(part.Uri.ToString()));
                Utils.CopyStream(part.GetStream(), pathImage);
                ImageColor imageColor = new ImageColor();
                imageColor.Source           = new Core.Model.Image(pathImage);
                imageColor.Opacity          = 1 - fill.Transparency;
                imageColor.OffsetX          = fill.TextureOffsetX;
                imageColor.OffsetY          = fill.TextureOffsetY;
                imageColor.IsTiled          = fill.TextureTile == MsoTriState.msoTrue;
                imageColor.Alignment        = ConvertImageAligment(fill.TextureAlignment);
                imageColor.ScaleX           = fill.TextureHorizontalScale;
                imageColor.ScaleY           = fill.TextureVerticalScale;
                imageColor.RotateWidthShape = fill.RotateWithObject == MsoTriState.msoTrue;
                foreach (var item in blipFill)
                {
                    if (item is Stretch stretch)
                    {
                        if (stretch.FillRectangle.Top != null)
                        {
                            imageColor.OffsetTop = stretch.FillRectangle.Top / 100000;
                        }
                        if (stretch.FillRectangle.Left != null)
                        {
                            imageColor.OffsetLeft = stretch.FillRectangle.Left / 100000;
                        }
                        if (stretch.FillRectangle.Right != null)
                        {
                            imageColor.OffsetRight = stretch.FillRectangle.Right / 100000;
                        }
                        if (stretch.FillRectangle.Bottom != null)
                        {
                            imageColor.OffsetBottom = stretch.FillRectangle.Bottom / 100000;
                        }
                    }
                }
                return(imageColor);
            }
            return(null);
        }
Exemplo n.º 4
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();
        }
Exemplo n.º 5
0
        public void InsertImage(long x, long y, long?width, long?height, string sImagePath)
        {
            try
            {
                WorksheetPart    wsp = CurrentWorksheetPart;
                DrawingsPart     dp;
                ImagePart        imgp;
                WorksheetDrawing wsd;

                ImagePartType ipt;
                switch (sImagePath.Substring(sImagePath.LastIndexOf('.') + 1).ToLower())
                {
                case "png":
                    ipt = ImagePartType.Png;
                    break;

                case "jpg":
                case "jpeg":
                    ipt = ImagePartType.Jpeg;
                    break;

                case "gif":
                    ipt = ImagePartType.Gif;
                    break;

                default:
                    return;
                }

                if (wsp.DrawingsPart == null)
                {
                    //----- no drawing part exists, add a new one

                    dp   = wsp.AddNewPart <DrawingsPart>();
                    imgp = dp.AddImagePart(ipt, wsp.GetIdOfPart(dp));
                    wsd  = new WorksheetDrawing();
                }
                else
                {
                    //----- use existing drawing part

                    dp   = wsp.DrawingsPart;
                    imgp = dp.AddImagePart(ipt);
                    dp.CreateRelationshipToPart(imgp);
                    wsd = dp.WorksheetDrawing;
                }

                using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
                {
                    imgp.FeedData(fs);
                }

                int imageNumber = dp.ImageParts.Count <ImagePart>();
                if (imageNumber == 1)
                {
                    Drawing drawing = new Drawing();
                    drawing.Id = dp.GetIdOfPart(imgp);
                    CurrentWorksheetPart.Worksheet.Append(drawing);
                }

                NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
                nvdp.Id          = new UInt32Value((uint)(1024 + imageNumber));
                nvdp.Name        = "Picture " + imageNumber.ToString();
                nvdp.Description = "";
                DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
                picLocks.NoChangeAspect     = true;
                picLocks.NoChangeArrowheads = true;
                NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
                nvpdp.PictureLocks = picLocks;
                NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
                nvpp.NonVisualDrawingProperties        = nvdp;
                nvpp.NonVisualPictureDrawingProperties = nvpdp;

                DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
                stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

                BlipFill blipFill = new BlipFill();
                DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
                blip.Embed               = dp.GetIdOfPart(imgp);
                blip.CompressionState    = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
                blipFill.Blip            = blip;
                blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
                blipFill.Append(stretch);

                DocumentFormat.OpenXml.Drawing.Transform2D t2d    = new DocumentFormat.OpenXml.Drawing.Transform2D();
                DocumentFormat.OpenXml.Drawing.Offset      offset = new DocumentFormat.OpenXml.Drawing.Offset();
                offset.X   = 0;
                offset.Y   = 0;
                t2d.Offset = offset;
                Bitmap bm = new Bitmap(sImagePath);

                DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();

                if (width == null)
                {
                    extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
                }
                else
                {
                    extents.Cx = width * (long)((float)914400 / bm.HorizontalResolution);
                }

                if (height == null)
                {
                    extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);
                }
                else
                {
                    extents.Cy = height * (long)((float)914400 / bm.VerticalResolution);
                }

                bm.Dispose();
                t2d.Extents = extents;
                ShapeProperties sp = new ShapeProperties();
                sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
                sp.Transform2D    = t2d;
                DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
                prstGeom.Preset          = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
                prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
                sp.Append(prstGeom);
                sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

                DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
                picture.NonVisualPictureProperties = nvpp;
                picture.BlipFill        = blipFill;
                picture.ShapeProperties = sp;

                Position pos = new Position();
                pos.X = x * 914400 / 72;
                pos.Y = y * 914400 / 72;
                Extent ext = new Extent();
                ext.Cx = extents.Cx;
                ext.Cy = extents.Cy;
                AbsoluteAnchor anchor = new AbsoluteAnchor();
                anchor.Position = pos;
                anchor.Extent   = ext;
                anchor.Append(picture);
                anchor.Append(new ClientData());
                wsd.Append(anchor);
                wsd.Save(dp);
            }
            catch (Exception ex)
            {
                throw ex; // or do something more interesting if you want
            }
        }
Exemplo n.º 6
0
        private void PlaceImageOnCell(Worksheet worksheet, Bitmap image, int Col, int Row, double colWid, double rowHeight, string type, string imgName = "", string imgDesc = "")//, float? W, float? H)
        {
            Dictionary <string, ImagePartType> mimeToImagePartType = new Dictionary <string, ImagePartType>()
            {
                { "image/bmp", ImagePartType.Bmp },
                { "image/gif", ImagePartType.Gif },
                { "image/jpg", ImagePartType.Jpeg },
                { "image/jpeg", ImagePartType.Jpeg },
                { "image/png", ImagePartType.Png },
                { "image/tiff", ImagePartType.Tiff }
            };

            try
            {
                ImagePart     imagePart;
                ImagePartType ip;
                if (!mimeToImagePartType.TryGetValue(type, out ip))
                {
                    ip = ImagePartType.Jpeg;
                }
                WorksheetDrawing wsd;
                DrawingsPart     dp;
                WorksheetPart    worksheetPart = worksheet.WorksheetPart;

                double imgMargin = 5;

                //string sImagePath = "D:/Documents/Source/Repos/DarrylSite/DarrylSite/Images/DC.png";
                if (worksheetPart.DrawingsPart == null)
                {
                    dp        = worksheetPart.AddNewPart <DrawingsPart>();
                    imagePart = dp.AddImagePart(ip, worksheetPart.GetIdOfPart(dp));
                    wsd       = new WorksheetDrawing();
                }
                else
                {
                    dp        = worksheetPart.DrawingsPart;
                    imagePart = dp.AddImagePart(ip);
                    dp.CreateRelationshipToPart(imagePart);
                    wsd = dp.WorksheetDrawing;
                }

                NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();
                nvdp.Id          = GetNextImageId();
                nvdp.Name        = imgName;
                nvdp.Description = imgDesc;
                DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
                picLocks.NoChangeAspect     = true;
                picLocks.NoChangeArrowheads = true;
                NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();
                nvpdp.PictureLocks = picLocks;
                NonVisualPictureProperties nvpp = new NonVisualPictureProperties();
                nvpp.NonVisualDrawingProperties        = nvdp;
                nvpp.NonVisualPictureDrawingProperties = nvpdp;

                DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
                stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

                BlipFill blipFill = new BlipFill();
                DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
                blip.Embed            = dp.GetIdOfPart(imagePart);
                blip.CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Email;

                /*
                 *  string outerXml =
                 *      "<a:ext uri=\"{28A0092B-C50C-407E-A947-70E740481C1C}\">" +
                 *      "<a14:useLocalDpi xmlns:a14 = \"http://schemas.microsoft.com/office/drawing/2010/main\"/>" +
                 *      "</a:ext> ";
                 *
                 *  string outerXml = "uri=\"{28A0092B-C50C-407E-A947-70E740481C1C}\">";
                 */
                A14.UseLocalDpi localDpi = new A14.UseLocalDpi();

                /*
                 * ExtensionList extLst = new ExtensionList();
                 * Extension extsn = new Extension(localDpi);
                 * extsn.Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}";
                 * extLst.Append(extsn);
                 * blip.Append(extLst);
                 */
                A.BlipExtensionList blipExtLst = new A.BlipExtensionList();
                A.BlipExtension     blipExt    = new A.BlipExtension()
                {
                    Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}"
                };
                localDpi.AddNamespaceDeclaration("a14", "http://schemas.microsoft.com/office/drawing/2010/main");
                blipExt.Append(localDpi);
                blipExtLst.Append(blipExt);
                blip.Append(blipExtLst);

                blip.Append();
                blipFill.Blip            = blip;
                blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
                blipFill.Append(stretch);

                DocumentFormat.OpenXml.Drawing.Transform2D t2d    = new DocumentFormat.OpenXml.Drawing.Transform2D();
                DocumentFormat.OpenXml.Drawing.Offset      offset = new DocumentFormat.OpenXml.Drawing.Offset();
                offset.X   = 0;
                offset.Y   = 0;
                t2d.Offset = offset;
                //Bitmap bm = new Bitmap(sImagePath);
                //http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
                //http://stackoverflow.com/questions/1341930/pixel-to-centimeter
                //http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
                DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();
                //extents.Cy = (long)image.Height * (long)((float)914400 / image.VerticalResolution);
                //extents.Cy = (int)(rowHeight * 72 / 96 * (100 - (2 * imgMargin)) / 100) * 12700;
                extents.Cy = (int)((rowHeight * 72 / 96 * 12700) * (((100 - (2 * imgMargin)) / 100)));
                //extents.Cx = (int)(((((colWid - 1) * 7) + 12) * 12700) * (.5 * image.Height / image.Width));
                //extents.Cx = (int)(((((colWid - 1) * 7) + 12) * 12700) * (.5 * extents.Cy / image.Width));
                extents.Cx = image.Width * extents.Cy / image.Height;
                ;
                t2d.Extents = extents;
                ShapeProperties sp = new ShapeProperties();
                sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
                sp.Transform2D    = t2d;
                DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
                prstGeom.Preset          = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
                prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
                sp.Append(prstGeom);
                sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

                DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
                picture.NonVisualPictureProperties = nvpp;
                picture.BlipFill        = blipFill;
                picture.ShapeProperties = sp;

                Xdr.FromMarker fromMarker = new Xdr.FromMarker();
                Xdr.ToMarker   toMarker   = new Xdr.ToMarker();

                // From
                ColumnId columnId1 = new ColumnId();
                columnId1.Text = Col.ToString();
                ColumnOffset columnOffset1 = new ColumnOffset();
                //columnOffset1.Text = "228600";
                double colloff = ((((colWid - 1) * 7) + 12) * 12700) * 72 / 96;
                colloff           -= extents.Cx;
                colloff           /= 2;
                colloff            = (int)colloff;
                columnOffset1.Text = colloff.ToString();

                RowId rowId1 = new RowId();
                rowId1.Text = Row.ToString();
                RowOffset rowOffset1 = new RowOffset();

                double rowoff = (int)((rowHeight * 72 / 96 * 12700) * (imgMargin / 100));

                rowOffset1.Text = (rowoff).ToString();

                fromMarker.Append(columnId1);
                fromMarker.Append(columnOffset1);
                fromMarker.Append(rowId1);
                fromMarker.Append(rowOffset1);

                // To
                ColumnId     columnId2     = new ColumnId();
                ColumnOffset columnOffset2 = new ColumnOffset();
                RowId        rowId2        = new RowId();
                RowOffset    rowOffset2    = new RowOffset();

                columnId2.Text     = (Col).ToString();
                columnOffset2.Text = "0";// "152381";
                // Margin is accounted for, so take it off the width
                columnOffset2.Text = (extents.Cx + colloff).ToString();

                rowId2.Text     = (Row).ToString();
                rowOffset2.Text = "4572000";                        // 4572000 = 12700 (#EMUs/pixel) * 45 (Olivia's cell height in Excel Cell units (aka 60 pixels)) * 8 (???)
                rowOffset2.Text = (extents.Cy + rowoff).ToString(); //

                toMarker.Append(columnId2);
                toMarker.Append(columnOffset2);
                toMarker.Append(rowId2);
                toMarker.Append(rowOffset2);

                //Position pos = new Position(); pos.X = Row; pos.Y = Col;
                Extent ext = new Extent(); ext.Cx = extents.Cx; ext.Cy = extents.Cy;

                TwoCellAnchor anchor = new TwoCellAnchor();
                //OneCellAnchor anchor = new OneCellAnchor();
                anchor.Append(fromMarker);
                anchor.Append(toMarker);
                //anchor.Extent = ext;
                //anchor.Append(toMarker);
                anchor.Append(picture);
                anchor.Append(new ClientData());
                wsd.Append(anchor);
                {
                    MemoryStream     imgStream = new MemoryStream();
                    ImageCodecInfo[] codecs    = ImageCodecInfo.GetImageEncoders();
                    ImageCodecInfo   codec     = codecs.First(c => c.MimeType == type);
                    Guid             imgGuid   = codec.FormatID;
                    ImageFormat      imf       = new ImageFormat(imgGuid);
                    float            h         = image.HorizontalResolution;
                    float            v         = image.VerticalResolution;

                    Bitmap    compressedImage = new Bitmap(64, 64);//, gr);
                    Rectangle rect            = new Rectangle(0, 0, 64, 64);
                    Graphics  gr = Graphics.FromImage(compressedImage);
                    gr.DrawImage(image, rect);
                    compressedImage.SetResolution(48, 48);

                    compressedImage.Save(imgStream, imf);
                    gr.Dispose();
                    compressedImage.Dispose();
                    imgStream.Position = 0;
                    imagePart.FeedData(imgStream);
                    imgStream.Dispose();
                }
                if (drawing == null)
                {
                    drawing    = new Drawing();
                    drawing.Id = dp.GetIdOfPart(imagePart);
                    worksheet.Append(drawing);
                }
                wsd.Save(dp);
                worksheetPart.Worksheet.Save();
                /* Sheets sheets = new Sheets();Sheet sheet = new Sheet();sheet.Name = "Sheet1";sheet.SheetId = 1;sheet.Id = wbp.GetIdOfPart(wsp);sheets.Append(sheet);wb.Append(sheets); */
            }
            catch (Exception e)
            {
                ModelState.AddModelError("Caught fatal exception placing image", e);
                Trace.TraceError($"OJException: Could not place image {e.Message}");
            }
        }
        /// <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;
        }
Exemplo n.º 8
0
        private void BuildWorkbook(string filename)
        {
            try
            {
                using (SpreadsheetDocument xl = SpreadsheetDocument.Create(filename, SpreadsheetDocumentType.Workbook))
                {
                    var wbp = xl.AddWorkbookPart();
                    var wsp = wbp.AddNewPart <WorksheetPart>();
                    var wb  = new Workbook();
                    var fv  = new FileVersion {
                        ApplicationName = "Microsoft Office Excel"
                    };
                    var ws = new Worksheet();
                    var sd = new SheetData();

                    var wbsp = wbp.AddNewPart <WorkbookStylesPart>();
                    wbsp.Stylesheet = CreateStylesheet();
                    wbsp.Stylesheet.Save();

                    var sImagePath = "polymathlogo.png";
                    var dp         = wsp.AddNewPart <DrawingsPart>();
                    var imgp       = dp.AddImagePart(ImagePartType.Png, wsp.GetIdOfPart(dp));
                    using (FileStream fs = new FileStream(sImagePath, FileMode.Open))
                    {
                        imgp.FeedData(fs);
                    }

                    var nvdp = new NonVisualDrawingProperties
                    {
                        Id          = 1025,
                        Name        = "Picture 1",
                        Description = "polymathlogo"
                    };
                    var picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks
                    {
                        NoChangeAspect     = true,
                        NoChangeArrowheads = true
                    };
                    var nvpdp = new NonVisualPictureDrawingProperties
                    {
                        PictureLocks = picLocks
                    };
                    var nvpp = new NonVisualPictureProperties
                    {
                        NonVisualDrawingProperties        = nvdp,
                        NonVisualPictureDrawingProperties = nvpdp
                    };

                    var stretch = new DocumentFormat.OpenXml.Drawing.Stretch
                    {
                        FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle()
                    };

                    var blip = new DocumentFormat.OpenXml.Drawing.Blip
                    {
                        Embed            = dp.GetIdOfPart(imgp),
                        CompressionState = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print
                    };

                    var blipFill = new BlipFill
                    {
                        Blip            = blip,
                        SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle()
                    };
                    blipFill.Append(stretch);

                    var offset = new DocumentFormat.OpenXml.Drawing.Offset
                    {
                        X = 0,
                        Y = 0
                    };
                    var t2d = new DocumentFormat.OpenXml.Drawing.Transform2D
                    {
                        Offset = offset
                    };

                    var bm = Xwt.Drawing.Image.FromFile(sImagePath).ToBitmap();
                    //http://en.wikipedia.org/wiki/English_Metric_Unit#DrawingML
                    //http://stackoverflow.com/questions/1341930/pixel-to-centimeter
                    //http://stackoverflow.com/questions/139655/how-to-convert-pixels-to-points-px-to-pt-in-net-c
                    var extents = new DocumentFormat.OpenXml.Drawing.Extents
                    {
                        Cx = (long)bm.Width * (long)((float)914400 / bm.PixelWidth),
                        Cy = (long)bm.Height * (long)((float)914400 / bm.PixelHeight)
                    };
                    bm.Dispose();
                    t2d.Extents = extents;
                    var prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry
                    {
                        Preset          = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle,
                        AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList()
                    };
                    var sp = new ShapeProperties
                    {
                        BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto,
                        Transform2D    = t2d
                    };
                    sp.Append(prstGeom);
                    sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

                    var picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture
                    {
                        NonVisualPictureProperties = nvpp,
                        BlipFill        = blipFill,
                        ShapeProperties = sp
                    };

                    var pos = new Position {
                        X = 0, Y = 0
                    };
                    Extent ext = new Extent {
                        Cx = extents.Cx, Cy = extents.Cy
                    };
                    var anchor = new AbsoluteAnchor
                    {
                        Position = pos,
                        Extent   = ext
                    };
                    anchor.Append(picture);
                    anchor.Append(new ClientData());

                    var wsd = new WorksheetDrawing();
                    wsd.Append(anchor);
                    var drawing = new Drawing {
                        Id = dp.GetIdOfPart(imgp)
                    };

                    wsd.Save(dp);

                    UInt32 index;
                    Random rand = new Random();

                    sd.Append(CreateHeader(10));
                    sd.Append(CreateColumnHeader(11));

                    for (index = 12; index < 30; ++index)
                    {
                        sd.Append(CreateContent(index, ref rand));
                    }

                    ws.Append(sd);
                    ws.Append(drawing);
                    wsp.Worksheet = ws;
                    wsp.Worksheet.Save();
                    Sheets sheets = new Sheets();
                    Sheet  sheet  = new Sheet
                    {
                        Name    = "Sheet1",
                        SheetId = 1,
                        Id      = wbp.GetIdOfPart(wsp)
                    };
                    sheets.Append(sheet);
                    wb.Append(fv);
                    wb.Append(sheets);

                    xl.WorkbookPart.Workbook = wb;
                    xl.WorkbookPart.Workbook.Save();
                    xl.Close();
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine(e.ToString());
            }
        }
Exemplo n.º 9
0
        internal static Picture AddPicture(this Slide slide, Shape referingShape, string imageFile)
        {
            Picture picture = new Picture();

            string      embedId = string.Empty;
            UInt32Value picId   = 10001U;
            string      name    = string.Empty;

            if (slide.Elements <Picture>().Count() > 0)
            {
                picId = ++slide.Elements <Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
            }
            name    = "image" + picId.ToString();
            embedId = "rId" + (slide.Elements <Picture>().Count() + 915).ToString(); // some value

            NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
            {
                NonVisualDrawingProperties = new NonVisualDrawingProperties()
                {
                    Name = name, Id = picId, Title = name
                },
                NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties()
                {
                    PictureLocks = new Drawing.PictureLocks()
                    {
                        NoChangeAspect = true
                    }
                },
                ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties()
                {
                    UserDrawn = true
                }
            };

            BlipFill blipFill = new BlipFill()
            {
                Blip = new Drawing.Blip()
                {
                    Embed = embedId
                }
            };

            Drawing.Stretch stretch = new Drawing.Stretch()
            {
                FillRectangle = new Drawing.FillRectangle()
            };
            blipFill.Append(stretch);

            ShapeProperties shapeProperties = new ShapeProperties()
            {
                Transform2D = new Drawing.Transform2D()
                {
                    Offset = new Drawing.Offset()
                    {
                        X = 1554691, Y = 1600200
                    },
                    Extents = new Drawing.Extents()
                    {
                        Cx = 6034617, Cy = 4525963
                    }
                }
            };

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

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

            slide.CommonSlideData.ShapeTree.Append(picture);

            // Add Image part
            slide.AddImagePart(embedId, imageFile);

            slide.Save();
            return(picture);
        }
Exemplo n.º 10
0
        public void AddImageContent(ShapeTree shapeTree1, uint ObjectID, PPTXImage Content)
        {
            Picture picture3 = new Picture();

            NonVisualPictureProperties nonVisualPictureProperties3 = new NonVisualPictureProperties();

            NonVisualDrawingProperties nonVisualDrawingProperties83 = new NonVisualDrawingProperties()
            {
                Id = ObjectID, Name = $"Content{ObjectID}"
            };

            A.NonVisualDrawingPropertiesExtensionList nonVisualDrawingPropertiesExtensionList5 = new A.NonVisualDrawingPropertiesExtensionList();

            nonVisualDrawingProperties83.Append(nonVisualDrawingPropertiesExtensionList5);

            NonVisualPictureDrawingProperties nonVisualPictureDrawingProperties3 = new NonVisualPictureDrawingProperties();

            A.PictureLocks pictureLocks3 = new A.PictureLocks()
            {
                NoChangeAspect = true
            };

            nonVisualPictureDrawingProperties3.Append(pictureLocks3);
            ApplicationNonVisualDrawingProperties applicationNonVisualDrawingProperties83 = new ApplicationNonVisualDrawingProperties();

            nonVisualPictureProperties3.Append(nonVisualDrawingProperties83);
            nonVisualPictureProperties3.Append(nonVisualPictureDrawingProperties3);
            nonVisualPictureProperties3.Append(applicationNonVisualDrawingProperties83);

            BlipFill blipFill3 = new BlipFill();

            A.Blip blip3 = new A.Blip()
            {
                Embed = ImageIDMap[Content.ImageFilePath]
            };

            A.BlipExtensionList blipExtensionList1 = new A.BlipExtensionList();

            blip3.Append(blipExtensionList1);

            A.Stretch       stretch3       = new A.Stretch();
            A.FillRectangle fillRectangle3 = new A.FillRectangle();

            stretch3.Append(fillRectangle3);

            blipFill3.Append(blip3);
            blipFill3.Append(stretch3);

            ShapeProperties shapeProperties70 = new ShapeProperties();


            A.PresetGeometry presetGeometry10 = new A.PresetGeometry()
            {
                Preset = A.ShapeTypeValues.Rectangle
            };
            A.AdjustValueList adjustValueList10 = new A.AdjustValueList();

            presetGeometry10.Append(adjustValueList10);

            A.Transform2D transform2D25 = SlideWriterHelper.CreateTransform2D(Content.Transform);
            if (transform2D25 != null)
            {
                shapeProperties70.Append(transform2D25);
            }

            shapeProperties70.Append(presetGeometry10);

            picture3.Append(nonVisualPictureProperties3);
            picture3.Append(blipFill3);
            picture3.Append(shapeProperties70);

            shapeTree1.Append(picture3);
        }
Exemplo n.º 11
0
        private static Picture AddPicture(Slide slide, Shape referingShape, string imageFile)
        {
            Picture picture = new Picture();

            string embedId = string.Empty;

            DocumentFormat.OpenXml.UInt32Value picId = 10001U;
            string name = string.Empty;

            if (slide.Elements <Picture>().Count() > 0)
            {
                picId = ++slide.Elements <Picture>().ToList().Last().NonVisualPictureProperties.NonVisualDrawingProperties.Id;
            }
            name    = "image" + picId.ToString();
            embedId = "rId" + (slide.Elements <Picture>().Count() + 915).ToString(); // some value

            NonVisualPictureProperties nonVisualPictureProperties = new NonVisualPictureProperties()
            {
                NonVisualDrawingProperties = new NonVisualDrawingProperties()
                {
                    Name = name, Id = picId, Title = name
                },
                NonVisualPictureDrawingProperties = new NonVisualPictureDrawingProperties()
                {
                    PictureLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks()
                    {
                        NoChangeAspect = true
                    }
                },
                ApplicationNonVisualDrawingProperties = new ApplicationNonVisualDrawingProperties()
                {
                    UserDrawn = true
                }
            };

            BlipFill blipFill = new BlipFill()
            {
                Blip = new DocumentFormat.OpenXml.Drawing.Blip()
                {
                    Embed = embedId
                }
            };

            DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch()
            {
                FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle()
            };
            blipFill.Append(stretch);

            ShapeProperties shapeProperties = new ShapeProperties()
            {
                Transform2D = new DocumentFormat.OpenXml.Drawing.Transform2D()
                {
                    //MMS:4
                    Offset = new DocumentFormat.OpenXml.Drawing.Offset()
                    {
                        X = 1565275, Y = 612775
                    },                                                                               // { X = 457200L, Y = 1124000L }
                    Extents = new DocumentFormat.OpenXml.Drawing.Extents()
                    {
                        Cx = 5486400, Cy = 4114800
                    }                                                                                    //{ Cx = 8229600L, Cy = 5029200L }
                }

                //<a:off x="1565275" y="612775" />
                //<a:ext cx="5486400" cy="4114800" />
            };

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

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

            slide.CommonSlideData.ShapeTree.Append(picture);

            // Add Image part
            AddImagePart(slide, embedId, imageFile);

            slide.Save();
            return(picture);
        }
Exemplo n.º 12
0
        // -----------------------------------------------------------------------------------------
        // http://polymathprogrammer.com/2010/11/10/how-to-insert-multiple-images-in-excel-open-xml/
        // November 10, 2010 by Vincent Tan
        // -----------------------------------------------------------------------------------------
        // Funcion to insert an .jpg image into an EXCEL worksheet
        private void InsertImage(WorksheetPart worksheetpart, string imagepath)
        {
            long             xpos      = 4000000;
            long             ypos      = 100000;
            Worksheet        worksheet = worksheetpart.Worksheet;
            DrawingsPart     dp;
            ImagePart        imgp;
            WorksheetDrawing wsd;
            ImagePartType    ipt = ImagePartType.Jpeg;

            // Create new or use existing Drawing part
            if (worksheetpart.DrawingsPart == null)
            {
                dp   = worksheetpart.AddNewPart <DrawingsPart>();
                imgp = dp.AddImagePart(ipt, worksheetpart.GetIdOfPart(dp));
                wsd  = new WorksheetDrawing();
            }
            else
            {
                dp   = worksheetpart.DrawingsPart;
                imgp = dp.AddImagePart(ipt);
                dp.CreateRelationshipToPart(imgp);
                wsd = dp.WorksheetDrawing;
            }

            using (FileStream fs = new FileStream(imagepath, FileMode.Open)) { imgp.FeedData(fs); }

            int imageNumber = dp.ImageParts.Count <ImagePart>();

            if (imageNumber == 1)
            {
                Drawing drawing = new Drawing();
                drawing.Id = dp.GetIdOfPart(imgp);
                worksheet.Append(drawing);
            }

            NonVisualDrawingProperties nvdp = new NonVisualDrawingProperties();

            nvdp.Id          = new UInt32Value((uint)(1024 + imageNumber));
            nvdp.Name        = "Picture " + imageNumber.ToString();
            nvdp.Description = "";
            DocumentFormat.OpenXml.Drawing.PictureLocks picLocks = new DocumentFormat.OpenXml.Drawing.PictureLocks();
            picLocks.NoChangeAspect     = true;
            picLocks.NoChangeArrowheads = true;
            NonVisualPictureDrawingProperties nvpdp = new NonVisualPictureDrawingProperties();

            nvpdp.PictureLocks = picLocks;
            NonVisualPictureProperties nvpp = new NonVisualPictureProperties();

            nvpp.NonVisualDrawingProperties        = nvdp;
            nvpp.NonVisualPictureDrawingProperties = nvpdp;

            DocumentFormat.OpenXml.Drawing.Stretch stretch = new DocumentFormat.OpenXml.Drawing.Stretch();
            stretch.FillRectangle = new DocumentFormat.OpenXml.Drawing.FillRectangle();

            BlipFill blipFill = new BlipFill();

            DocumentFormat.OpenXml.Drawing.Blip blip = new DocumentFormat.OpenXml.Drawing.Blip();
            blip.Embed               = dp.GetIdOfPart(imgp);
            blip.CompressionState    = DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print;
            blipFill.Blip            = blip;
            blipFill.SourceRectangle = new DocumentFormat.OpenXml.Drawing.SourceRectangle();
            blipFill.Append(stretch);

            DocumentFormat.OpenXml.Drawing.Transform2D t2d    = new DocumentFormat.OpenXml.Drawing.Transform2D();
            DocumentFormat.OpenXml.Drawing.Offset      offset = new DocumentFormat.OpenXml.Drawing.Offset();
            offset.X   = 0;
            offset.Y   = 0;
            t2d.Offset = offset;
            Bitmap bm = new Bitmap(imagepath);

            DocumentFormat.OpenXml.Drawing.Extents extents = new DocumentFormat.OpenXml.Drawing.Extents();

            extents.Cx = (long)bm.Width * (long)((float)914400 / bm.HorizontalResolution);
            extents.Cy = (long)bm.Height * (long)((float)914400 / bm.VerticalResolution);

            bm.Dispose();
            t2d.Extents = extents;
            ShapeProperties sp = new ShapeProperties();

            sp.BlackWhiteMode = DocumentFormat.OpenXml.Drawing.BlackWhiteModeValues.Auto;
            sp.Transform2D    = t2d;
            DocumentFormat.OpenXml.Drawing.PresetGeometry prstGeom = new DocumentFormat.OpenXml.Drawing.PresetGeometry();
            prstGeom.Preset          = DocumentFormat.OpenXml.Drawing.ShapeTypeValues.Rectangle;
            prstGeom.AdjustValueList = new DocumentFormat.OpenXml.Drawing.AdjustValueList();
            sp.Append(prstGeom);
            sp.Append(new DocumentFormat.OpenXml.Drawing.NoFill());

            DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture picture = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Picture();
            picture.NonVisualPictureProperties = nvpp;
            picture.BlipFill        = blipFill;
            picture.ShapeProperties = sp;

            Position pos = new Position();

            pos.X = xpos;
            pos.Y = ypos;
            Extent ext = new Extent();

            ext.Cx = extents.Cx;
            ext.Cy = extents.Cy;
            AbsoluteAnchor anchor = new AbsoluteAnchor();

            anchor.Position = pos;
            anchor.Extent   = ext;
            anchor.Append(picture);
            anchor.Append(new ClientData());
            wsd.Append(anchor);
            wsd.Save(dp);
        }