0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

FlowDocumentをRTFに変換する

Last updated at Posted at 2021-10-20

FlowDocumentをRTFに変換する

以下の記事に関連する記事です。

上記の記事では、WPFのRichTextBoxFlowDocumentを作って表示するなんてことをしたのですが、保存機能も欲しいですよね。
追加のコーディングを節約しつつファイルを保存できる機能を実装してしまいましょう。

最初にやった方法(System.Windows.Forms.RichTextBox)

実は、最初にやったのは、System.Windows.Forms.RichTextBoxを使った方法です。そう、WPFのはずなのに、なぜかWindowsFormsのRichTextBoxです。
WPFのRichTextBoxとの間のデータ転送はClipboardを使います。
全選択→コピー→ペースト
って感じです。(ここでは、本題ではないのでソースは記述しません)
System.Windows.Forms.RichTextBoxSystem.Windows.Forms.RichTextBox.SaveFileというメソッドを持っており、RTFとして保存できます。

https://docs.microsoft.com/ja-jp/dotnet/api/system.windows.forms.richtextbox.savefile?view=windowsdesktop-5.0#System_Windows_Forms_RichTextBox_SaveFile_System_String_

クソダサいというのが最大の欠点です。

もっといい解決方法(System.Windows.Document.TextRange)

System.Windows.Document.TextRangeというクラスがあります。これのコンストラクタは、System.Windows.Documents.TextPointerを二つとります。
二つのTextPointer間のテキストを取得して、クラスにするって感じですかね。
一方で、System.Windows.Documents.FlowDocumentは、ContentStart, ContentEndの二つのプロパティがあり、それぞれ、FlowDocumentインスタンスの先頭と末尾のTextPointerを返します。つまり

var theFlowDocumentTextRange = new System.Windows.Documents.TextPointer(theFlowDocument.ContentStart, theFlowDocument.ContentEnd);

で、FlowDocumentのオブジェクトのリッチテキストをSystem.Windows.Documents.TextPointerクラスのインスタンスとして取得できるわけです。
そして、System.Windows.Documents.TextRangeクラスには、Save()というメソッドがあります。なお、Save()メソッドの引数はSystem.IO.StreamStringです。

var theStream = File.OpenWrite(theFileName);
theFlowDocumentTextRange.Save(theStream, System.Windows.DataFormats.Rtf);
theStream.Close();

という形でRTFファイルに保存することができます。
なお、System.Windows.Documents.TextPointer.Save()メソッドの第2パラメータには、System.Windows.DataFormats.Rtfの他に、System.Windows.DataFormats.TextSystem.Windows.DataFormats.XamlSystem.Windows.DataFormats.XamlPackageの3種類が指定できます。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?