Пример #1
0
        static Queue <NonnullRichTextBuilder> ReadAllLinesDocx(string path)
        {
            Queue <NonnullRichTextBuilder> richTexts = new Queue <NonnullRichTextBuilder>();
            WordprocessingDocument         doc       = null;

            try
            {
                doc = WordprocessingDocument.Open(path, false);
            }
            catch (OpenXmlPackageException)
            {
                return(richTexts);
            }
            catch (System.IO.IOException)
            {
                return(richTexts);
            }
            Body body = doc.MainDocumentPart.Document.Body;

            foreach (Paragraph paragraph in body.ChildElements.OfType <Paragraph>())
            {
                DocumentFormat.OpenXml.Drawing.Blip hasImage =
                    paragraph.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                if (hasImage == null)
                {
                    richTexts.Enqueue(new NonnullRichTextBuilder(paragraph.InnerText));
                }
                else
                {
                    List <object> runs = new List <object>();
                    foreach (Run docRun in paragraph.ChildElements.OfType <Run>())
                    {
                        DocumentFormat.OpenXml.Drawing.Blip imgContainer =
                            docRun.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                        if (imgContainer == null)
                        {
                            runs.Add(docRun.InnerText);
                        }
                        else
                        {
                            string           imgId      = imgContainer.Embed.Value;
                            ImagePart        imgPart    = doc.MainDocumentPart.GetPartById(imgId) as ImagePart;
                            System.IO.Stream imgStream  = imgPart.GetStream();
                            byte[]           imgInBytes = new byte[imgStream.Length];
                            imgStream.Read(imgInBytes, 0, (int)imgStream.Length);
                            runs.Add(imgInBytes);
                        }
                    }
                    NonnullRichTextBuilder richTextRuns = new NonnullRichTextBuilder(CompactRuns(runs));
                    richTexts.Enqueue(richTextRuns);
                }
            }
            doc.Close();
            return(richTexts);
        }
Пример #2
0
        /// <summary>
        /// Add picture
        /// </summary>
        /// <param name="picture"></param>
        /// <returns></returns>
        private string AddPicture(DocumentFormat.OpenXml.Drawing.Pictures.Picture picture)
        {
            foreach (OpenXmlElement element in picture.Elements())
            {
                if (element is DocumentFormat.OpenXml.Drawing.Pictures.BlipFill)
                {
                    DocumentFormat.OpenXml.Drawing.Blip blip = ((DocumentFormat.OpenXml.Drawing.Pictures.BlipFill)element).Blip;

                    if (blip != null)
                    {
                        OpenXmlPart image    = document.MainDocumentPart.GetPartById(blip.Embed.Value);
                        string      fileName = Path.Combine(imageDirectory, Path.GetFileName(image.Uri.ToString()));
                        fileName = Util.StreamToFile(image.GetStream(), fileName, FileMode.CreateNew, null);
                        return(fileName);
                    }
                }
            }

            return("");
        }
Пример #3
0
        /// <summary>
        /// Get the relationship id of image.
        /// </summary>
        /// <typeparam name="TSdtType">SdtElement type</typeparam>
        /// <param name="sdt">A sdtElement object that may contains image placeholder.</param>
        /// <param name="imageTag">Image placeholder tagID.</param>
        /// <returns>The relationship id of image.</returns>
        internal static string GetImageRelId <TSdtType>(TSdtType sdt, string imageTag) where TSdtType : SdtElement
        {
            // loop through all tags in the document within the sdt element
            foreach (Tag t in sdt.Descendants <Tag>().ToList())
            {
                // Do we have the correct tag?
                if (t.Val.ToString().ToUpper() == imageTag.ToUpper())
                {
                    // Get the BLIP for the image - there is only one image per placeholder so no need to loop through anything
                    DocumentFormat.OpenXml.Drawing.Blip b = sdt.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                    if (null != b)
                    {
                        // return the image id tag
                        return(b.Embed.Value);
                    }
                }
            }

            return(string.Empty);
        }
