Example #1
0
        protected void AnnotateOpenXmlElement(OpenXmlElement element)
        {
            if (luminanceModulation != 1.0)
            {
                element.AppendChild(new LuminanceModulation()
                {
                    Val = (int)(luminanceModulation * 100000)
                });
            }

            if (luminanceOffset != 0.0)
            {
                element.AppendChild(new LuminanceOffset()
                {
                    Val = (int)(luminanceOffset * 100000)
                });
            }

            if (tint != 0.0)
            {
                element.AppendChild(new Tint()
                {
                    Val = (int)(tint * 100000)
                });
            }

            if (alpha != 1.0)
            {
                element.AppendChild(new Alpha()
                {
                    Val = (int)(alpha * 100000)
                });
            }
        }
        public void Add(string item)
        {
            var point   = new TPoint();
            var wrapper = _pointFactoryFn(point);

            wrapper.Value = item;
            Items.Add(wrapper);
            CollectionRoot.AppendChild(point);
            _updateCount();
        }
 public static void AddTextToElement(OpenXmlElement element, string text)
 {
     var splitText = text.Split(new[] {"\r\n", "\n", "\r"}, StringSplitOptions.RemoveEmptyEntries);
     foreach (var line in splitText)
     {
         element.AppendChild(new Text(line));
         if (line != splitText.Last())
         {
             element.AppendChild(new Break());
         }
     }
 }
        private static Text InsertTextRun(OpenXmlElement parent, string text)
        {
            OpenXmlElement last = parent;

            if (last is Paragraph)
            {
                last = last.AppendChild(new Run());
            }
            if (last is Run)
            {
                return(last.AppendChild(new Text(text)));
            }
            return(InsertTextRun(last.AppendChild(new Paragraph()), text));
        }
Example #5
0
 public static void SetChildIfNotExists <T>(OpenXmlElement parent) where T : OpenXmlElement, new()
 {
     if (!HasChild <T>(parent))
     {
         parent.AppendChild(new T());
     }
 }
Example #6
0
        /// <summary>
        /// Render a hyperlink.
        /// </summary>
        /// <param name="hyperlink"></param>
        /// <param name="parent"></param>
        /// <param name="context"></param>
        /// <param name="documentPart"></param>
        /// <param name="formatProvider"></param>
        /// <returns></returns>
        public static OpenXmlElement Render(this Hyperlink hyperlink,
                                            OpenXmlElement parent,
                                            ContextModel context,
                                            OpenXmlPart documentPart,
                                            IFormatProvider formatProvider)
        {
            context.ReplaceItem(hyperlink, formatProvider);

            if (!hyperlink.Show)
            {
                return(null);
            }

            var fieldCodeXmlelement = new DocumentFormat.OpenXml.Wordprocessing.Hyperlink();

            if (!string.IsNullOrWhiteSpace(hyperlink.Anchor))
            {
                fieldCodeXmlelement.Anchor = hyperlink.Anchor;
            }
            else if (!string.IsNullOrWhiteSpace(hyperlink.WebSiteUri))
            {
                HyperlinkRelationship hyperlinkPart = documentPart.AddHyperlinkRelationship(new Uri(hyperlink.WebSiteUri), true);
                fieldCodeXmlelement.Id = hyperlinkPart.Id;
            }

            parent.AppendChild(fieldCodeXmlelement);

            hyperlink.Text.Render(fieldCodeXmlelement, context, documentPart, formatProvider);

            return(fieldCodeXmlelement);
        }
        private Paragraph CreateParagraph(DocxNode node, OpenXmlElement parent)
        {
            Paragraph para = parent.AppendChild(new Paragraph());

            OnParagraphCreated(node, para);
            return(para);
        }
