We are using the Aspose.Words for .NET to export Word documents in our application. Now I have to include RichText content (actually, a FlowDocument) in the exported document too. In order to export, we are implementing the IMailMergeDataSource interface. The GetValue function of this IMailMergeDataSource implementation is called by the Aspose library, and this function is looks like this:

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

So I get the field name of the current field in the Word template, and I have to set the fieldValue to a string, so that the string in the fieldValue can appear in the Word document.

But for example when I set the fieldValue to a FlowDocument, the result will be an XML string (the ToString representation of the FlowDocument object)

有帮助吗?

解决方案

I would suggest that you pass the rich text in the fieldValue. Load this rich text into Aspose.Words Document object as follows (within FieldMerging event):

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);

You need to Implement IFieldMergingCallback interface to be able to control how data is inserted into merge fields during a mail merge operation.

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); 

I hope this is going to help in your scenario. If it doesn't help, please do let me know.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top