首页 > 解决方案 > 将图像添加到 word 模板的占位符

问题描述

大家好,我有使用 Open XML SDK 在 Microsoft Word 文档中查找 MERGEFIELD 并用提供的数据替换它们的代码,这运行良好,但我现在想用图像替换提供的字符串

来自链接的代码:

https://www.codeproject.com/Articles/38575/Fill-Mergefields-in-docx-Documents-without-Microso

    using (WordprocessingDocument docx = WordprocessingDocument.Open(stream, true))
                    {
                        //  2010/08/01: addition
                        ConvertFieldCodes(docx.MainDocumentPart.Document);

                        // first: process all tables
                        foreach (var field in docx.MainDocumentPart.Document.Descendants<SimpleField>())
                        {
                            string fieldname = GetFieldName(field, out switches);
                           // I will get fieldname "ImgLogo" and then I want to add an Image at this position. 
                        }
                    }

我会得到如上所示的字段名“ImgLogo”,然后我想在这个位置添加一个图像。完整的代码显示在上面的链接中。

在这里帮助我提前致谢。

标签: c#imagems-wordoffice-interop

解决方案


您可以使用 mergefield if 语句。写出你的语句,在你完成后将图像粘贴到 if 语句的 else 段中。

https://wordmvp.com/FAQs/MailMerge/MMergeIfFields.htm

按 Alt + F9 在 word/excel 中显示合并域代码。如果应该编辑模板文档而不是最终产品。因为您在合并后看不到这些字段。

当您合并图片时,它会覆盖两个 { MERGEFIELD MergeImage } 字段。当它覆盖它们时, { MERGEFIELD MergeImage } = "" 将不正确,并将显示您的图像而不是占位符。如前所述,占位符图像应粘贴到 =“在此处粘贴占位符”。

这就像在合并图像之前一样,{ MERGEFIELD MergeImage } 等于一个空白字符串。

例如

{ IF { MERGEFIELD MergeImage } = "" "Paste Placeholder here" "{ MERGEFIELD MergeImage }" }

分解以上内容:

{ IF CONDITION "TRUE" "FALSE" }

如果没有合并任何内容,您将获得占位符,否则您将获得合并后的图像。


推荐阅读