Example #8
0
        private void SetMarginBottom(OpenXmlElement parent)
        {
            Paragraph para = parent.AppendChild(new Paragraph());
            para.ParagraphProperties = new ParagraphProperties();

            DocxMargin.SetBottomMargin(defaultDLMargin, para.ParagraphProperties);
        }
        public static void InsertText(String text, String styleXml, OpenXmlElement parentNode)
        {
            // Разделить строку на подстроки
            //String[] runs = macroVarValue.Split(new char[] { '\r', '\n' });
            //String[] runs = Regex.Split(macroVarValue, "\r\n|\r|\n");
            String[] runs = Regex.Split(text, "\r\n");

            // Вставить текст
            foreach (String run in runs)
            {
                // Создать новый Paragraph
                Paragraph newParagraph = parentNode.AppendChild(new Paragraph());

                // Вернуть старый стиль в Paragraph
                ParagraphProperties newParagraphProperties = newParagraph.AppendChild(new ParagraphProperties());
                newParagraphProperties.InnerXml = styleXml;

                // Создать новый Run
                Run newRun = newParagraph.AppendChild(new Run());

                // Вернуть старый стиль в Run
                RunProperties newRunProperties = newRun.AppendChild(new RunProperties());
                newRunProperties.InnerXml = styleXml;

                // Вставить в него текст
                newRun.AppendChild(new Text(run));
            }
        }
        private static void CreateTestResultSheet(SpreadsheetDocument document, OpenXmlElement sheets, CEAEDBEntities db, uint sheetID = 1)
        {
            var newWorksheetPart = document.WorkbookPart.AddNewPart <WorksheetPart>();

            var relationshipId = document.WorkbookPart.GetIdOfPart(newWorksheetPart);
            var sheet          = new Sheet
            {
                Id      = relationshipId,
                SheetId = sheetID,
                Name    = "Test Results Statistics"
            };

            sheets.AppendChild(sheet);

            var sheetData = new SheetData();


            newWorksheetPart.Worksheet = new Worksheet(sheetData);

            //create header rows

            var projectRow = CreateResultsHeaderRow(1);

            sheetData.AppendChild(projectRow);

            //creating content rows
            var colIndex = 2;

            var testresults = db.TestResults.ToList();

            foreach (var tst in testresults)
            {
                //creating row for this user
                var row = CreateTestResultRow(colIndex, tst);
                sheetData.AppendChild(row);

                colIndex++;
            }


            //set col width
            var columns = new Columns();

            columns.Append(new Column {
                Min = 1, Max = 250, Width = 20, CustomWidth = true
            });
            columns.Append(new Column {
                Min = 1, Max = 250, Width = 20, CustomWidth = true
            });
            columns.Append(new Column {
                Min = 1, Max = 175, Width = 20, CustomWidth = true
            });
            columns.Append(new Column {
                Min = 1, Max = 250, Width = 20, CustomWidth = true
            });

            newWorksheetPart.Worksheet.Append(columns);

            newWorksheetPart.Worksheet.Save();
        }
Example #11
0
 private Paragraph CreateParagraph(DocxNode node, OpenXmlElement parent)
 {
     Paragraph para = parent.AppendChild(new Paragraph());
     OnParagraphCreated(node, para);
     OnOLParagraphCreated(this, new ParagraphEventArgs(para));
     return para;
 }
