[英]Aspose.Words - MailMerge images
我正在尝试遍历Dataset
,使用 Aspose.Words Mail-Merge 功能为每个项目创建一个页面。 下面的代码循环遍历Dataset
- 并将一些值传递给邮件合并执行函数。
var blankDocument = new Document();
var pageDocument = new Document(sFilename);
...
foreach (DataRow row in ds.Tables[0].Rows){
var sBarCode = row["BarCode"].ToString();
var imageFilePath = HttpContext.Current.Server.MapPath("\\_temp\\") + sBarCode + ".png";
var tempDoc = (Document)pageDocument.Clone(true);
var fieldNames = new string[] { "Test", "Barcode" };
var fieldData = new object[] { imageFilePath, imageFilePath };
tempDoc.MailMerge.Execute(fieldNames, fieldData);
blankDocument.AppendDocument(tempDoc, ImportFormatMode.KeepSourceFormatting);
}
var stream = new MemoryStream();
blankDocument.Save(stream, SaveFormat.Docx);
// I then output this stream using headers,
// to cause the browser to download the document.
邮件合并项{ MERGEFIELD Test }
从Dataset
{ MERGEFIELD Test }
获取正确的Dataset
。 但是,实际图像使用以下方法在所有页面上显示第 1 页的图像:
{ INCLUDEPICTURE "{MERGEFIELD Barcode }" \* MERGEFORMAT \d }
假设这是我的“条形码”字段数据:
c:\img1.png
c:\img2.png
c:\img3.png
本文档的第一页在“测试”字段的文本中显示c:\\img1.png
。 显示的图像是img1.png
。
但是,第 2 页将c:\\img2.png
显示为文本,但将img1.png
显示为实际图像。
有没有人对此有任何见解?
编辑:这似乎更像是一个 Word 问题。 当我在 Word 中的Alt + F9模式之间切换时,图像实际上显示c:\\img1.png
作为源。 所以这就是它显示在每个页面上的原因。
我已将其简化为:
{ INCLUDEPICTURE "{MERGEFIELD Barcode }" \d }
此外,在 Word 的邮件收件人列表中添加了此字段的测试数据。 当我预览时,它不会拉入数据,而是更改图像。 所以,这是根本问题。
我知道这是个老问题。 但我还是想回答一下。
使用 Aspose.Words 在执行邮件合并时插入图像非常容易。 要实现这一点,您应该简单地使用具有特殊名称的合并字段,例如 Image:MyImageFieldName。 https://docs.aspose.com/words/net/insert-checkboxes-html-or-images-during-mail-merge/#how-to-insert-images-from-a-database
此外,不需要遍历数据集中的行并为每一行执行邮件合并。 只需将整个数据传递给 MailMerge.Execute 方法,Aspose.Words 就会为数据中的每条记录复制模板。 这是此类模板的简单示例
使用以下代码执行邮件合并后:
// Create dummy data.
DataTable dt = new DataTable();
dt.Columns.Add("FirstName");
dt.Columns.Add("LastName");
dt.Columns.Add("MyImage");
dt.Rows.Add("John", "Smith", @"C:\Temp\1.png");
dt.Rows.Add("Jane", "Smith", @"C:\Temp\2.png");
// Open template, execute mail merge and save the result.
Document doc = new Document(@"C:\Temp\in.docx");
doc.MailMerge.Execute(dt);
doc.Save(@"C:\Temp\out.docx");
披露:我在 Aspose.Words 团队工作。
如果这是 Word 输出,(不确定 Aspose),这里可能有两个问题。
INCLUDEPICTURE
期望将反斜杠加倍,例如"c\\\\img2.png"
,或(不太可靠)在该平台上使用正斜杠或 Mac ":"
分隔符。 不过,如果数据像您在这里所做的那样通过字段结果输入,则可能没问题。
INCLUDEPICTURE
结果并未“按设计”自动更新,因为大约 10 年前 Microsoft 出于安全原因修改了一系列字段行为。 如果要合并到输出文档,则可以使用以下嵌套字段来解决该问题:
{ INCLUDEPICTURE { IF TRUE "{ MERGEFIELD Barcode }" } }
或删除结果文档中的字段,
{ IF { INCLUDEPICTURE { IF TRUE "{ MERGEFIELD Barcode }" } } { INCLUDEPICTURE { IF TRUE "{ MERGEFIELD Barcode }" } } }
所有{ }
需要以通常的方式使用Ctrl + F9插入。
(不要问我在哪里记录了“TRUE”的这种用法 - 据我所知,它不是。)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.