How to create a HTML document in C# and VB.Net

How to create a HTML document in C# and VB.Net

Let's create a simple HTML document with two paragraphs and some formatted text, like a shown on picture:

A simple HTML document

Main steps

  1. Notice you are importing the SautinSoft.Document namespace.
    using SautinSoft.Document;
  2. Let's create an instance of DocumentCore with the name dc.
    
    DocumentCore dc = new DocumentCore();
    
    DocumentCore is root class, it represents a document itself.
  3. Add a new Section into our document.
    
        Section section = new Section(dc);
        dc.Sections.Add(section);
    
    Section is a collection of Block elements that are grouped by a unify page properties concept and having specific headers and footers.
  4. Create a new Paragraph with two Run elements (which represent our text), next add it into the section.
    
        // Way 1: Add 1st paragraph.
        Paragraph par1 = new Paragraph(dc);
        par1.ParagraphFormat.Alignment = HorizontalAlignment.Center;
        section.Blocks.Add(par1);
    
        // Let's create a characterformat for text in the 1st paragraph.
        CharacterFormat cf = new CharacterFormat() { FontName = "Verdana", Size = 16, FontColor = Color.Orange };
    
        Run text1 = new Run(dc, "This is a first line in 1st paragraph!");
        text1.CharacterFormat = cf;
        par1.Inlines.Add(text1);
    
        // Let's add a line break into our paragraph.
        par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));
    
        Run text2 = text1.Clone();
        text2.Text = "Let's type a second line.";
        par1.Inlines.Add(text2);
    
    Paragraph is a Block derived element used to group Inline elements like a Run, Shape, Picture, Field etc.
    Run (Inline derived) is a container for one or more text characters having the same character formatting.
  5. Add a second Paragraph with text using ContentRange class.
    The ContentRange recognizes the line feed «\n» character as a signal to create a new Paragraph.
    
        // Way 2 (easy): Add 2nd paragraph using ContentRange.
        dc.Content.End.Insert("\nThis is a first line in 2nd paragraph.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true });
        SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak);
        dc.Content.End.Insert(lBr.Content);
        dc.Content.End.Insert("This is a second line.", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single });
    
    ContentRange represents an area in document as a contiguous sequence of characters boundend by start and end positions. It allows to insert and extract data in a streaming manner in(from) desired positions.
  6. We can save our document to HTML format using two options: HtmlFixedSaveOptions or HtmlFlowingSaveOptions.
    
        // Save the dc as HtmlFixed document.
        dc.Save(@"d:\Result-fixed.html", new HtmlFixedSaveOptions());
    

    or

    
                // Save the dc as HtmlFlowing document.
        dc.Save(@"d:\Result-flowing.html", new HtmlFlowingSaveOptions());
    

    Here you may find an extra info How to save a document to HTML format with options.

 

Complete code

using SautinSoft.Document;

namespace Example
{
    class Program
    {       
        static void Main(string[] args)
        {
            CreateHtml();
        }
		
        /// <summary>
        /// Creates a new document and saves it into HTML format.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/examples/create-html-document-net-csharp-vb.php
        /// </remarks>
        public static void CreateHtml()
        {          
            // Set a path to our HTML document.
            string htmlFixedPath = @"Result-Fixed.html";
            string htmlFlowingPath = @"Result-Flowing.html";

            // Let's create a simple HTML document.
            DocumentCore dc = new DocumentCore();

            // Add new section.
            Section section = new Section(dc);
            dc.Sections.Add(section);

            // Add two paragraphs using different ways:
            // Way 1: Add 1st paragraph.
            Paragraph par1 = new Paragraph(dc);
            par1.ParagraphFormat.Alignment = HorizontalAlignment.Center;
            section.Blocks.Add(par1);

            // Let's create a characterformat for text in the 1st paragraph.
            CharacterFormat cf = new CharacterFormat() { FontName = "Verdana", Size = 16, FontColor = Color.Orange };

            Run text1 = new Run(dc, "This is a first line in 1st paragraph!");
            text1.CharacterFormat = cf;
            par1.Inlines.Add(text1);

            // Let's add a line break into our paragraph.
            par1.Inlines.Add(new SpecialCharacter(dc, SpecialCharacterType.LineBreak));

            Run text2 = text1.Clone();
            text2.Text = "Let's type a second line.";
            par1.Inlines.Add(text2);

            // Way 2 (easy): Add 2nd paragraph using ContentRange.
            dc.Content.End.Insert("\nThis is a first line in 2nd paragraph.", new CharacterFormat() { Size = 25, FontColor = Color.Blue, Bold = true });
            SpecialCharacter lBr = new SpecialCharacter(dc, SpecialCharacterType.LineBreak);
            dc.Content.End.Insert(lBr.Content);
            dc.Content.End.Insert("This is a second line.", new CharacterFormat() { Size = 20, FontColor = Color.DarkGreen, UnderlineStyle = UnderlineType.Single });

            // Save HTML document as HTML-fixed format.
            dc.Save(htmlFixedPath, new HtmlFixedSaveOptions());
            // Save HTML document as HTML-flowing format.
            dc.Save(htmlFlowingPath, new HtmlFlowingSaveOptions());

            // Open the results for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(htmlFixedPath) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(htmlFlowingPath) { UseShellExecute = true });
        }
    }
}

