C#操作Word合并多文档中的图片

我们在项目中可能会有这样的需求,类似文档合并,即把不同文档的某些内容合并到同一个文档,

我们只需要拿到所有需要合并的文档集合,转换为文档流,代码如下:

string url = ((Microsoft.AspNetCore.Http.Internal.DefaultHttpRequest)Request).Scheme + "://" + Request.Host.Value;
 string templateFilePathName = string.IsNullOrWhiteSpace(mySettings.GdAppTemplatePath) ? url + "/DesignReplyMergeFillTemplate.doc" : mySettings.GdAppTemplatePath;
            Console.WriteLine("模板地址" + templateFilePathName);
 List<Stream> strs = new List<Stream>();

 string loadFilePath = mySettings.DownLoadApiUrl + "/" + fileId;
                                BinaryFormatter serializer = new BinaryFormatter();
                                using (System.IO.MemoryStream memStream = new System.IO.MemoryStream())
                                {
                                    WebClient webClient = new WebClient();
                                    var buffer = webClient.DownloadData(loadFilePath);
                                    serializer.Serialize(memStream, buffer);
                                    memStream.Close();
                                    strs.Add(new MemoryStream(buffer));
                                }

   //图片路径集合
            List<string> Filelist = new List<string>();
            string savePath = AppDomain.CurrentDomain.BaseDirectory + "Images";
 foreach (var str in strs)
            {
                Document doc = new Document(str);
                NodeCollection shapes = doc.GetChildNodes(NodeType.Shape, true);
         
                int imageIndex = 0;

                if (!Directory.Exists(savePath))//如果不存在就创建file文件夹
                {
                    Directory.CreateDirectory(savePath);
                }
                else
                {
                    Directory.Delete(savePath, true);//删除文件夹以及文件夹中的子目录,文件   
                    Directory.CreateDirectory(savePath);
                }
                foreach (Shape shape in shapes)
                {
                    if (shape.HasImage)
                    {
                        string time = DateTime.Now.ToString("HHmmssfff");
                        //扩展名
                        string ex = FileFormatUtil.ImageTypeToExtension(shape.ImageData.ImageType);
                        string fileName = string.Format("{0}_{1}{2}", time, imageIndex, ex);
                        string saveFileName = savePath + "\\" + fileName;
                        shape.ImageData.Save(saveFileName);
                        //添加文件到集合
                        Filelist.Add(saveFileName);
                        imageIndex++;
                    }
                }
            }

   MemoryStream mStream = new MemoryStream();
            string docGuid = Guid.NewGuid().ToString();
            BinaryFormatter serializer = new BinaryFormatter();
            using (System.IO.MemoryStream memStream = new System.IO.MemoryStream())
            {
                WebClient webClient = new WebClient();
                var buffer = webClient.DownloadData(templateFilePathName);
                serializer.Serialize(memStream, buffer);
                memStream.Close();
                var strObj = new MemoryStream(buffer);
                Document groupDoc = new Document(strObj);

                groupDoc.MailMerge.Execute(rDic.Keys.ToArray(), rDic.Values.ToArray());
                if (printChartNameCodeDs != null && printChartNameCodeDs.Tables.Count > 0)
                {
                    groupDoc.MailMerge.ExecuteWithRegions(printChartNameCodeDs);
                }
                if (Filelist.Count > 0)
                {
                    //书签名称
                    string bookMark = "FilePicture";
                    foreach (var item in Filelist)
                    {
                        //处理插入图片
                        DocumentBuilder builder = new DocumentBuilder(groupDoc);   //builder里面有个write方法
                        builder.MoveToBookmark(bookMark);   //找到你图片插入的位子,定位到这里
                        FileStream fs = new FileStream(item, FileMode.Open);
                        byte[] imgByte = new byte[fs.Length];
                        fs.Read(imgByte, 0, imgByte.Length);
                        builder.InsertImage(imgByte, 200, 200);  //以字节组的方式写入word
                        fs.Close();
                        builder = null;
                        //文件是否存在
                        if (System.IO.File.Exists(item))
                        {
                            //删除文件
                            System.IO.File.Delete(item);
                        }
                    }
                }
                groupDoc.Save(mStream, Aspose.Words.Saving.SaveOptions.CreateSaveOptions(docGuid + ".doc"));
            }
            return File(mStream.ToArray(), "application/msword", docGuid + ".doc");

最终将图片存储在指定位置取到之后加载到另外一个文档即可;

posted @ 2021-02-23 17:09  ProgrammerWorld  阅读(277)  评论(0编辑  收藏  举报