//word doc add image, and convert image to text public static void DocxAddImage(WordprocessingDocument docx, ref string text, List <WordImageDto> images) { if (images == null || images.Count == 0) { return; } var mainPart = docx.MainDocumentPart; foreach (var image in images) { //var imagePath = images[i]; //var width = Convert.ToDouble(images[i + 1]); //var height = Convert.ToDouble(images[i + 2]); //var tag = images[i + 3]; var imageService = new WordImageService(image.FilePath, image.Width, image.Height); var newText = ""; if (imageService.DataStream != null) { //TODO: how multiple images ?? var imagePart = mainPart.AddImagePart(ImagePartType.Jpeg); imagePart.FeedData(imageService.DataStream); var imagePartId = mainPart.GetIdOfPart(imagePart); newText = GetImageRun(imagePartId, imageService).InnerXml; } text.Replace(image.Tag, newText); } }
//for add word image //http://blog.darkthread.net/post-2017-11-06-insert-image-to-docx.aspx //https://msdn.microsoft.com/zh-tw/library/office/bb497430.aspx public static Run GetImageRun(string imagePartId, WordImageService imageService) { // Define the reference of the image. var element = new Drawing( new DW.Inline( //Size of image, unit = EMU(English Metric Unit) //1 cm = 360000 EMUs new DW.Extent() { Cx = imageService.WidthInEMU, Cy = imageService.HeightInEMU }, new DW.EffectExtent() { LeftEdge = 0L, TopEdge = 0L, RightEdge = 0L, BottomEdge = 0L }, new DW.DocProperties() { Id = (UInt32Value)1U, Name = imageService.ImageName, }, 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 = imageService.FileName, }, new PIC.NonVisualPictureDrawingProperties()), new PIC.BlipFill( new A.Blip( new A.BlipExtensionList( new A.BlipExtension() { Uri = "{28A0092B-C50C-407E-A947-70E740481C1C}" }) ) { Embed = imagePartId, 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 = imageService.WidthInEMU, Cy = imageService.HeightInEMU }), new A.PresetGeometry( new A.AdjustValueList() ) { Preset = A.ShapeTypeValues.Rectangle })) ) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" }) ) { DistanceFromTop = (UInt32Value)0U, DistanceFromBottom = (UInt32Value)0U, DistanceFromLeft = (UInt32Value)0U, DistanceFromRight = (UInt32Value)0U, //EditId = "50D07946", //remark line, cause word 2007 cannot open !! }); return(new Run(element)); }