Example #12
0
        private void ProcessBody(DocxNode node, ref Paragraph paragraph)
        {
            while (node != null)
            {
                if (node.IsText)
                {
                    string text;

                    if (!IsEmptyText(node, out text))
                    {
                        if (paragraph == null)
                        {
                            paragraph = body.AppendChild(new Paragraph());
                            OnParagraphCreated(node, paragraph);
                        }

                        Run run = paragraph.AppendChild(new Run(new Text()
                        {
                            Text  = ClearHtml(text),
                            Space = SpaceProcessingModeValues.Preserve
                        }));

                        RunCreated(node, run);
                    }
                }
                else
                {
                    node.ParagraphNode = node;
                    node.Parent        = body;
                    ProcessChild(node, ref paragraph);
                }

                node = node.Next;
            }
        }
        private void AppendImageToElement(KeyValuePair <string, ImageElement> placeholder, OpenXmlElement element, WordprocessingDocument wordprocessingDocument)
        {
            string imageExtension = placeholder.Value.MemStream.GetImageType();

            MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;

            var imageUri = new Uri($"/word/media/{placeholder.Key}{_imageCounter}.{imageExtension}", UriKind.Relative);

            // Create "image" part in /word/media
            // Change content type for other image types.
            PackagePart packageImagePart = wordprocessingDocument.Package.CreatePart(imageUri, "Image/" + imageExtension);

            // Feed data.
            placeholder.Value.MemStream.Position = 0;
            byte[] imageBytes = placeholder.Value.MemStream.ToArray();
            packageImagePart.GetStream().Write(imageBytes, 0, imageBytes.Length);

            PackagePart documentPackagePart = mainPart.OpenXmlPackage.Package.GetPart(new Uri("/word/document.xml", UriKind.Relative));

            // URI to the image is relative to relationship document.
            PackageRelationship imageRelationshipPart = documentPackagePart.CreateRelationship(
                new Uri("media/" + placeholder.Key + _imageCounter + "." + imageExtension, UriKind.Relative),
                TargetMode.Internal, "http://schemas.openxmlformats.org/officeDocument/2006/relationships/image");

            var imgTmp = placeholder.Value.MemStream.GetImage();

            var drawing = GetImageElement(imageRelationshipPart.Id, placeholder.Key, "picture", imgTmp.Width, imgTmp.Height, placeholder.Value.Dpi);

            element.AppendChild(drawing);
        }
        private void WriteReferralsToSheet(OpportunityReportDto dto, OpenXmlElement sheetData)
        {
            var rowIndex = 3;

            foreach (var referral in dto.ReferralItems)
            {
                var row = new Row {
                    RowIndex = (uint)rowIndex
                };

                row.AppendChild(SpreadsheetExtensions.CreateTextCell(1, rowIndex, referral.Workplace));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(2, rowIndex, referral.JobRole));

                row.AppendChild(int.TryParse(referral.PlacementsDetail, out var placements)
                    ? SpreadsheetExtensions.CreateTextCell(3, rowIndex, placements)
                    : SpreadsheetExtensions.CreateTextCell(3, rowIndex, referral.PlacementsDetail));

                row.AppendChild(SpreadsheetExtensions.CreateTextCell(4, rowIndex, referral.ProviderNameForReport));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(5, rowIndex, referral.ProviderVenueTownAndPostcode));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(6, rowIndex, $"{referral.DistanceFromEmployer:#0.0} miles"));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(7, rowIndex, referral.PrimaryContact));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(8, rowIndex, referral.PrimaryContactEmail));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(9, rowIndex, referral.PrimaryContactPhone));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(10, rowIndex, referral.SecondaryContact));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(11, rowIndex, referral.SecondaryContactEmail));
                row.AppendChild(SpreadsheetExtensions.CreateTextCell(12, rowIndex, referral.SecondaryContactPhone));

                sheetData.AppendChild(row);
                rowIndex++;
            }
        }
Example #15
0
 public OpenXmlElement GetOrCreateDataLabel()
 {
     return(this.series.GetFirstChild <DataLabels>() ?? series.AppendChild(
                new DataLabels()
                .AppendChildFluent(new ShowLegendKey()
     {
         Val = false
     })
                .AppendChildFluent(new ShowValue()
     {
         Val = false
     })
                .AppendChildFluent(new ShowCategoryName()
     {
         Val = false
     })
                .AppendChildFluent(new ShowSeriesName()
     {
         Val = false
     })
                .AppendChildFluent(new ShowPercent()
     {
         Val = false
     })
                .AppendChildFluent(new ShowBubbleSize()
     {
         Val = true
     })
                .AppendChildFluent(new ShowLeaderLines()
     {
         Val = true
     })
                ));
 }
Example #16
0
        public TSelf SetText(IRange range)
        {
            StringCache stringCache = new StringCache();

            if (range.Width == 1 && range.Height > 0)
            {
                stringCache.PointCount = new PointCount()
                {
                    Val = (uint)range.Height.Value
                };
                for (uint i = 0; i < range.Height; ++i)
                {
                    stringCache.AppendChild(new StringPoint()
                    {
                        Index = i, NumericValue = new NumericValue(range[0, i].InnerValue)
                    });
                }
            }
            else if (range.Height == 1 && range.Width > 0)
            {
                stringCache.PointCount = new PointCount()
                {
                    Val = (uint)range.Width.Value
                };
                for (uint i = 0; i < range.Width; ++i)
                {
                    stringCache.AppendChild(new StringPoint()
                    {
                        Index = i, NumericValue = new NumericValue(range[i, 0].InnerValue)
                    });
                }
            }
            else
            {
                throw new ArgumentException("Expected an one-dimensional range.");
            }

            SeriesText seriesText = series.GetFirstChild <SeriesText>() ?? series.AppendChild(new SeriesText());

            seriesText.StringReference = new StringReference()
            {
                Formula     = new Formula(range.Formula),
                StringCache = stringCache
            };

            return(this.Self);
        }
Example #17
0
        private void SetMarginBottom(OpenXmlElement parent)
        {
            Paragraph para = parent.AppendChild(new Paragraph());

            para.ParagraphProperties = new ParagraphProperties();

            DocxMargin.SetBottomMargin(defaultDLMargin, para.ParagraphProperties);
        }
