HTML Import Example for WPF

Nevron NOV RichTextEditor for WPF ships with hundreds of examples with full source code, as part of the Nevron Open Vision Suite. All WPF RichTextEditor examples are also available as a stand-alone Visual Studio solution in C# and VB.NET, which you can download from the links below.

HTML Import Example for WPF Description

This example demonstrates the HTML import capabilities of the Nevron Rich Text widget. Simply select one of the preloaded examples from the combo box to the right and see it imported. You can also edit the source of the HTML code and press the Import button when ready.


Html Import Example

C# HTML Import Example Code for Nevron RichTextEditor for WPF
Language: C#

using Nevron.Nov;
using Nevron.Nov.Dom;
using Nevron.Nov.Graphics;
using Nevron.Nov.IO;
using Nevron.Nov.Layout;
using Nevron.Nov.Text;
using Nevron.Nov.Text.Formats;
using Nevron.Nov.UI;
using Nevron.Nov.Windows.Forms;
using System;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;

namespace NovWinFormsProject
{
	public partial class Form1 : Form
	{
		#region Constructors

		public Form1()
		{
			InitializeComponent();

			// Set form title
			Text = "NOV WinForms - NHtmlImportExample";

			// Create the NOV example and its controls
			NWidget exampleContent = CreateExampleContent();
			NWidget exampleControls = CreateExampleControls();
			if (exampleControls != null)
			{
				exampleControls.PreferredWidth = 300;
			}

			// Place the example and its controls in a pair box
			NPairBox pairBox = new NPairBox(exampleContent, exampleControls);
			pairBox.FillMode = ENStackFillMode.First;
			pairBox.FitMode = ENStackFitMode.First;
			pairBox.Margins = new NMargins(NDesign.HorizontalSpacing, NDesign.VerticalSpacing);

			// Host the example in the form
			NNovWidgetHost host = new NNovWidgetHost(pairBox);
			host.Dock = DockStyle.Fill;
			Controls.Add(host);
		}

		#endregion

		#region Example

