[英]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.