Example #18
0
 public static void MoveChilds(this OpenXmlElement target, IEnumerable <OpenXmlElement> childs)
 {
     foreach (var c in childs.ToList())
     {
         c.Remove();
         target.AppendChild(c);
     }
 }
Example #19
0
        private void ProcessTemplateAndAppendToContainer(WordprocessingDocument wordprocessingDocument, OpenXmlElement container, OpenXmlElement template, Dictionary <string, string> data)
        {
            var templateClone = template.CloneNode(true);

            ReplaceMergeFields(wordprocessingDocument, templateClone, data);

            container.AppendChild(templateClone);
        }
        public TFluent SetShowValue(bool show)
        {
            OpenXmlElement dataLabel = this.element.GetOrCreateDataLabel();
            ShowValue      showValue = dataLabel.GetFirstChild <ShowValue>() ?? dataLabel.AppendChild(new ShowValue());

            showValue.Val = show;

            return(this.result);
        }
Example #21
0
        private static void AddImageToElement(OpenXmlElement element, EmuRectangle rect, string relationshipId)
        {
            rect = NormalizeToWidth(rect);

            // Define the reference of the image.
            var imgElement = GetImageElement(rect, relationshipId);

            element.AppendChild(new Run(imgElement));
        }
Example #22
0
        public TFluent SetShowPercent(bool show)
        {
            OpenXmlElement dataLabel   = this.element.GetOrCreateDataLabelAdjust();
            ShowPercent    showPercent = dataLabel.GetFirstChild <ShowPercent>() ?? dataLabel.AppendChild(new ShowPercent());

            showPercent.Val = show;

            return(this.result);
        }
Example #23
0
        private void WriteProvidersToSheet(ProviderProximityReportDto dto, OpenXmlElement sheetData)
        {
            var rows  = sheetData.Descendants <Row>().ToList();
            var cells = rows[0].Descendants <Cell>().ToList();

            var rowIndex = 3;

            if (dto.SkillAreas.Any())
            {
                var skillsHeaderBuilder = new StringBuilder();

                for (var i = 0; i < dto.SkillAreas.Count; i++)
                {
                    skillsHeaderBuilder.Append(dto.SkillAreas[i]);
                    if (i < dto.SkillAreas.Count - 1)
                    {
                        skillsHeaderBuilder.Append("; ");
                    }
                }

                cells[2].UpdateTextCell(skillsHeaderBuilder.ToString());

                rowIndex = 5;
                cells    = rows[1].Descendants <Cell>().ToList();
            }

            cells[2].UpdateTextCell($"Distance from {dto.Postcode}");

            foreach (var provider in dto.Providers)
            {
                foreach (var route in provider.Routes)
                {
                    foreach (var qualification in route.QualificationShortTitles)
                    {
                        var row = new Row {
                            RowIndex = (uint)rowIndex
                        };

                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(1, rowIndex, provider.ProviderName));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(2, rowIndex,
                                                                             $"{provider.ProviderVenueTown} {provider.ProviderVenuePostcode}"));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(3, rowIndex, $"{provider.Distance:#0.0} miles"));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(4, rowIndex, route.RouteName));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(5, rowIndex, qualification));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(6, rowIndex, provider.PrimaryContact));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(7, rowIndex, provider.PrimaryContactEmail));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(8, rowIndex, provider.PrimaryContactPhone));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(9, rowIndex, provider.SecondaryContact));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(10, rowIndex, provider.SecondaryContactEmail));
                        row.AppendChild(SpreadsheetExtensions.CreateTextCell(11, rowIndex, provider.SecondaryContactPhone));

                        sheetData.AppendChild(row);
                        rowIndex++;
                    }
                }
            }
        }
Example #24
0
        public TFluent SetExtents(long width, long height)
        {
            OpenXmlElement transform = this.element.GetOrCreateTransform();
            Extents        extents   = transform.GetFirstChild <Extents>() ?? transform.AppendChild(new Extents());

            extents.Cx = width;
            extents.Cy = height;

            return(this.element);
        }
Example #25
0
        public TFluent SetOffset(long x, long y)
        {
            OpenXmlElement transform = this.element.GetOrCreateTransform();
            Offset         offset    = transform.GetFirstChild <Offset>() ?? transform.AppendChild(new Offset());

            offset.X = x;
            offset.Y = y;

            return(this.element);
        }