Пример #4
0
        static private int UpdateValueInSdtPic(string value, WordprocessingDocument wordDoc, string position)
        {
            int retValue = 0;
            var items    = wordDoc.MainDocumentPart.Document.Descendants <SdtElement>().Where(
                o =>
            {
                var tagedItem = o.SdtProperties.Elements <Tag>().FirstOrDefault();
                if (tagedItem != null)
                {
                    return(tagedItem.Val == position);
                }
                return(false);
            });

            foreach (var item in items)
            {
                string  embed = null;
                Drawing dr    = item.Descendants <Drawing>().FirstOrDefault();
                if (dr != null)
                {
                    DocumentFormat.OpenXml.Drawing.Blip blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                    if (blip != null)
                    {
                        embed = blip.Embed;
                    }
                }

                if (embed != null)
                {
                    IdPartPair idpp = wordDoc.MainDocumentPart.Parts.Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart    ip   = (ImagePart)idpp.OpenXmlPart;
                        byte[]       data = Convert.FromBase64String(value);
                        MemoryStream ms   = new MemoryStream(data);
                        ip.FeedData(ms);
                    }
                }
            }
            return(retValue);
        }
Пример #5
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);
        }
        public static WordprocessingDocument InsertImages(this WordprocessingDocument doc, ClientContext clientContext, string contentControlTag, string attachementServerRelativeUrl, TraceWriter log, List <string> messages)
        {
            try
            {
                SdtElement cc = doc.MainDocumentPart.Document.Body.Descendants <SdtElement>().FirstOrDefault(c =>
                {
                    SdtProperties p = c.Elements <SdtProperties>().FirstOrDefault();
                    if (p != null)
                    {
                        // Is it a picture content control?
                        SdtContentPicture pict = p.Elements <SdtContentPicture>().FirstOrDefault();
                        // Get the alias.
                        SdtAlias a = p.Elements <SdtAlias>().FirstOrDefault();

                        if (pict != null && a.Val == contentControlTag)
                        {
                            return(true);
                        }
                    }
                    return(false);
                });
                string embed = null;
                if (cc != null)
                {
                    Drawing dr = cc.Descendants <Drawing>().FirstOrDefault();
                    if (dr != null)
                    {
                        DocumentFormat.OpenXml.Drawing.Blip blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                        if (blip != null)
                        {
                            embed = blip.Embed;
                        }
                    }
                }
                if (embed != null)
                {
                    IdPartPair idpp = doc.MainDocumentPart.Parts
                                      .Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart ip             = (ImagePart)idpp.OpenXmlPart;
                        var       attachmentFile = clientContext.Site.RootWeb.GetFileByServerRelativeUrl(attachementServerRelativeUrl);
                        clientContext.Load(attachmentFile);
                        clientContext.ExecuteQueryRetry();
                        if (attachmentFile != null)
                        {
                            // Returns required result
                            ClientResult <Stream> attachmentStream = attachmentFile.OpenBinaryStream();
                            clientContext.ExecuteQueryRetry();
                            ip.FeedData(attachmentStream.Value);
                        }
                    }
                }
                return(doc);
            }
            catch (Exception ex)
            {
                string message = $"An error occurred replacing Image Content Control Tag \"{contentControlTag}\". Please ensure its an Image Content Control, and the value is the server relative url of an image file that you have access to";
                log.Info(message);
                messages.Add(message);
                return(doc);
            }
        }
