[英]System.InvalidOperationException when creating Word file with Gembox
我们正在使用 Gembox 文档合并包含合并字段的 Word 模板文档。 我们注意到当某些字段值包含特殊字符\t或\n时,会发生异常...
发生错误 - 文本不能包含换行符 (' ')、回车符 (' ') 或制表符 (' ')。 如果要中断文本或插入制表符,请将具有特定 SpecialCharacterType 的 SpecialCharacter 实例插入父级的 InlineCollection。
我们发现这篇文章描述了该问题的解决方案,但我们没有看到如何将其应用到我们的场景中。
这是我们抛出异常的代码......
public static void Merge(DocumentModel word, PricingSummaryModel model)
{
word.MailMerge.FieldMerging += (sender, e) =>
{
if (e.FieldName.Contains("CustomField."))
{
var trove = FindCustomFieldValueTrove(e.FieldName, model);
var value = ProcessCustomField(e.FieldName, e.Field.GetInstructionText(), trove);
e.Inline = new Run(e.Document, value) { CharacterFormat = e.Field.CharacterFormat.Clone() };
e.Cancel = false;
}
};
word.MailMerge.Execute(model);
}
我们可以通过先删除任何特殊字符来解决问题...
但是我们当然失去了特殊字符。 对于我们的场景,如何做到这一点? 我们并不是在“构建”上述帖子中引用的文档。 相反,我们从 Word 模板开始,本质上是邮件合并字段的字段值。
您需要处理这些特殊字符并将适当的元素添加到e.Inlines
集合中。
例如,试试这个:
var value = ProcessCustomField(e.FieldName, e.Field.GetInstructionText(), trove);
int startIndex = 0, currentIndex = 0, length = value.Length;
for (; currentIndex < length; currentIndex++)
{
char c = value[currentIndex];
if (c == '\t' || c == '\n')
{
e.Inlines.Add(
new Run(e.Document, value.Substring(startIndex, currentIndex - startIndex))
{ CharacterFormat = e.Field.CharacterFormat.Clone() });
e.Inlines.Add(
new SpecialCharacter(e.Document, c == '\t' ? SpecialCharacterType.Tab : SpecialCharacterType.LineBreak)
{ CharacterFormat = e.Field.CharacterFormat.Clone() });
startIndex = currentIndex + 1;
}
else if (currentIndex == length - 1)
e.Inlines.Add(
new Run(e.Document, value.Substring(startIndex, currentIndex - startIndex + 1))
{ CharacterFormat = e.Field.CharacterFormat.Clone() });
}
e.Cancel = false;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.