0

我们正在使用 Aspose.Words for .NET 在我们的应用程序中导出 Word 文档。现在我还必须在导出的文档中包含 RichText 内容(实际上是一个 FlowDocument)。为了导出,我们正在实现 IMailMergeDataSource 接口。此 IMailMergeDataSource 实现的 GetValue 函数由 Aspose 库调用,该函数如下所示:

public override bool GetValue(string fieldName, out object fieldValue) {  ...  }

所以我在Word模板中获取了当前字段的字段名,我要设置fieldValue为字符串,这样fieldValue中的字符串才能出现在Word文档中。

但是例如,当我将 fieldValue 设置为 FlowDocument 时,结果将是一个 XML 字符串(FlowDocument 对象的 ToString 表示)

4

1 回答 1

1

我建议您在 fieldValue 中传递富文本。将此富文本加载到 Aspose.Words Document 对象中,如下所示(在 FieldMerging 事件中):

string rtfStr = "{\\rtf1\\ansi\\ansicpg1252\\deff0\\deflang3079{\\fonttbl{\\f0\\fnil\\fcharset0 Microsoft Sans Serif;}}{\\colortbl ;\\red255\\green0\\blue0;\\red0\\green128\\blue0;\\red0\\green0\\blue255;}\\viewkind4\\uc1\\pard\\cf1\\f0\\fs17 Rot.\\cf0\\fs17  \\cf2\\fs17 Gr\\'fcn.\\cf0\\fs17  \\cf3\\fs17 Blau.\\cf0\\fs17  \\i\\fs17 Kursiv.\\i0\\fs17  \\strike\\fs17 Durchgestrichen. \\ul\\strike0 Unterstrichen.\\ulnone\\fs17  \\b\\fs17 Fett.\\b0\\fs17\\par}";

System.Text.ASCIIEncoding encoding = new System.Text.ASCIIEncoding();
byte[] dataBytes = encoding.GetBytes(rtfStr);
MemoryStream stream = new MemoryStream(dataBytes);

LoadOptions loadOptions = new LoadOptions();
loadOptions.LoadFormat = LoadFormat.Rtf;

Document doc = new Document(stream, loadOptions);

您需要实现 IFieldMergingCallback 接口,以便能够控制在邮件合并操作期间如何将数据插入到合并字段中。

private class HandleMergeFields : IFieldMergingCallback
{
    void IFieldMergingCallback.FieldMerging(FieldMergingArgs e)
    {
        DocumentBuilder builder = new DocumentBuilder(e.Document);

        builder.MoveToMergeField("fieldName");
        Node node = builder.CurrentNode;

        // doc is an RTF document we created from RTF string
        InsertDocument(node, doc); 

我希望这对您的情况有所帮助。如果它没有帮助,请让我知道。

于 2012-04-24T06:34:17.960 回答