Пример #7
0
        public static void SetContentOfContentControl(SdtElement contentControl, string content)
        {
            if (contentControl == null)
            {
                throw new ArgumentNullException("contentControl");
            }

            content = string.IsNullOrEmpty(content) ? string.Empty : content;
            var isCombobox = contentControl.SdtProperties.Descendants <SdtContentDropDownList>().FirstOrDefault() != null;
            var isImage    = contentControl.SdtProperties.Descendants <SdtContentPicture>().FirstOrDefault() != null;
            var prop       = contentControl.Elements <SdtProperties>().FirstOrDefault();

            if (isCombobox)
            {
                var openXmlCompositeElement = GetSdtContentOfContentControl(contentControl);
                var run = CreateRun(openXmlCompositeElement, content);
                SetSdtContentKeepingPermissionElements(openXmlCompositeElement, run);
            }

            if (isImage)
            {
                string  embed = null;
                Drawing dr    = contentControl.Descendants <Drawing>().FirstOrDefault();
                if (dr != null)
                {
                    DocumentFormat.OpenXml.Drawing.Blip blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                    if (blip != null)
                    {
                        embed = blip.Embed;
                    }
                }

                if (embed != null)
                {
                    var        document = (Document)prop.Ancestors <Body>().FirstOrDefault().Parent;
                    IdPartPair idpp     = document.MainDocumentPart.Parts.Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart     ip = (ImagePart)idpp.OpenXmlPart;
                        DirectoryInfo di = new DirectoryInfo(System.Reflection.Assembly.GetExecutingAssembly().Location);
                        using (FileStream fileStream = File.Open(Path.Combine(di.Parent.FullName, content), FileMode.Open))
                        {
                            ip.FeedData(fileStream);
                        }
                    }
                }
            }
            else
            {
                var openXmlCompositeElement = GetSdtContentOfContentControl(contentControl);
                contentControl.SdtProperties.RemoveAllChildren <ShowingPlaceholder>();
                var runs = new List <Run>();

                if (IsContentControlMultiline(contentControl))
                {
                    var textSplitted = content.Split(Environment.NewLine.ToCharArray()).ToList();
                    var addBreak     = false;

                    foreach (var textSplit in textSplitted)
                    {
                        var run = CreateRun(openXmlCompositeElement, textSplit);

                        if (addBreak)
                        {
                            run.AppendChild(new Break());
                        }

                        if (!addBreak)
                        {
                            addBreak = true;
                        }

                        runs.Add(run);
                    }
                }
                else
                {
                    runs.Add(CreateRun(openXmlCompositeElement, content));
                }

                SdtContentCell aopenXmlCompositeElement = openXmlCompositeElement as SdtContentCell;
                if (aopenXmlCompositeElement != null)
                {
                    AddRunsToSdtContentCell(aopenXmlCompositeElement, runs);
                }
                else if (openXmlCompositeElement is SdtContentBlock)
                {
                    var para = CreateParagraph(openXmlCompositeElement, runs);
                    SetSdtContentKeepingPermissionElements(openXmlCompositeElement, para);
                }
                else
                {
                    SetSdtContentKeepingPermissionElements(openXmlCompositeElement, runs);
                }
            }
        }
Пример #8
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;
        }
Пример #9
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);
            }
