예제 #1
0
        private List <string> ExtractImages(Body content, MainDocumentPart wDoc, string imageFolderPath)
        {
            List <string> imageList = new List <string>();

            foreach (DocumentFormat.OpenXml.Wordprocessing.Paragraph par in content.Descendants <DocumentFormat.OpenXml.Wordprocessing.Paragraph>())
            {
                ParagraphProperties paragraphProperties = par.ParagraphProperties;
                for (int i = 0; i < par.Descendants <Run>().Count(); i++)
                {
                    Run     run   = par.Descendants <Run>().ElementAt(i);
                    Drawing image =
                        run.Descendants <Drawing>().FirstOrDefault();
                    if (image != null)
                    {
                        var       imageFirst    = image.Inline.Graphic.GraphicData.Descendants <DocumentFormat.OpenXml.Drawing.Pictures.Picture>().FirstOrDefault();
                        var       blip          = imageFirst.BlipFill.Blip.Embed.Value;
                        ImagePart img           = (ImagePart)wDoc.Document.MainDocumentPart.GetPartById(blip);
                        string    imageFileName = string.Empty;
                        string    imageFilePath = string.Empty;
                        using (Image toSaveImage = Bitmap.FromStream(img.GetStream()))
                        {
                            imageFileName = "Img_" + imageCount;
                            imageFilePath = imageFolderPath + "\\" + imageFileName + ".png";
                            try
                            {
                                toSaveImage.Save(imageFilePath, ImageFormat.Png);
                            }
                            catch (Exception ex)
                            {
                            }
                        }
                        imageList.Add(imageFilePath);
                        Run run2 = par.Descendants <Run>().ElementAt(i - 1);
                        run2.AppendChild(new Text(" Images/" + imageFileName + ".png"));
                        image.Remove();
                        imageCount++;
                    }
                }
            }
            return(imageList);
        }