DEV Community

jelizaveta
jelizaveta

Posted on

Converting HTML to Word or Word to HTML Using C#

As the standard format for web content, HTML and the common office document format Word often need to be converted between each other in many enterprise-level applications. Whether it is generating Word reports from dynamic content in a database or publishing existing Word documents as web pages, mastering efficient conversion methods can significantly improve productivity.

This article introduces how to use Spire.Doc for .NET, a professional document processing component, to easily convert between HTML and Word using C# code.

Why Choose Spire.Doc for .NET?

The .NET framework does not natively support manipulating or converting Word or HTML documents. While there are open-source alternatives (such as HtmlAgilityPack combined with OpenXML SDK), they often require developers to handle many low-level details manually and may fall short in style preservation, image embedding, and other areas.

Spire.Doc for .NET provides a powerful and easy-to-use API that enables document creation, editing, and conversion without installing Microsoft Office on the server. It excels in conversion quality:

  • Style Preservation : Full support for CSS styles in HTML, including text formatting, colors, alignment, and more.
  • Image Handling : Automatically recognizes and embeds <img> tags from HTML.
  • Table Structure : Preserves the original layout of HTML tables to avoid misalignment.
  • Development Complexity : The API is cleanly designed with a low learning curve.

Preparation: Installing Spire.Doc

Before coding, you need to add a reference to Spire.Doc in your project. The recommended approach is to run the following command in the NuGet Package Manager Console:

Install-Package Spire.Doc
Enter fullscreen mode Exit fullscreen mode

Scenario 1: Converting an HTML String to Word

This scenario is highly flexible and suitable for fetching HTML content from databases, API endpoints, or other dynamic data sources, and generating Word documents on the fly.

The following code demonstrates how to read the content of an HTML file (as a string) and convert it to a .docx file:

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;

namespace ConvertHtmlStringToWord
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Create a Document object
            Document document = new Document();

            // 2. Add a section
            Section section = document.AddSection();
            // Optional: set page margins
            section.PageSetup.Margins.All = 2;

            // 3. Add a paragraph
            Paragraph paragraph = section.AddParagraph();

            // 4. Read the HTML string from a file
            string htmlFilePath = @"C:\Users\Administrator\Desktop\Html.html";
            string htmlString = File.ReadAllText(htmlFilePath, System.Text.Encoding.UTF8);

            // 5. Append the HTML string to the paragraph
            paragraph.AppendHTML(htmlString);

            // 6. Save as a Word document
            document.SaveToFile("AddHtmlStringToWord.docx", FileFormat.Docx);

            // 7. Release resources
            document.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

Key Method Explanation :

  • Paragraph.AppendHTML(htmlString) is the core of the conversion. It parses the incoming HTML string and fully converts its formatting, images, and layout into Word paragraph content.
  • document.SaveToFile() allows you to specify the output format as FileFormat.Docx.

Scenario 2: Converting an HTML File Directly to Word

If you already have an existing HTML file and want to convert it directly to a Word document, the code is even more concise:

using Spire.Doc;

namespace ConvertHtmlToWord
{
    class Program
    {
        static void Main(string[] args)
        {
            // 1. Create a Document object
            Document document = new Document();

            // 2. Load the HTML file directly
            document.LoadFromFile(@"C:\Users\Administrator\Desktop\MyHtml.html", FileFormat.Html);

            // 3. Save as a Word document
            document.SaveToFile("HtmlToWord.docx", FileFormat.Docx);

            // 4. Release resources
            document.Dispose();
        }
    }
}
Enter fullscreen mode Exit fullscreen mode

This approach does everything in one step. The Document.LoadFromFile() method directly supports loading files in FileFormat.Html format, eliminating the need to manually read the file content.

Key Considerations

In practice, keep the following points in mind to ensure the best conversion results:

  1. CSS Style Support : Spire.Doc supports most common CSS styles, such as font-size, color, text-align, and more. However, for very complex CSS layouts, there may be minor differences in the output.
  2. Image Paths : <img> tags in HTML are automatically converted to images in Word. Make sure the image paths (whether local paths or network URLs) are accessible during conversion.
  3. Table Layout : For tables with complex structures, it is advisable to avoid special layout attributes like table-layout: fixed to ensure the converted tables display correctly in Word.
  4. Performance : For large files with substantial content or high-resolution images, it is recommended to perform the conversion in a background thread or asynchronous task to avoid blocking the main UI thread.

Summary

With Spire.Doc for .NET, developers can achieve high-quality, high-fidelity conversions between HTML and Word in C# projects with minimal code. Whether you are dealing with dynamically generated HTML strings or batch-converting existing HTML files, this library provides a stable and efficient solution. It helps you quickly build automated document processing workflows and focus more on your business logic.

Top comments (0)