Example #26
0
        public static void SetFill(OpenXmlElement shapeProperties, OpenXmlColor color)
        {
            shapeProperties.RemoveAllChildren <NoFill>();
            shapeProperties.RemoveAllChildren <SolidFill>();
            shapeProperties.RemoveAllChildren <GradientFill>();
            shapeProperties.RemoveAllChildren <BlipFill>();
            shapeProperties.RemoveAllChildren <PatternFill>();
            shapeProperties.RemoveAllChildren <GroupFill>();

            shapeProperties.AppendChild(new SolidFill().AppendChildFluent(color.CreateColorElement()));
        }
        /// <summary>
        /// Вставка элемента после первого из указанных, у которого значение не null.
        /// Хотя бы один элемент должен быть не null, иначе вставка не произойдет.
        /// </summary>
        /// <param name="refChilds">Элементы в порядке, после первого из которых требуется вставить новый элемент</param>
        /// <param name="force">Укажите true для вставки элемента даже если все элементы в списке null</param>
        /// <returns>true при удачной вставке, false в обратном случае</returns>
        public bool AfterOneOf(IEnumerable <OpenXmlElement> refChilds, bool force = false)
        {
            bool success;

            if (success = ToOneOf(refChilds, _After) || !force)
            {
                return(success);
            }
            ParentElem.AppendChild(newChild);
            return(true);
        }
Example #28
0
        public TFluent SetDelete(bool value)
        {
            OpenXmlElement dataLabelAdjust = this.element.GetOrCreateDataLabelAdjust();

            if (value)
            {
                Index index = dataLabelAdjust.GetFirstChild <Index>();
                dataLabelAdjust.RemoveAllChildren();
                dataLabelAdjust.AppendChild(index);
                dataLabelAdjust.AppendChild(new Delete()
                {
                    Val = true
                });
            }
            else
            {
                dataLabelAdjust.RemoveAllChildren <Delete>();
            }

            return(this.result);
        }
        /// <summary>
        /// Gets or creates the element's first child of type T.
        /// </summary>
        /// <typeparam name="T">A subclass of OpenXmlElement</typeparam>
        /// <param name="element">The element</param>
        /// <returns>The existing or newly created first child of this element</returns>
        public static T Produce <T>(this OpenXmlElement element) where T : OpenXmlElement, new()
        {
            var child = element.GetFirstChild <T>();

            if (child != null)
            {
                return(child);
            }

            child = new T();
            element.AppendChild(child);
            return(child);
        }