		public NWidget CreateExampleContent()
		{
			NSplitter splitter = new NSplitter();
			splitter.SplitMode = ENSplitterSplitMode.Proportional;
			splitter.SplitFactor = 0.5;

			// Create the "HTML Code" group box
			m_HtmlTextBox = new NTextBox();
			m_HtmlTextBox.AcceptsEnter = true;
			m_HtmlTextBox.AcceptsTab = true;
			m_HtmlTextBox.Multiline = true;
			m_HtmlTextBox.WordWrap = false;
			m_HtmlTextBox.VScrollMode = ENScrollMode.WhenNeeded;
			m_HtmlTextBox.HScrollMode = ENScrollMode.WhenNeeded;

			NButton importButton = new NButton("Import");
			importButton.Content.HorizontalPlacement = ENHorizontalPlacement.Center;
			importButton.Click += OnImportButtonClick;

			NPairBox pairBox = CreatePairBox(m_HtmlTextBox, importButton);
			splitter.Pane1.Content = new NGroupBox("HTML Code", pairBox);

			// Create the "Preview" group box
			m_PreviewRichText = new NRichTextView();
			m_PreviewRichText.ReadOnly = true;
            m_PreviewRichText.DocumentLoaded += OnRichTextDocumentLoaded;
			splitter.Pane2.Content = new NGroupBox("Preview", m_PreviewRichText);

			return splitter;
		}
		public NWidget CreateExampleControls()
		{
			NStackPanel stack = new NStackPanel();
			stack.VerticalSpacing = 10;

			m_ElapsedTimeLabel = new NLabel();
			stack.Add(CreatePredefinedPageGroupBox());
			stack.Add(CreateNavigationGroupBox());
			stack.Add(m_ElapsedTimeLabel);

			return stack;
		}
		public string GetExampleDescription()
		{
			return @"

This example demonstrates the HTML import capabilities of the Nevron Rich Text widget. Simply select one of the preloaded examples from the combo box to the right and see it imported. You can also edit the source of the HTML code and press the Import button when ready.

"; } /// /// Gets the relevant documentation links for the example /// /// public (string Name, string Url)[] GetDocumentationUrls() { return new[] { ("Rich Text - Loading Documents", "https://www.nevron.com/docs/openvision/rich-text-loading-documents.html"), ("Rich Text Editor Formats", "https://www.nevron.com/docs/openvision/rich-text-editor-formats.html"), }; } #endregion #region Implementation private NGroupBox CreatePredefinedPageGroupBox() { NListBox testListBox = new NListBox(); NEmbeddedResource[] embeddedResources = new NEmbeddedResource[] { Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_AttributeSelectors_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Backgrounds_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Borders_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_CursorsAndTooltips_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_EmbeddedImages_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Lists_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_MediaAndImportance_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_PseudoClasses_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_StyleSheets_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Tables_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_TextStyles_html }; for (int i = 0, count = embeddedResources.Length; i < count; i++) { NEmbeddedResource embeddedResource = embeddedResources[i]; NListBoxItem item = new NListBoxItem(NStringHelpers.InsertSpacesBeforeUppersAndDigits(embeddedResource.Name)); item.Tag = embeddedResource; testListBox.Items.Add(item); } testListBox.Selection.Selected += OnListBoxItemSelected; testListBox.Selection.SingleSelect(testListBox.Items[0]); return new NGroupBox("Predefined HTML pages", testListBox); } private NGroupBox CreateNavigationGroupBox() { // Create the navigation pair box m_NavigationTextBox = new NTextBox(); m_NavigationTextBox.Text = DefaultAddress; m_NavigationTextBox.VerticalPlacement = ENVerticalPlacement.Center; NButton goButton = new NButton("Go"); goButton.VerticalPlacement = ENVerticalPlacement.Center; goButton.Click += OnGoButtonClick; NPairBox pairBox = new NPairBox(m_NavigationTextBox, goButton); pairBox.FitMode = ENStackFitMode.First; pairBox.FillMode = ENStackFillMode.First; pairBox.Spacing = 3; return new NGroupBox("Import from URL", pairBox); } private bool TryParseUrl(string url, out Uri uri) { uri = null; url = NStringHelpers.SafeTrim(url); if (String.IsNullOrEmpty(url)) return false; if (!url.Contains("://") && // URI scheme check url.IndexOf(@":\") != 1 && // Windows file path check url[0] != '/') // Unix file path check { // This URL doesn't have a scheme and is not a file path, so add an HTTP URI scheme url = "http://" + url; } return Uri.TryCreate(url, UriKind.Absolute, out uri); } private void LoadSource(Stream stream) { byte[] bytes = NStreamHelpers.ReadToEnd(stream); m_HtmlTextBox.Text = NEncoding.UTF8.GetString(bytes); } private NPromise LoadHtml(Stream stream, string baseUri) { m_ElapsedTimeLabel.Text = String.Empty; stream.Position = 0; m_Stopwatch = Stopwatch.StartNew(); NTextLoadSettings settings = null; if (baseUri != null) { settings = new NTextLoadSettings(); settings.BaseUri = new Uri(baseUri); } return m_PreviewRichText.LoadFromStreamAsync(stream, NTextFormat.Html, settings); } #endregion #region Event Handlers private void OnImportButtonClick(NEventArgs arg1) { byte[] bytes = NEncoding.UTF8.GetBytes(m_HtmlTextBox.Text); using (MemoryStream stream = new MemoryStream(bytes)) { LoadHtml(stream, null); } } private void OnListBoxItemSelected(NItemEventArgs arg1) { if (arg1.TargetNode == null) return; // Determine the full name of the selected resource NEmbeddedResource embeddedResource = (NEmbeddedResource)arg1.Item.Tag; // Read the stream and set it as text of the HTML code text box Stream stream = embeddedResource.Stream; LoadSource(stream); LoadHtml(stream, null).Finally( delegate() { stream.Close(); } ); } private void OnGoButtonClick(NEventArgs arg1) { string url = m_NavigationTextBox.Text; if (String.IsNullOrEmpty(url)) return; // Normalize the URL Uri uri; if (!TryParseUrl(url, out uri)) { NMessageBox.ShowError("Invalid URL or file path", "Error"); return; } if (uri.IsFile) { // Load from file NFile file = NFileSystem.Current.GetFile(url); file.OpenReadAsync().Then(delegate (Stream stream) { using (stream) { LoadSource(stream); LoadHtml(stream, url); } }); } else if (NUriHelpers.IsHttp(uri)) { // Load from URI try { m_Stopwatch = Stopwatch.StartNew(); m_PreviewRichText.LoadFromUriAsync(uri); } catch (Exception ex) { m_Stopwatch.Stop(); NMessageBox.ShowError(ex.Message, "Error"); } } } private void OnRichTextDocumentLoaded(NEventArgs args) { // Show the elapsed time if (m_Stopwatch != null) { m_Stopwatch.Stop(); m_ElapsedTimeLabel.Text = "Elapsed time: " + m_Stopwatch.ElapsedMilliseconds + " ms"; } } #endregion #region Fields private NTextBox m_HtmlTextBox; private NRichTextView m_PreviewRichText; private NTextBox m_NavigationTextBox; private NLabel m_ElapsedTimeLabel; private Stopwatch m_Stopwatch; #endregion #region Static Methods private static NPairBox CreatePairBox(NWidget widget1, NWidget widget2) { NPairBox pairBox = new NPairBox(widget1, widget2, ENPairBoxRelation.Box1AboveBox2); pairBox.FitMode = ENStackFitMode.First; pairBox.FillMode = ENStackFillMode.First; pairBox.Spacing = NDesign.VerticalSpacing; return pairBox; } #endregion #region Constants private const string DefaultAddress = @"https://helpopenvision.nevron.com/Welcome.html"; #endregion #region Nested Types #endregion } }

Download a fully functional C# (.cs) HTML Import Example for WPF Solution

VB.NET HTML Import Example Code for Nevron RichTextEditor for WPF
Language: VB.NET

Imports Nevron.Nov
Imports Nevron.Nov.Dom
Imports Nevron.Nov.Graphics
Imports Nevron.Nov.IO
Imports Nevron.Nov.Layout
Imports Nevron.Nov.Text
Imports Nevron.Nov.Text.Formats
Imports Nevron.Nov.UI
Imports Nevron.Nov.Windows.Wpf
Imports System
Imports System.Diagnostics
Imports System.IO
Imports System.Runtime.InteropServices

Class MainWindow

#Region "Constructors"

	Public Sub New()
		' This call is required by the designer.
		InitializeComponent()

		' Add any initialization after the InitializeComponent() call.

		' Set form title
		Title = "NOV WPF - NHtmlImportExample"

		' Create the NOV example and its controls
		Dim exampleContent As NWidget = CreateExampleContent()
		Dim exampleControls As NWidget = CreateExampleControls()
		If Not exampleControls Is Nothing Then
			exampleControls.PreferredWidth = 300
		End If

		' Place the example and its controls in a pair box
		Dim pairBox As NPairBox = New NPairBox(exampleContent, exampleControls)
		pairBox.FillMode = ENStackFillMode.First
		pairBox.FitMode = ENStackFitMode.First
		pairBox.Margins = New NMargins(NDesign.HorizontalSpacing, NDesign.VerticalSpacing)

		' Host the example in the form
		Dim host As NNovWidgetHost(Of NWidget) = New NNovWidgetHost(Of NWidget)(pairBox)
		Content = host
	End Sub


#End Region

#Region "Example"

        Public Function CreateExampleContent() As NWidget
            Dim splitter As NSplitter = New NSplitter()
            splitter.SplitMode = ENSplitterSplitMode.Proportional
            splitter.SplitFactor = 0.5

            ' Create the "HTML Code" group box
            m_HtmlTextBox = New NTextBox()
            m_HtmlTextBox.AcceptsEnter = True
            m_HtmlTextBox.AcceptsTab = True
            m_HtmlTextBox.Multiline = True
            m_HtmlTextBox.WordWrap = False
            m_HtmlTextBox.VScrollMode = ENScrollMode.WhenNeeded
            m_HtmlTextBox.HScrollMode = ENScrollMode.WhenNeeded

            Dim importButton As NButton = New NButton("Import")
            importButton.Content.HorizontalPlacement = ENHorizontalPlacement.Center
            importButton.Click += AddressOf OnImportButtonClick

            Dim pairBox = CreatePairBox(m_HtmlTextBox, importButton)
            splitter.Pane1.Content = New NGroupBox("HTML Code", pairBox)

            ' Create the "Preview" group box
            m_PreviewRichText = New NRichTextView()
            m_PreviewRichText.ReadOnly = True
            Me.m_PreviewRichText.DocumentLoaded += AddressOf OnRichTextDocumentLoaded
            splitter.Pane2.Content = New NGroupBox("Preview", m_PreviewRichText)

            Return splitter
        End Function
        Public Function CreateExampleControls() As NWidget
            Dim stack As NStackPanel = New NStackPanel()
            stack.VerticalSpacing = 10

            m_ElapsedTimeLabel = New NLabel()
            stack.Add(CreatePredefinedPageGroupBox())
            stack.Add(CreateNavigationGroupBox())
            stack.Add(m_ElapsedTimeLabel)

            Return stack
        End Function
        Public Function GetExampleDescription() As String
            Return "

This example demonstrates the HTML import capabilities of the Nevron Rich Text widget. Simply select one of the preloaded examples from the combo box to the right and see it imported. You can also edit the source of the HTML code and press the Import button when ready.

" End Function ''' ''' Gets the relevant documentation links for the example ''' ''' Public Function GetDocumentationUrls() As (String, String)() Return {("Rich Text - Loading Documents", "https://www.nevron.com/docs/openvision/rich-text-loading-documents.html"), ("Rich Text Editor Formats", "https://www.nevron.com/docs/openvision/rich-text-editor-formats.html")} End Function #End Region #Region "Implementation" Private Function CreatePredefinedPageGroupBox() As NGroupBox Dim testListBox As NListBox = New NListBox() Dim embeddedResources = New NEmbeddedResource() {NResources.RSTR_HtmlSuite_AttributeSelectors_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Backgrounds_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Borders_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_CursorsAndTooltips_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_EmbeddedImages_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Lists_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_MediaAndImportance_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_PseudoClasses_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_StyleSheets_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_Tables_html, Nevron.Nov.Examples.NResources.RSTR_HtmlSuite_TextStyles_html} Dim i = 0, count = embeddedResources.Length While i < count Dim embeddedResource = embeddedResources(i) Dim item As NListBoxItem = New NListBoxItem(NStringHelpers.InsertSpacesBeforeUppersAndDigits(embeddedResource.Name)) item.Tag = embeddedResource testListBox.Items.Add(item) i += 1 End While testListBox.Selection.Selected += AddressOf OnListBoxItemSelected testListBox.Selection.SingleSelect(testListBox.Items(0)) Return New NGroupBox("Predefined HTML pages", testListBox) End Function Private Function CreateNavigationGroupBox() As NGroupBox ' Create the navigation pair box m_NavigationTextBox = New NTextBox() m_NavigationTextBox.Text = DefaultAddress m_NavigationTextBox.VerticalPlacement = ENVerticalPlacement.Center Dim goButton As NButton = New NButton("Go") goButton.VerticalPlacement = ENVerticalPlacement.Center goButton.Click += AddressOf OnGoButtonClick Dim pairBox As NPairBox = New NPairBox(m_NavigationTextBox, goButton) pairBox.FitMode = ENStackFitMode.First pairBox.FillMode = ENStackFillMode.First pairBox.Spacing = 3 Return New NGroupBox("Import from URL", pairBox) End Function Private Function TryParseUrl(url As String, ByRef uri As Uri) As Boolean uri = Nothing url = NStringHelpers.SafeTrim(url) If String.IsNullOrEmpty(url) Then Return False If Not url.Contains("://") AndAlso url.IndexOf(":\") <> 1 AndAlso url(0) <> "/"c Then ' URI scheme check ' Windows file path check ' Unix file path check ' This URL doesn't have a scheme and is not a file path, so add an HTTP URI scheme url = "http://" & url End If Return Uri.TryCreate(url, UriKind.Absolute, uri) End Function Private Sub LoadSource(stream As Stream) Dim bytes = NStreamHelpers.ReadToEnd(stream) m_HtmlTextBox.Text = NEncoding.UTF8.GetString(bytes) End Sub Private Function LoadHtml(stream As Stream, baseUri As String) As NPromise(Of Boolean) m_ElapsedTimeLabel.Text = String.Empty stream.Position = 0 m_Stopwatch = Stopwatch.StartNew() Dim settings As NTextLoadSettings = Nothing If Not Equals(baseUri, Nothing) Then settings = New NTextLoadSettings() settings.BaseUri = New Uri(baseUri) End If Return m_PreviewRichText.LoadFromStreamAsync(stream, NTextFormat.Html, settings) End Function #End Region #Region "Event Handlers" Private Sub OnImportButtonClick(arg1 As NEventArgs) Dim bytes = NEncoding.UTF8.GetBytes(m_HtmlTextBox.Text) Using stream As MemoryStream = New MemoryStream(bytes) LoadHtml(stream, Nothing) End Using End Sub Private Sub OnListBoxItemSelected(arg1 As NItemEventArgs(Of NListBoxItem)) If arg1.TargetNode Is Nothing Then Return ' Determine the full name of the selected resource Dim embeddedResource As NEmbeddedResource = arg1.Item.Tag ' Read the stream and set it as text of the HTML code text box Dim stream As Stream = embeddedResource.Stream LoadSource(stream) LoadHtml(CType(stream, Stream), CStr(Nothing)).[Finally](Sub() stream.Close()) End Sub Private Sub OnGoButtonClick(arg1 As NEventArgs) Dim url = m_NavigationTextBox.Text If String.IsNullOrEmpty(url) Then Return ' Normalize the URL Dim uri As Uri If Not TryParseUrl(url, uri) Then NMessageBox.ShowError("Invalid URL or file path", "Error") Return End If If uri.IsFile Then ' Load from file Dim file = NFileSystem.Current.GetFile(url) file.OpenReadAsync().[Then](Sub(stream As Stream) Using stream LoadSource(stream) LoadHtml(stream, url) End Using End Sub) ElseIf NUriHelpers.IsHttp(uri) Then ' Load from URI Try m_Stopwatch = Stopwatch.StartNew() m_PreviewRichText.LoadFromUriAsync(uri) Catch ex As Exception m_Stopwatch.Stop() NMessageBox.ShowError(ex.Message, "Error") End Try End If End Sub Private Sub OnRichTextDocumentLoaded(args As NEventArgs) ' Show the elapsed time If m_Stopwatch IsNot Nothing Then m_Stopwatch.Stop() m_ElapsedTimeLabel.Text = "Elapsed time: " & m_Stopwatch.ElapsedMilliseconds.ToString() & " ms" End If End Sub #End Region #Region "Fields" Private m_HtmlTextBox As NTextBox Private m_PreviewRichText As NRichTextView Private m_NavigationTextBox As NTextBox Private m_ElapsedTimeLabel As NLabel Private m_Stopwatch As Stopwatch #End Region #Region "Static Methods" Private Shared Function CreatePairBox(widget1 As NWidget, widget2 As NWidget) As NPairBox Dim pairBox As NPairBox = New NPairBox(widget1, widget2, ENPairBoxRelation.Box1AboveBox2) pairBox.FitMode = ENStackFitMode.First pairBox.FillMode = ENStackFillMode.First pairBox.Spacing = NDesign.VerticalSpacing Return pairBox End Function #End Region #Region "Constants" Private Const DefaultAddress As String = "https://helpopenvision.nevron.com/Welcome.html" #End Region #Region "Nested Types" #End Region End Class

Download a fully functional VB.NET (.vb) HTML Import Example for WPF Solution