Пример #10
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
            }
        }
        public void ProcessWordDocument(string docFilePath)
        {
            tableIndex = 1;
            mathIndex  = 1;
            imageIndex = 1;
            videoIndex = 1;
            textIndex  = 1;
            using (WordprocessingDocument doc = WordprocessingDocument.Open(docFilePath, false))
            {
                foreach (var table in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Wordprocessing.Table>())
                {
                    int       trows     = table.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableRow>().Count();
                    int       tcols     = table.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableRow>().First().Descendants <DocumentFormat.OpenXml.Wordprocessing.TableCell>().Count();
                    WordTable wordTable = new WordTable(trows, tcols);
                    //create a table class and add the text from the rows and cells
                    int row = 0, cell = 0;
                    foreach (var tableRow in table.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableRow>())
                    {
                        foreach (var tableCell in tableRow.Descendants <DocumentFormat.OpenXml.Wordprocessing.TableCell>())
                        {
                            string text = tableCell.InnerText;
                            wordTable.AddText(row, cell, text);
                            cell++;
                            //save the cell into a table class for later processing with row info
                        }
                        cell = 0;
                        row++;
                    }
                    DocumentFormat.OpenXml.Wordprocessing.Paragraph para = new DocumentFormat.OpenXml.Wordprocessing.Paragraph();
                    Run    run           = para.AppendChild(new Run());
                    string IDplaceholder = "%Table-&" + tableIndex;
                    run.AppendChild(new Text(IDplaceholder));
                    table.Parent.ReplaceChild(para, table);
                    //table.Remove();
                    tableIndex++;
                    //store the table
                    TableList.Add(IDplaceholder, wordTable);
                }
                foreach (var formula in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Math.OfficeMath>())
                {
                    string wordDocXml = formula.OuterXml;
                    XslCompiledTransform xslTransform = new XslCompiledTransform();
                    xslTransform.Load(officeMathMLSchemaFilePath);
                    string mmlFormula = null;

                    using (TextReader tr = new StringReader(wordDocXml))
                    {
                        // Load the xml of your main document part.
                        using (XmlReader reader = XmlReader.Create(tr))
                        {
                            XmlWriterSettings settings = xslTransform.OutputSettings.Clone();

                            // Configure xml writer to omit xml declaration.
                            settings.ConformanceLevel   = ConformanceLevel.Fragment;
                            settings.OmitXmlDeclaration = true;

                            using (MemoryStream ms = new MemoryStream())
                            {
                                XmlWriter xw = XmlWriter.Create(ms, settings);

                                // Transform our OfficeMathML to MathML.
                                xslTransform.Transform(reader, xw);
                                ms.Seek(0, SeekOrigin.Begin);
                                using (StreamReader sr = new StreamReader(ms, Encoding.UTF8))
                                {
                                    mmlFormula = sr.ReadToEnd();
                                }
                            }
                        }
                        DocumentFormat.OpenXml.Wordprocessing.Paragraph para = formula.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                        Run    run           = para.AppendChild(new Run());
                        string IDplaceholder = "%Math-&" + mathIndex;
                        run.AppendChild(new Text(IDplaceholder));
                        mathIndex++;
                        formula.Remove();
                        if (mmlFormula != null)
                        {
                            MathList.Add(IDplaceholder, mmlFormula);
                        }
                    }
                }
                foreach (var graphic in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Drawing.Graphic>())
                {
                    DocumentFormat.OpenXml.Drawing.Blip blip = graphic.FirstChild.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().First();
                    string    imageId   = blip.Embed.Value;
                    ImagePart imagePart = (ImagePart)doc.MainDocumentPart.GetPartById(imageId);
                    var       uri       = imagePart.Uri;
                    var       filename  = uri.ToString().Split('/').Last();
                    var       stream    = doc.Package.GetPart(uri).GetStream();
                    Bitmap    b         = new Bitmap(stream);
                    string    imagePath = TempImageFolder + filename;
                    b.Save(imagePath);
                    DocumentFormat.OpenXml.Wordprocessing.Paragraph para = graphic.Parent.Parent.Parent.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                    Run    run           = para.AppendChild(new Run());
                    string IDplaceholder = "%Image-&" + imageIndex;
                    run.AppendChild(new Text(IDplaceholder));
                    imageIndex++;
                    ImageList.Add(IDplaceholder, imagePath);
                }
                try
                {
                    foreach (var video in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Drawing.VideoFromFile>())
                    {
                        //extract video bytes from word document
                        DocumentFormat.OpenXml.Drawing.Blip blip = video.FirstChild.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().First();
                        var    vid      = doc.MainDocumentPart.GetPartById(blip.Embed.Value);
                        var    uri      = vid.Uri;
                        var    filename = uri.ToString().Split('/').Last();
                        var    stream   = doc.Package.GetPart(uri).GetStream();
                        byte[] videoBytes;
                        using (BinaryReader br = new BinaryReader(stream))
                        {
                            videoBytes = br.ReadBytes((int)stream.Length);
                        }
                        //TODO set these up universally somewhere
                        string videoFolder     = @"C:\websites\RoboBraille.Web.Api\dist\";
                        string urlDistribution = @"http://2.109.50.18:5150/dist/" + filename;

                        //write bytes to shared web folder
                        File.WriteAllBytes(videoFolder + filename, videoBytes);
                        //send post video request to Amara

                        //put placeholder
                        //TODO check that video.Parent.Parent ...points to the right parent
                        DocumentFormat.OpenXml.Wordprocessing.Paragraph para = video.Parent.Parent.Parent.Parent.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                        Run    run           = para.AppendChild(new Run());
                        string IDplaceholder = "%Video-&" + videoIndex;
                        run.AppendChild(new Text(IDplaceholder));
                        videoIndex++;
                        //make somehow an list of videos sent to amara and their source location and store that info somewhere? maybe as jobs?
                    }
                } catch
                {
                }
                foreach (var element in doc.MainDocumentPart.Document.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>())
                {
                    try
                    {
                        var    psID = element.ParagraphProperties.ParagraphStyleId;
                        string type = null;
                        switch (psID.Val.ToString().ToLowerInvariant())
                        {
                        //for each case save the inner text of the paragraph and remove it
                        case "heading1": { type = "h1-"; break; }

                        case "heading2": { type = "h2-"; break; }

                        case "heading3": { type = "h3-"; break; }

                        case "heading4": { type = "h4-"; break; }

                        case "heading5": { type = "h5-"; break; }

                        case "title": { type = "title-"; break; }

                        case "subtitle": { type = "subtitle-"; break; }

                        default: break;
                        }
                        if (type != null)
                        {
                            string id = "%" + type + "&" + textIndex;
                            PlainTextList.Add(id, element.InnerText);
                            textIndex++;
                            element.RemoveAllChildren();
                            DocumentFormat.OpenXml.Wordprocessing.Paragraph para = element.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Paragraph());
                            Run run = para.AppendChild(new Run());
                            run.AppendChild(new Text(id));
                        }
                    }
                    catch
                    { //do nothing
                    }
                }

                PlaceholderIDList = ExtractTextAndCreatePlaceholderList(doc);
                if (textBuilder.Length > 0)
                {
                    string s2 = AddTextToTextList();
                    if (s2 != null)
                    {
                        PlaceholderIDList.Add(s2);
                    }
                }
            }
        }
