Как сохранить документ в формате HTML на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите или создайте документ.
  3. Сохраните в формате HTML.
  1. Сохранить в файл:
    
                // The file format will be detected automatically from the file extension: ".html".
                dc.Save(@"d:\Book.html");
    

    Чтобы не полагаться на расширение файла и гарантировать, что содержимое файла действительно является HTML, Вы можете указать HtmlFixedSaveOptions или HtmlFlowingSaveOptions в качестве 2-го параметра.

    
    dc.Save(@"d:\Book.html", new HtmlFixedSaveOptions());
    

    В HtmlFixedSaveOptions или HtmlFlowingSaveOptions Вы также можете установить различные параметры, влияющие на процесс сохранения.

    В фиксированном режиме HTML компонент отображает HTML-разметку, используя абсолютно позиционированные элементы.

    В потоковом режиме HTML компонент отображает HTML как потоковый документ без какого-либо абсолютного позиционирования.

                dc.Save(@"d:\Book.html", new HtmlFixedSaveOptions()
                {
                    Version = HtmlVersion.Html5,
                    CssExportMode = CssExportMode.Inline
                });
    
  2. Сохранить в потоке:
                // Let's save our document to a MemoryStream.
                using (MemoryStream ms = new MemoryStream())
                {
                    // HTML Fixed.
                    dc.Save(ms, new HtmlFixedSaveOptions());
                 
                    // Or HTML flowing.
                    dc.Save(ms, new HtmlFlowingSaveOptions());
                }
    

Полный код

using System.IO;
using SautinSoft.Document;

namespace Example
{
    class Program 
    {        
        static void Main(string[] args)
        {
            // Get your free 100-day key here:   
            // https://sautinsoft.com/start-for-free/

            SaveToHtmlFile();
            SaveToHtmlStream();
        }

        /// <summary>
        /// Open an existing document and saves it as HTML files (in the Fixed and Flowing modes).
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-html-net-csharp-vb.php
        /// </remarks>
        static void SaveToHtmlFile()
        {
            string inputFile = @"..\..\..\example.docx";

            DocumentCore dc = DocumentCore.Load(inputFile);           

            string fileHtmlFixed = @"Fixed-as-file.html";
            string fileHtmlFlowing = @"Flowing-as-file.html";

            // Save to HTML file: HtmlFixed.
            dc.Save(fileHtmlFixed, new HtmlFixedSaveOptions()
            {
                Version = HtmlVersion.Html5,
                CssExportMode = CssExportMode.Inline
            });

            // Save to HTML file: HtmlFlowing.
            dc.Save(fileHtmlFlowing, new HtmlFlowingSaveOptions()
            {
                Version = HtmlVersion.Html5,
                CssExportMode = CssExportMode.Inline,
                ListExportMode = HtmlListExportMode.ByHtmlTags
            });
			
			// Important for Linux: Install MS Fonts
			// sudo apt install ttf-mscorefonts-installer -y

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

        }

        /// <summary>
        /// Creates a new document and saves it as HTML documents (in the Fixed and Flowing modes) using MemoryStream.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-html-net-csharp-vb.php
        /// </remarks>
        static void SaveToHtmlStream()
        {
            // There variables are necessary only for demonstration purposes.
            byte[] fileData = null;
            string fileHtmlFixed = @"Fixed-as-stream.html";
            string fileHtmlFlowing = @"Flowing-as-stream.html";

            // Assume we already have a document 'dc'.
            DocumentCore dc = new DocumentCore();
            dc.Content.End.Insert("Hey Guys and Girls!");

            // Let's save our document to a MemoryStream.
            using (MemoryStream ms = new MemoryStream())
            {
                // HTML Fixed.
                dc.Save(ms, new HtmlFixedSaveOptions());
                fileData = ms.ToArray();

                File.WriteAllBytes(fileHtmlFixed, fileData);

                // Or HTML flowing.
                dc.Save(ms, new HtmlFlowingSaveOptions());
                fileData = ms.ToArray();

                File.WriteAllBytes(fileHtmlFlowing, fileData);
				
				// Important for Linux: Install MS Fonts
			    // sudo apt install ttf-mscorefonts-installer -y
            }
        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        SaveToHtmlFile()
        SaveToHtmlStream()
    End Sub
    ''' Get your free 100-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Open an existing document and saves it as HTML files (in the Fixed and Flowing modes).
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-html-net-csharp-vb.php
    ''' </remarks>
    Sub SaveToHtmlFile()
        Dim inputFile As String = "..\..\..\example.docx"

        Dim dc As DocumentCore = DocumentCore.Load(inputFile)

        Dim fileHtmlFixed As String = "Fixed-as-file.html"
        Dim fileHtmlFlowing As String = "Flowing-as-file.html"

        ' Save to HTML file: HtmlFixed.
        dc.Save(fileHtmlFixed, New HtmlFixedSaveOptions() With {
            .Version = HtmlVersion.Html5,
            .CssExportMode = CssExportMode.Inline
        })

        ' Save to HTML file: HtmlFlowing.
        dc.Save(fileHtmlFlowing, New HtmlFlowingSaveOptions() With {
            .Version = HtmlVersion.Html5,
            .CssExportMode = CssExportMode.Inline,
            .ListExportMode = HtmlListExportMode.ByHtmlTags
        })

        ' Open the results for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(fileHtmlFixed) With {.UseShellExecute = True})
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(fileHtmlFlowing) With {.UseShellExecute = True})

    End Sub

    ''' <summary>
    ''' Creates a new document and saves it as HTML documents (in the Fixed and Flowing modes) using MemoryStream.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/save-document-as-html-net-csharp-vb.php
    ''' </remarks>
    Sub SaveToHtmlStream()
        ' There variables are necessary only for demonstration purposes.
        Dim fileData() As Byte = Nothing
        Dim fileHtmlFixed As String = "Fixed-as-stream.html"
        Dim fileHtmlFlowing As String = "Flowing-as-stream.html"

        ' Assume we already have a document 'dc'.
        Dim dc As New DocumentCore()
        dc.Content.End.Insert("Hey Guys and Girls!")

        ' Let's save our document to a MemoryStream.
        Using ms As New MemoryStream()
            ' HTML Fixed.
            dc.Save(ms, New HtmlFixedSaveOptions())
            fileData = ms.ToArray()

            File.WriteAllBytes(fileHtmlFixed, fileData)

            ' Or HTML flowing.
            dc.Save(ms, New HtmlFlowingSaveOptions())
            fileData = ms.ToArray()

            File.WriteAllBytes(fileHtmlFlowing, fileData)
        End Using
    End Sub
End Module

Download


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



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

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