Exemplo n.º 1
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.º 2
0
        /// <summary>
        /// Add the logo of the system
        /// </summary>
        /// <param name="logoPath">Path of the logo</param>
        /// <param name="worksheetPart">Worksheet Part</param>
        /// <returns>Drawing</returns>
        private static Drawing AddLogo(string logoPath, WorksheetPart worksheetPart)
        {
            string sImagePath = logoPath;
            DrawingsPart dp = worksheetPart.AddNewPart<DrawingsPart>();
            ImagePart imgp = dp.AddImagePart(ImagePartType.Png, worksheetPart.GetIdOfPart(dp));
            using (FileStream fs = new FileStream(sImagePath, FileMode.Open, FileAccess.Read))
            {
                imgp.FeedData(fs);
            }

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

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

            DocumentFormat.OpenXml.Drawing.Spreadsheet.BlipFill blipFill = new DocumentFormat.OpenXml.Drawing.Spreadsheet.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();
            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;
            DocumentFormat.OpenXml.Drawing.Spreadsheet.ShapeProperties sp = new DocumentFormat.OpenXml.Drawing.Spreadsheet.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;

            DocumentFormat.OpenXml.Drawing.Spreadsheet.Position pos = new DocumentFormat.OpenXml.Drawing.Spreadsheet.Position();
            pos.X = 18 * 914400  / 72;
            pos.Y = 28 * 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());
            WorksheetDrawing wsd = new WorksheetDrawing();
            wsd.Append(anchor);
            Drawing drawing = new Drawing();
            drawing.Id = dp.GetIdOfPart(imgp);

            wsd.Save(dp);
            return drawing;
        }
Exemplo n.º 3
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
                    }))));
                }
            }
        }