Download.

        
            Imports SautinSoft.Document

Module Sample
    Sub Main()
        CreateHtml()
    End Sub

    ''' <summary>
    ''' Creates a new document and saves it into HTML format.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/examples/create-html-document-net-csharp-vb.php
    ''' </remarks>
    Sub CreateHtml()
        ' Set a path to our HTML document.
        Dim htmlFixedPath As String = "Result-Fixed.html"
        Dim htmlFlowingPath As String = "Result-Flowing.html"

        ' Let's create a simple HTML document.
        Dim dc As New DocumentCore()

        ' Add new section.
        Dim section As New Section(dc)
        dc.Sections.Add(section)

        ' Add two paragraphs using different ways:
        ' Way 1: Add 1st paragraph.
        Dim par1 As New Paragraph(dc)
        par1.ParagraphFormat.Alignment = HorizontalAlignment.Center
        section.Blocks.Add(par1)

        ' Let's create a characterformat for text in the 1st paragraph.
        Dim cf As New CharacterFormat() With {
            .FontName = "Verdana",
            .Size = 16,
            .FontColor = Color.Orange
        }

        Dim text1 As New Run(dc, "This is a first line in 1st paragraph!")
        text1.CharacterFormat = cf
        par1.Inlines.Add(text1)

        ' Let's add a line break into our paragraph.
        par1.Inlines.Add(New SpecialCharacter(dc, SpecialCharacterType.LineBreak))

        Dim text2 As Run = text1.Clone()
        text2.Text = "Let's type a second line."
        par1.Inlines.Add(text2)

        ' Way 2 (easy): Add 2nd paragraph using ContentRange.
        dc.Content.End.Insert(vbLf & "This is a first line in 2nd paragraph.", New CharacterFormat() With {
            .Size = 25,
            .FontColor = Color.Blue,
            .Bold = True
        })
        Dim lBr As New SpecialCharacter(dc, SpecialCharacterType.LineBreak)
        dc.Content.End.Insert(lBr.Content)
        dc.Content.End.Insert("This is a second line.", New CharacterFormat() With {
            .Size = 20,
            .FontColor = Color.DarkGreen,
            .UnderlineStyle = UnderlineType.Single
        })

        ' Save HTML document as HTML-fixed format.
        dc.Save(htmlFixedPath, New HtmlFixedSaveOptions())
        ' Save HTML document as HTML-flowing format.
        dc.Save(htmlFlowingPath, New HtmlFlowingSaveOptions())


        ' Open the results for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(htmlFixedPath) With {.UseShellExecute = True})
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(htmlFlowingPath) With {.UseShellExecute = True})
    End Sub
End Module

Download.


If you need a new code example or have a question: email us at support@sautinsoft.com or ask at Online Chat (right-bottom corner of this page) or use the Form below:



Questions and suggestions from you are always welcome!

We are developing .Net components since 2002. We know PDF, DOCX, RTF, HTML, XLSX and Images formats. If you need any assistance with creating, modifying or converting documents in various formats, we can help you. We will write any code example for you absolutely free.

© SautinSoft 2002 - 2019