Esempio n. 1
0
        private static void InsertImage(OpenXmlPart part, string fieldName, Bitmap image, long imageWidth, long imageHeight)
        {
            var mergeFields = part.RootElement.Descendants <FieldCode>().Where(f => f.InnerText.Contains(fieldName));

            if (!mergeFields.Any())
            {
                return;
            }
            using (MemoryStream imageStream = new MemoryStream(image.ToByteArray()))
            {
                ImagePart imagePart;
                if (part is MainDocumentPart)
                {
                    imagePart = ((MainDocumentPart)part).AddImagePart(imageStream);
                }
                else if (part is HeaderPart)
                {
                    imagePart = ((HeaderPart)part).AddImagePart(imageStream);
                }
                else
                {
                    imagePart = ((FooterPart)part).AddImagePart(imageStream);
                }
                foreach (var field in mergeFields)
                {
                    Run rFldCode = (Run)field.Parent;
                    Run rBegin   = rFldCode.PreviousSibling <Run>();
                    Run rEnd     = rFldCode.NextSibling <Run>();
                    rFldCode.RemoveAllChildren();
                    rBegin.Remove();
                    rEnd.Remove();
                    Drawing imageElement = part.CreateElement(imagePart, "Image", imageWidth, imageHeight);
                    rFldCode.AppendChild(imageElement);
                }
            }
        }