Пример #12
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());
            }
        }
Пример #13
0
        private static void ReplaceParagraphParts(OpenXmlElement element, WordprocessingDocument wordDocument)
        {
            //int i = 1;

            // Getting all Paragraph in Xml File

            Drawing  draw     = element.Descendants <Drawing>().FirstOrDefault();
            FileInfo fileInfo = new FileInfo("C:\\Users\\Gaurav Koli\\Downloads\\battlefield_bad_company_2_table_room_parquet-740403.jpg");
            string   embed    = null;

            DocumentFormat.OpenXml.Drawing.Blip blip = null;

            foreach (var paragraph in element.Descendants <Paragraph>())
            {
                //Getting blip Id to get Image Part
                SdtAlias sa = paragraph.Descendants <SdtAlias>().SingleOrDefault();
                if (sa != null && sa.Val == "crmndc_signatureurl")
                {
                    sa.Val = "Change Picture";
                    Console.WriteLine("Done");
                    Drawing dr = paragraph.Descendants <Drawing>().FirstOrDefault();
                    //9525 is EMU per pixel
                    Int64 finalCx = (600 * 9525);
                    Int64 finalCy = (300 * 9525);

                    //resize the image
                    dr.Inline.Extent.Cx = finalCx;
                    dr.Inline.Extent.Cy = finalCy;

                    dr.Inline.Graphic.GraphicData.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>().ShapeProperties.Transform2D.Extents.Cx = finalCx;
                    dr.Inline.Graphic.GraphicData.GetFirstChild <DocumentFormat.OpenXml.Drawing.Pictures.Picture>().ShapeProperties.Transform2D.Extents.Cy = finalCy;

                    if (dr != null)
                    {
                        blip = dr.Descendants <DocumentFormat.OpenXml.Drawing.Blip>().FirstOrDefault();
                        if (blip != null)
                        {
                            embed = blip.Embed;
                        }
                    }
                }

                //Getting Image part and change the Image

                if (embed != null)
                {
                    IdPartPair idpp = wordDocument.MainDocumentPart.Parts.Where(pa => pa.RelationshipId == embed).FirstOrDefault();
                    if (idpp != null)
                    {
                        ImagePart ip = (ImagePart)idpp.OpenXmlPart;
                        try
                        {
                            using (FileStream fileStream = fileInfo.OpenRead())
                            {
                                ip.FeedData(fileStream);
                                // fileStream.Close();
                            }
                            if (blip != null)
                            {
                                blip.Embed.Value = wordDocument.MainDocumentPart.GetIdOfPart(ip);
                            }
                            Console.WriteLine("done " + wordDocument.MainDocumentPart.GetIdOfPart(ip));
                            // Console.ReadKey();
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine(ex.StackTrace);
                            Console.ReadKey();
                        }
                    }
                    embed = null;
                }

                //Changing the Templete Text
                var sdtContentText = paragraph.Descendants <Text>();

                if (sdtContentText != null)
                {
                    foreach (Text text in sdtContentText)
                    {
                        switch (text.Text)
                        {
                        case "<<crmndc_seller1_fullname>>":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "Lysaker, ":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "21.03.2016":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "<<title>>":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "<<crmndc_buyer1_fullname>>":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "crmndc_insurancecompany_name":
                            text.Text = "Common" + i;
                            i++;
                            break;

                        case "<<":
                            text.Text = "";
                            break;

                        case ">>":
                            text.Text = "";
                            break;

                        default:
                            break;
                        }
                    }
                }
            }
        }
Пример #14
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);
        }