2012-04-02 35 views
0

我們使用Aspose.Words for .NET在我們的應用程序中導出Word文檔。 現在我必須在導出的文檔中包含RichText內容(實際上是一個FlowDocument)。 爲了導出,我們正在實現IMailMergeDataSource接口。這IMailMergeDataSource實現的getValue函數是由閱讀Aspose庫調用,這個功能看起來是這樣的:如何使用Aspose.Words for .NET將RichText保存到Word中?

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

所以我得到的Word模板當前字段的字段名,我必須設置fieldValue轉換爲字符串,以便fieldValue中的字符串可以出現在Word文檔中。

但例如當我設置fieldValue方法到FlowDocument的,其結果將是一個XML字符串(FlowDocument的對象的ToString表示)

回答

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

我希望這會對您的情況有所幫助。如果它沒有幫助,請讓我知道。

+1

它的工作原理!謝謝!我只需要將FlowDocument字符串轉換爲一個RTF字符串: – asdfghjkl 2012-04-27 11:48:30

+0

var xamlString =「...」; var flowDocument = FlowDocumentService.GetFlowDocument(xamlString); string dataFormat = DataFormats.Rtf; var documentTextRange = new TextRange(flowDocument.ContentStart,flowDocument.ContentEnd); var stream = new MemoryStream(); documentTextRange.Save(stream,dataFormat); LoadOptions loadOptions = new LoadOptions(); loadOptions.LoadFormat = LoadFormat.Rtf; fieldValue = new Document(stream,loadOptions); – asdfghjkl 2012-04-27 11:49:43

相關問題