첨부 실행 코드는 나눔고딕코딩 폰트를 사용합니다.
본 블로그는 광고를 포함하고 있습니다.
광고 클릭에서 발생하는 수익금은 모두 블로그 콘텐츠 향상을 위해 쓰여집니다.

728x90
반응형
728x170

TestProject.zip
0.01MB

▶ MainWindow.xaml

<Window x:Class="TestProject.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Width="800"
    Height="600"
    Title="FlowDocument 클래스 : RTF 파일을 XAML로 변환하기"
    FontFamily="나눔고딕코딩"
    FontSize="16">
    <Grid>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="10" />
            <ColumnDefinition Width="*"  />
            <ColumnDefinition Width="10" />
            <ColumnDefinition Width="*"  />
            <ColumnDefinition Width="10" />
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="10"   />
            <RowDefinition Height="*"    />
            <RowDefinition Height="10"   />
            <RowDefinition Height="Auto" />
            <RowDefinition Height="10"   />
        </Grid.RowDefinitions>
        <TextBox Name="textBox" Grid.Row="1" Grid.Column="1"
            HorizontalScrollBarVisibility="Auto"
            VerticalScrollBarVisibility="Auto"
            TextWrapping="Wrap"
            IsReadOnly="True" />
        <Border Grid.Row="1" Grid.Column="3"
            BorderThickness="1"
            BorderBrush="Gray">
            <FlowDocumentScrollViewer Name="flowDocumentScrollViewer"
                HorizontalScrollBarVisibility="Auto"
                VerticalScrollBarVisibility="Auto" />
        </Border>
        <Button Name="openFileButton" Grid.Row="3" Grid.Column="3"
            HorizontalAlignment="Right"
            VerticalAlignment="Bottom"
            Width="100"
            Height="30"
            Content="파일 열기" />
    </Grid>
</Window>

 

728x90

 

▶ MainWindow.xaml.cs

using Microsoft.Win32;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Xml;

namespace TestProject
{
    /// <summary>
    /// 메인 윈도우
    /// </summary>
    public partial class MainWindow : Window
    {
        //////////////////////////////////////////////////////////////////////////////////////////////////// Field
        ////////////////////////////////////////////////////////////////////////////////////////// Private

        #region Field

        /// <summary>
        /// 파일 열기 대화 상자
        /// </summary>
        private OpenFileDialog openFileDialog;

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Constructor
        ////////////////////////////////////////////////////////////////////////////////////////// Public

        #region 생성자 - MainWindow()

        /// <summary>
        /// 생성자
        /// </summary>
        public MainWindow()
        {
            InitializeComponent();

            this.openFileDialog = new OpenFileDialog();

            this.openFileDialog.Filter      = "RTF 파일 (*.rtf)|*.rtf";
            this.openFileDialog.FilterIndex = 1;
            this.openFileDialog.DefaultExt  = ".rtf";

            this.openFileButton.Click += openFileButton_Click;
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////////////////////////// Method
        ////////////////////////////////////////////////////////////////////////////////////////// Private
        //////////////////////////////////////////////////////////////////////////////// Event

        #region 파일 열기 버튼 클릭시 처리하기 - openFileButton_Click(sender, e)

        /// <summary>
        /// 파일 열기 버튼 클릭시 처리하기
        /// </summary>
        /// <param name="sender">이벤트 발생자</param>
        /// <param name="e">이벤트 인자</param>
        private void openFileButton_Click(object sender, RoutedEventArgs e)
        {
            bool result = this.openFileDialog.ShowDialog(this).GetValueOrDefault();

            if(result)
            {
                string rtf = File.ReadAllText(this.openFileDialog.FileName, Encoding.UTF8);

                string xaml = GetXAML(rtf);

                FlowDocument document = GetDocument(xaml);

                this.flowDocumentScrollViewer.Document = document;

                this.textBox.Text = xaml;
            }
        }

        #endregion

        //////////////////////////////////////////////////////////////////////////////// Function

        #region XAML 구하기 - GetXAML(rtf)

        /// <summary>
        /// XAML 구하기
        /// </summary>
        /// <param name="rtf">RTF</param>
        /// <returns>XAML</returns>
        private string GetXAML(string rtf)
        {
            FlowDocument document = new FlowDocument();

            TextRange range = new TextRange(document.ContentStart, document.ContentEnd);

            using(MemoryStream sourceStream = new MemoryStream(Encoding.UTF8.GetBytes(rtf)))
            {
                range.Load(sourceStream, DataFormats.Rtf);

                using(MemoryStream targetStream = new MemoryStream())
                {
                    range.Save(targetStream, DataFormats.Xaml);

                    targetStream.Position = 0;

                    using(StreamReader reader = new StreamReader(targetStream))
                    {
                        string xaml = reader.ReadToEnd();

                        return xaml;
                    }
                }
            }
        }

        #endregion
        #region 문서 구하기 - GetDocument(xaml)

        /// <summary>
        /// 문서 구하기
        /// </summary>
        /// <param name="xaml">XAML</param>
        /// <returns>문서</returns>
        private FlowDocument GetDocument(string xaml)
        {
            StringReader stringReader = new StringReader(xaml);

            XmlReader xmlReader = XmlReader.Create(stringReader);

            Section section = XamlReader.Load(xmlReader) as Section;

            FlowDocument document = new FlowDocument();

            while(section.Blocks.Count > 0)
            {
                Block block = section.Blocks.FirstBlock;

                section.Blocks.Remove(block);

                document.Blocks.Add(block);
            }

            return document;
        }

        #endregion
    }
}

※ 이미지가 포함된 RTF 파일 로드시 이미지는 누락된다.

728x90
반응형
그리드형(광고전용)
Posted by icodebroker

댓글을 달아 주세요