C# Core Interop Attach/Add 图片文件转换成生成的Word文档

C# Core Interop Attach/Add picture file into a generated Word document

我正在使用 Interop 生成 Word 文档,它工作得很好。

我有一个模板文件,在该模板中我有一个标签#name#,我的代码向其传递了一个值。我只是想知道如何调整我的代码以便它也可以添加图片?

假设图像文件位置是 Path.Combine(_hostingEnvironment.WebRootPath, "template\image" + ".jpg") (我还想将该图像调整到特定尺寸)

public FileResult Download()
    {

        var stream = new MemoryStream();

        string TemplateLoc = "template\Template.docx";
        string path = Path.Combine(_hostingEnvironment.WebRootPath, TemplateLoc);

        string sourceFile = Path.Combine(path);
        string destinationFile = Path.Combine(_hostingEnvironment.WebRootPath, "template\Test" + ".docx");

            try
            {
                System.IO.File.Copy(sourceFile, destinationFile);

                Dictionary<string, string> keyValues = new Dictionary<string, string>();

                keyValues.Add("#name#", "Sarah");

                Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
                word.Visible = false;
                word.ScreenUpdating = false;

                Microsoft.Office.Interop.Word.Document doc = word.Documents.Open(destinationFile);
                Microsoft.Office.Interop.Word.Range range = word.ActiveDocument.Content;

                doc.Activate();

                object missing = Type.Missing;
                object sourceDoc = sourceFile;
                object destinationDoc = destinationFile;
                object matchCase = false;
                object matchWholeWord = true;
                object findWrap = Microsoft.Office.Interop.Word.WdFindWrap.wdFindContinue;
                object findFormat = true;
                object replaceAll = Microsoft.Office.Interop.Word.WdReplace.wdReplaceAll;
                object fileFormat2 = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatDocument;
                //

                //Replace text ##
                foreach (KeyValuePair<string, string> kvp in keyValues)
                {
                    object findText = kvp.Key;
                    object replaceText = kvp.Value;

                    if (range.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref missing,
                        ref missing, ref missing, ref missing, ref findWrap, ref missing,
                        ref replaceText, ref replaceAll, ref missing, ref missing, ref missing, ref missing))
                    {
                        //Console.WriteLine("Found " + findText + ", replaced with " + replaceText);
                        continue;
                    }
                }


                doc.SaveAs(destinationFile);
                doc.Close();
                word.Quit();


            }
            catch (Exception e)
            {
                throw e;
            }


        byte[] fileBytes = System.IO.File.ReadAllBytes(Path.Combine(_hostingEnvironment.WebRootPath, "template\Test" + ".docx"));
        string fileName = "test.docx";
        return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
    }

Word 有两种插入图形的方式:作为形状或作为 InlineShapes。 InlineShapes 与文本一起放置 in-line;形状具有文本环绕格式。下面的代码显示了 InlineShapes 的语法。 Shapes 的语法非常相似,如果您键入 doc.Shapes.AddPicture,您应该获得 Intellisense。如果我有选择,我会使用 InlineShape,因为它在页面上的位置更多 predictable/stable.

无论您使用哪个,重要的是指定 Range 参数以便正确定位图形。

            foreach (KeyValuePair<string, string> kvp in keyValues)
            {
                object findText = kvp.Key;
                object replaceText = kvp.Value;

                if (range.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref missing,
                    ref missing, ref missing, ref missing, ref findWrap, ref missing,
                    ref replaceText, ref replaceAll, ref missing, ref missing, ref missing, ref missing))
                {
                    //Console.WriteLine("Found " + findText + ", replaced with " + replaceText);
                   object oRange = range;
                   object oTrue = true;
                   Microsoft.Office.Interop.Word.InlineShape ils = doc.InlineShapes.AddPicture(Path.Combine(_hostingEnvironment.WebRootPath, "template\image" + ".jpg"), 
                       ref missing, ref oTrue, ref oRange);
                   ils.Height = 100;
                   ils.Width = 100;

                    //Replace text ##
                    continue;
                }
            }