简体   繁体   English

如何将FlowDocument转换为rtf

[英]How to convert FlowDocument to rtf

I have used a WPF RichTextBox to save a flowdocument from it as byte[] in database. 我使用WPF RichTextBox将数据流中的flowdocument保存为byte []。 Now i need to retrieve this data and display in a report RichTextBox as an rtf. 现在我需要检索此数据并在RichTextBox报告中显示为rtf。 when i try to convert the byte[] using TextRange or in XAMLReader i get a FlowDocument back but how do i convert it to rtf string as the report RichTextBox only takes rtf. 当我尝试使用TextRange或在XAMLReader中转换byte []时,我得到一个FlowDocument,但我如何将其转换为rtf字符串,因为报告RichTextBox只需要rtf。

Thanks 谢谢

Arvind 阿文德

You should not persist the FlowDocument directly as it should be considered the runtime representation of the document, not the actual document content. 您不应该直接持久化FlowDocument,因为它应该被视为文档的运行时表示,而不是实际的文档内容。 Instead, use the TextRange class to Save and Load to various formats including Rtf . 而是使用TextRange类来保存和加载各种格式,包括Rtf

A quick sample on how to create a selection and save to a stream: 有关如何创建选择并保存到流的快速示例:

var content = new TextRange(doc.ContentStart, doc.ContentEnd);

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

To load content into a selection would be similar: 将内容加载到选择中将类似:

var content = new TextRange(doc.ContentStart, doc.ContentEnd);

if (content.CanLoad(DataFormats.Rtf))
{
    content.Load(stream, DataFormats.Rtf);
}

This works like a charm for me. 这对我来说就像一个魅力。 Displays the result in an RTF box without difficulties. 在没有困难的情况下在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

You will need to use your connection string & SQL select statement ... other than that, this is it ... 你需要使用你的连接字符串和SQL select语句...除此之外,这就是它......

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM