如何将FlowDocument转换为rtf

我使用WPF RichTextBox将数据流中的flowdocument保存为byte []。 现在我需要检索此数据并在RichTextBox报告中显示为rtf。 当我尝试使用TextRange或在XAMLReader中转换byte []时,我得到一个FlowDocument,但我如何将其转换为rtf字符串,因为报告RichTextBox只需要rtf。

谢谢

阿文德

您不应该直接持久化FlowDocument,因为它应该被视为文档的运行时表示,而不是实际的文档内容。 相反,使用TextRange类来保存和加载各种格式,包括Rtf 。

有关如何创建选择并保存到流的快速示例:

var content = new TextRange(doc.ContentStart, doc.ContentEnd); if (content.CanSave(DataFormats.Rtf)) { using (var stream = new MemoryStream()) { content.Save(stream, DataFormats.Rtf); } } 

将内容加载到选择中将类似:

 var content = new TextRange(doc.ContentStart, doc.ContentEnd); if (content.CanLoad(DataFormats.Rtf)) { content.Load(stream, DataFormats.Rtf); } 

这对我来说就像一个魅力。 在没有困难的情况下在RTF框中显示结果。

 public static string getDocumentAsXaml(IDocumentPaginatorSource flowDocument) { return XamlWriter.Save(flowDocument); } 
  Using conn As New System.Data.SqlClient.SqlConnection(connectionSTRING) Dim adapter As New System.Data.SqlClient.SqlDataAdapter(selectSTRING, conn) Dim DS As System.Data.DataSet = New System.Data.DataSet adapter.Fill(DS) Dim ba() As Byte = Text.Encoding.ASCII.GetBytes(DS.Tables(0).Rows(0)("RTF_Field").ToString()) Dim ms As MemoryStream = New MemoryStream(ba) Dim fd As FlowDocument = New FlowDocument Dim tr As TextRange = New TextRange(fd.ContentStart, fd.ContentEnd) tr.Load(ms, System.Windows.DataFormats.Rtf) ms.Close() RichTextBox.Document = fd End Using 

你需要使用你的连接字符串和SQL select语句……除此之外,这就是它……