WPF - RichTextBox в HTML используя C# и .NET


Полный код

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WPF___RichTextBox_to_HTML
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        public MainWindow()
        {
            InitializeComponent();

            // Insert RTF document into RichText Control.
            string inpFile = @"..\..\example.rtf";
            byte[] rtfBytes = File.ReadAllBytes(inpFile);

            using (MemoryStream ms = new MemoryStream(rtfBytes))
            {
                System.Windows.Documents.TextRange tr = new System.Windows.Documents.TextRange(
                   rtfControl.Document.ContentStart, rtfControl.Document.ContentEnd);
                tr.Load(ms, DataFormats.Rtf);
            }

        }
        private void BtnConvert_Click(object sender, RoutedEventArgs e)
        {
            // Get RTF from RichTextBox
            string rtfString = string.Empty;
            using (MemoryStream ms = new MemoryStream())
            {
                TextRange range = new TextRange(rtfControl.Document.ContentStart, rtfControl.Document.ContentEnd);
                range.Save(ms, DataFormats.Rtf);
                ms.Seek(0, SeekOrigin.Begin);
                using (StreamReader sr = new StreamReader(ms))
                {
                    rtfString = sr.ReadToEnd();
                }
            }
            // Convert RTF to HTML using SautinSoft.RtfToHtml.dll            
            string outFile = @"Result.html";

            SautinSoft.RtfToHtml r = new SautinSoft.RtfToHtml();

            // Specify some properties for output HTML document.
            r.OutputFormat = SautinSoft.RtfToHtml.eOutputFormat.HTML_5;
            r.Encoding = SautinSoft.RtfToHtml.eEncoding.UTF_8;

            // Imagefolder must already exist.
            r.ImageStyle.ImageFolder = System.Environment.CurrentDirectory;

            // Subfolder for images will be created by the component.
            r.ImageStyle.ImageSubFolder = "image.files";

            // A template name for images.
            r.ImageStyle.ImageFileName = "picture";

            // false - store images as files on HDD,
            // true - store images inside HTML document using base64.
            r.ImageStyle.IncludeImageInHtml = false;

            try
            {
                r.OpenRtf(rtfString);
                r.ToHtml(outFile);

                // Open the result for demonstration purposes.
                System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile)
                { UseShellExecute = true });
            }
            catch (Exception ex)
            {
                MessageBox.Show($"Error: {ex.Message}");
            }
        }
    }
}

Скачать

Imports System
Imports System.IO

Class MainWindow
    Private Sub BtnConvert_Click(sender As Object, e As RoutedEventArgs) Handles btnConvert.Click

        ' Get RTF from RichTextBox
        Dim rtfString As String = String.Empty
        Using ms As New MemoryStream()
            Dim range As New TextRange(rtfControl.Document.ContentStart, rtfControl.Document.ContentEnd)
            range.Save(ms, DataFormats.Rtf)
            ms.Seek(0, SeekOrigin.Begin)
            Using sr As New StreamReader(ms)
                rtfString = sr.ReadToEnd()
            End Using
        End Using
		
        ' Convert RTF to HTML using SautinSoft.RtfToHtml.dll            
        Dim outFile As String = "Result.html"

        Dim r As New SautinSoft.RtfToHtml()

        ' Specify some properties for output HTML document.
        r.OutputFormat = SautinSoft.RtfToHtml.eOutputFormat.HTML_5
        r.Encoding = SautinSoft.RtfToHtml.eEncoding.UTF_8

        ' Imagefolder must already exist.
        r.ImageStyle.ImageFolder = Environment.CurrentDirectory

        ' Subfolder for images will be created by the component.
        r.ImageStyle.ImageSubFolder = "image.files"

        ' A template name for images.
        r.ImageStyle.ImageFileName = "picture"

        ' false - store images as files on HDD,
        ' true - store images inside HTML document using base64.
        r.ImageStyle.IncludeImageInHtml = False

        Try
            r.OpenRtf(rtfString)
            r.ToHtml(outFile)

            ' Open the result for demonstration purposes.
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
        Catch ex As Exception
            MessageBox.Show($"Error: {ex.Message}")
        End Try
    End Sub

    Private Sub Window_Loaded(sender As Object, e As RoutedEventArgs)
	
        ' Insert RTF document into RichText Control.
        Dim inpFile As String = "..\..\example.rtf"
        Dim rtfBytes() As Byte = File.ReadAllBytes(inpFile)

        Using ms As New MemoryStream(rtfBytes)
            Dim tr As New System.Windows.Documents.TextRange(rtfControl.Document.ContentStart, rtfControl.Document.ContentEnd)
            tr.Load(ms, DataFormats.Rtf)
        End Using
    End Sub
End Class

Скачать

<Window x:Class="WPF___RichTextBox_to_HTML.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        xmlns:local="clr-namespace:WPF___RichTextBox_to_HTML"
        mc:Ignorable="d"
        Title="WPF - RichTextBox to HTML using SautinSoft.RtfToHtml.dll"
        WindowState="Maximized"
        WindowStyle="SingleBorderWindow">
    <Grid>
        <Grid.RowDefinitions>
            <RowDefinition Height="*"></RowDefinition>
            <RowDefinition Height="Auto"></RowDefinition>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="*"></ColumnDefinition>
        </Grid.ColumnDefinitions>
        <RichTextBox Name="rtfControl" Grid.Row="0" Margin="2,10"></RichTextBox>
        <Button Name="btnConvert" Grid.Row="1" Width="150" Height="28" Margin="5" Click="BtnConvert_Click">Convert to HTML</Button>
    </Grid>
</Window>

If you are looking also for a .NET solution to Create or Modify HTML documents, see our Document .Net.


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу support@sautinsoft.ru или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.