Example #30
0
        /// <summary>
        /// Create the image
        /// </summary>
        /// <param name="image">Image model</param>
        /// <param name="parent">Container</param>
        /// <param name="context">Context</param>
        /// <param name="documentPart">MainDocumentPart</param>
        /// <returns></returns>
        public static OpenXmlElement Render(this Models.Image image, OpenXmlElement parent, ContextModel context, OpenXmlPart documentPart)
        {
            context.ReplaceItem(image);
            ImagePart imagePart;

            if (documentPart is MainDocumentPart)
            {
                imagePart = (documentPart as MainDocumentPart).AddImagePart((ImagePartType)(int)image.ImagePartType);
            }
            else if (documentPart is HeaderPart)
            {
                imagePart = (documentPart as HeaderPart).AddImagePart((ImagePartType)(int)image.ImagePartType);
            }
            else if (documentPart is FooterPart)
            {
                imagePart = (documentPart as FooterPart).AddImagePart((ImagePartType)(int)image.ImagePartType);
            }
            else
            {
                return(null);
            }

            bool isNotEmpty = false;

            if (image.Content != null && image.Content.Length > 0)
            {
                using (MemoryStream stream = new MemoryStream(image.Content))
                {
                    imagePart.FeedData(stream);
                }
                isNotEmpty = true;
            }
            else if (!string.IsNullOrWhiteSpace(image.Path))
            {
                using (FileStream stream = new FileStream(image.Path, FileMode.Open))
                {
                    imagePart.FeedData(stream);
                }
                isNotEmpty = true;
            }
            if (isNotEmpty)
            {
                OpenXmlElement result = CreateImage(imagePart, image, documentPart);
                parent.AppendChild(result);
                return(result);
            }
            else
            {
                return(null);
            }
        }
        /// <summary>
        /// Render a table element
        /// </summary>
        /// <param name="table"></param>
        /// <param name="parent"></param>
        /// <param name="context"></param>
        /// <param name="documentPart"></param>
        /// <param name="formatProvider"></param>
        /// <returns></returns>
        public static Run Render(this BarModel barChart, OpenXmlElement parent, ContextModel context, OpenXmlPart documentPart, IFormatProvider formatProvider)
        {
            context.ReplaceItem(barChart, formatProvider);

            Run runItem = null;

            if (!string.IsNullOrWhiteSpace(barChart.DataSourceKey) && context.ExistItem <BarChartModel>(barChart.DataSourceKey))
            {
                // We construct categories and series from the context object
                var contextModel = context.GetItem <BarChartModel>(barChart.DataSourceKey);

                if (contextModel.BarChartContent != null && contextModel.BarChartContent.Categories != null &&
                    contextModel.BarChartContent.Series != null)
                {
                    // Update barChart object :
                    barChart.Categories = contextModel.BarChartContent.Categories.Select(e => new BarCategory()
                    {
                        Name  = e.Name,
                        Color = e.Color
                    }).ToList();

                    // We update
                    barChart.Series = contextModel.BarChartContent.Series.Select(e => new BarSerie()
                    {
                        LabelFormatString = e.LabelFormatString,
                        Color             = e.Color,
                        DataLabelColor    = e.DataLabelColor,
                        Values            = e.Values,
                        Name = e.Name
                    }).ToList();
                }
                else
                {
                    return(runItem);
                }
            }

            switch (barChart.BarChartType)
            {
            case BarChartType.BarChart:
                runItem = CreateBarGraph(barChart, documentPart);
                break;
            }

            if (runItem != null)
            {
                parent.AppendChild(runItem);
            }

            return(runItem);
        }
        public TFluent SetNoFill()
        {
            OpenXmlElement shapeProperties = this.element.GetOrCreateShapeProperties();

            shapeProperties.RemoveAllChildren <NoFill>();
            shapeProperties.RemoveAllChildren <SolidFill>();
            shapeProperties.RemoveAllChildren <GradientFill>();
            shapeProperties.RemoveAllChildren <BlipFill>();
            shapeProperties.RemoveAllChildren <PatternFill>();
            shapeProperties.RemoveAllChildren <GroupFill>();

            shapeProperties.AppendChild(new NoFill());

            return(this.result);
        }
Example #33
0
        private static void AddImageToBody(OpenXmlElement mainElement, string relationshipId, Image image)
        {
            long cx = (long)image.Width * (long)((float)914400 / image.HorizontalResolution);
            long cy = (long)image.Height * (long)((float)914400 / image.VerticalResolution);

            // Define the reference of the image.
            var element =
                 new Drawing(
                     new DW.Inline(
                         new DW.Extent() { Cx = cx, Cy = cy },
                         new DW.EffectExtent()
                         {
                             LeftEdge = 0L,
                             TopEdge = 0L,
                             RightEdge = 0L,
                             BottomEdge = 0L
                         },
                         new DW.DocProperties()
                         {
                             Id = (UInt32Value)1U,
                             Name = System.Guid.NewGuid().ToString()
                         },
                         new DW.NonVisualGraphicFrameDrawingProperties(
                             new A.GraphicFrameLocks() { NoChangeAspect = true }),
                         new A.Graphic(
                             new A.GraphicData(
                                 new PIC.Picture(
                                     new PIC.NonVisualPictureProperties(
                                         new PIC.NonVisualDrawingProperties()
                                         {
                                             Id = (UInt32Value)0U,
                                             Name = System.Guid.NewGuid().ToString() + ".png"
                                         },
                                         new PIC.NonVisualPictureDrawingProperties()),
                                     new PIC.BlipFill(
                                         new A.Blip(
                                             new A.BlipExtensionList(
                                                 new A.BlipExtension()
                                                 {
                                                     Uri =
                                                       "{" + System.Guid.NewGuid().ToString() + "}"
                                                 })
                                         )
                                         {
                                             Embed = relationshipId,
                                             CompressionState =
                                             A.BlipCompressionValues.Print
                                         },
                                         new A.Stretch(
                                             new A.FillRectangle())),
                                     new PIC.ShapeProperties(
                                         new A.Transform2D(
                                             new A.Offset() { X = 0L, Y = 0L },
                                             new A.Extents() { Cx = cx, Cy = cy }),
                                         new A.PresetGeometry(
                                             new A.AdjustValueList()
                                         ) { Preset = A.ShapeTypeValues.Rectangle }))
                             ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
                     ));

            // Append the reference to body, the element should be in a Run.
            mainElement.AppendChild(new Paragraph(new Run(element)));
        }