Exemplo n.º 4
0
            public static Wp.Drawing GetAnchorPicture(String imagePartId, uint width = 1500, uint height = 1500, uint horizontalOffset = 0, uint verticalOffset = 0, String pictureName = "Picture")
            {
                Wp.Drawing _drawing = new Wp.Drawing();
                DWp.Anchor _anchor  = new DWp.Anchor()
                {
                    DistanceFromTop    = (OXML.UInt32Value) 0U,
                    DistanceFromBottom = (OXML.UInt32Value) 0U,
                    DistanceFromLeft   = (OXML.UInt32Value) 0U,
                    DistanceFromRight  = (OXML.UInt32Value) 0U,
                    SimplePos          = false,
                    RelativeHeight     = (OXML.UInt32Value) 0U,
                    BehindDoc          = true,
                    Locked             = false,
                    LayoutInCell       = true,
                    AllowOverlap       = true,
                    EditId             = "44CEF5E4",
                    AnchorId           = "44803ED1"
                };
                DWp.SimplePosition _spos = new DWp.SimplePosition()
                {
                    X = 0L,
                    Y = 0L
                };

                DWp.HorizontalPosition _hp = new DWp.HorizontalPosition()
                {
                    RelativeFrom = DWp.HorizontalRelativePositionValues.Column
                };
                DWp.PositionOffset _hPO = new DWp.PositionOffset();
                _hPO.Text = horizontalOffset.ToString();
                _hp.Append(_hPO);

                DWp.VerticalPosition _vp = new DWp.VerticalPosition()
                {
                    RelativeFrom = DWp.VerticalRelativePositionValues.Paragraph
                };
                DWp.PositionOffset _vPO = new DWp.PositionOffset();
                _vPO.Text = verticalOffset.ToString();
                _vp.Append(_vPO);

                DWp.Extent _e = new DWp.Extent()
                {
                    Cx = height,
                    Cy = width
                };

                DWp.EffectExtent _ee = new DWp.EffectExtent()
                {
                    LeftEdge   = 0L,
                    TopEdge    = 0L,
                    RightEdge  = 0L,
                    BottomEdge = 0L
                };

                DWp.WrapTight _wp = new DWp.WrapTight()
                {
                    WrapText = DWp.WrapTextValues.BothSides
                };

                DWp.WrapPolygon _wpp = new DWp.WrapPolygon()
                {
                    Edited = false
                };
                DWp.StartPoint _sp = new DWp.StartPoint()
                {
                    X = 0L,
                    Y = 0L
                };

                DWp.LineTo _l1 = new DWp.LineTo()
                {
                    X = 0L, Y = 0L
                };
                DWp.LineTo _l2 = new DWp.LineTo()
                {
                    X = 0L, Y = 0L
                };
                DWp.LineTo _l3 = new DWp.LineTo()
                {
                    X = 0L, Y = 0L
                };
                DWp.LineTo _l4 = new DWp.LineTo()
                {
                    X = 0L, Y = 0L
                };

                _wpp.Append(_sp);
                _wpp.Append(_l1);
                _wpp.Append(_l2);
                _wpp.Append(_l3);
                _wpp.Append(_l4);

                _wp.Append(_wpp);

                DWp.DocProperties _dp = new DWp.DocProperties()
                {
                    Id   = 1U,
                    Name = pictureName
                };

                OXML.Drawing.Graphic     _g  = new OXML.Drawing.Graphic();
                OXML.Drawing.GraphicData _gd = new OXML.Drawing.GraphicData()
                {
                    Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture"
                };
                OXML.Drawing.Pictures.Picture _pic = new OXML.Drawing.Pictures.Picture();

                OXML.Drawing.Pictures.NonVisualPictureProperties _nvpp = new OXML.Drawing.Pictures.NonVisualPictureProperties();
                OXML.Drawing.Pictures.NonVisualDrawingProperties _nvdp = new OXML.Drawing.Pictures.NonVisualDrawingProperties()
                {
                    Id   = 0,
                    Name = pictureName
                };
                OXML.Drawing.Pictures.NonVisualPictureDrawingProperties _nvpdp = new OXML.Drawing.Pictures.NonVisualPictureDrawingProperties();
                _nvpp.Append(_nvdp);
                _nvpp.Append(_nvpdp);


                OXML.Drawing.Pictures.BlipFill _bf = new OXML.Drawing.Pictures.BlipFill();
                OXML.Drawing.Blip _b = new OXML.Drawing.Blip()
                {
                    Embed            = imagePartId,
                    CompressionState = OXML.Drawing.BlipCompressionValues.Print
                };
                _bf.Append(_b);

                OXML.Drawing.Stretch       _str = new OXML.Drawing.Stretch();
                OXML.Drawing.FillRectangle _fr  = new OXML.Drawing.FillRectangle();
                _str.Append(_fr);
                _bf.Append(_str);

                OXML.Drawing.Pictures.ShapeProperties _shp = new OXML.Drawing.Pictures.ShapeProperties();
                OXML.Drawing.Transform2D _t2d = new OXML.Drawing.Transform2D();
                OXML.Drawing.Offset      _os  = new OXML.Drawing.Offset()
                {
                    X = 0L,
                    Y = 0L
                };
                OXML.Drawing.Extents _ex = new OXML.Drawing.Extents()
                {
                    Cx = 989965L,
                    Cy = 791845L
                };

                _t2d.Append(_os);
                _t2d.Append(_ex);

                OXML.Drawing.PresetGeometry _preGeo = new OXML.Drawing.PresetGeometry()
                {
                    Preset = OXML.Drawing.ShapeTypeValues.Rectangle
                };
                OXML.Drawing.AdjustValueList _adl = new OXML.Drawing.AdjustValueList();
                _preGeo.Append(_adl);

                _shp.Append(_t2d);
                _shp.Append(_preGeo);

                _pic.Append(_nvpp);
                _pic.Append(_bf);
                _pic.Append(_shp);

                _gd.Append(_pic);
                _g.Append(_gd);

                _anchor.Append(_spos);
                _anchor.Append(_hp);
                _anchor.Append(_vp);
                _anchor.Append(_e);
                _anchor.Append(_ee);
                _anchor.Append(_wp);
                _anchor.Append(_dp);
                _anchor.Append(_g);

                _drawing.Append(_anchor);

                return(_drawing);
            }
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
 public NonPlaceholderTransform(OpenXmlCompositeElement xmlElement)
 {
     _offset  = xmlElement.Descendants <DocumentFormat.OpenXml.Drawing.Offset>().First(); //TODO: make lazy
     _extents = xmlElement.Descendants <DocumentFormat.OpenXml.Drawing.Extents>().First();
 }
Exemplo n.º 7
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.º 8
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);
        }