【问题标题】:How to save RichText to Word with Aspose.Words for .NET?如何使用 Aspose.Words for .NET 将 RichText 保存到 Word?
【发布时间】:2015-02-26 09:29:22
【问题描述】:

我们正在使用 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 表示)

【问题讨论】:

    标签: .net ms-word richtext aspose


    【解决方案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); 
    

    我希望这对您的方案有所帮助。如果没有帮助,请告诉我。

    【讨论】:

    • 有效!谢谢!我只需要将 FlowDocument 字符串转换为 RTF 字符串:
    • var xamlString = "..."; var flowDocument = FlowDocumentService.GetFlowDocument(xamlString);字符串数据格式 = 数据格式.Rtf; var documentTextRange = new TextRange(flowDocument.ContentStart, flowDocument.ContentEnd); var 流 = 新的 MemoryStream(); documentTextRange.Save(流,数据格式); LoadOptions loadOptions = new LoadOptions(); loadOptions.LoadFormat = LoadFormat.Rtf; fieldValue = new Document(stream, loadOptions);
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多