MariGold.OpenXHTML is a GitHub project to convert HTML to Open XML Word documents. It is a wrapper library built over the Open XML SDK 2.5 library. It simply extracts each element from HTML documents and creates corresponding Open XML word elements in the Word file. For example, any div elements in HTML document will be converted as paragraphs in the Word document. Not all the HTML/CSS behaviors can be supported in the Word documents. Say, floated div may not convert in the same manner because the Word documents do not support floated paragraphs.
This article demonstrates how to create a Windows application to convert an HTML file to an Open XML Word document. Our sample application is a simple form with one textbox and two buttons. One button is to select an HTML file with an open dialog box and another is one to convert this HTML file and save the Word document with a Save dialog box.
Set up the application
This article is using Visual Studio 2015 Community Edition and .NET 4.5 Framework to create the application. Open the "New Project" dialog box and select the "Windows Forms Application".

Modify the default Form1 form as shown below.

Modify the default Form1 form as shown below.
Now, it's time to add the reference to the MariGold.OpenXHTML library. It is available as NuGet package. In Visual Studio, select Tools -> NuGet Package Manager -> Package Manager Console and enter the following command. Alternatively, you can use the "Manage NuGet Packages" menu from the "References" project folder.
Install-Package MariGold.OpenXHTML
This will also install the following dependencies.
- DocumentFormat.OpenXml - OpenXml SDK 2.5 library to create Open XML word documents.
- MariGold.HtmlParser - To parse and extract the HTML elements from the input file.
How the code works
The "Browse" button simply selects an HTML file and copies the file path into the text box.
- if (openFileDialog1.ShowDialog() == DialogResult.OK)
- {
- txtFile.Text = openFileDialog1.FileName;
- }
- if (saveFileDialog1.ShowDialog() == DialogResult.OK)
- {
- WordDocument doc = new WordDocument(saveFileDialog1.FileName);
- using (StreamReader sr = new StreamReader(txtFile.Text))
- {
- doc.Process(new HtmlParser(sr.ReadToEnd()));
- }
- doc.Save();
- }
The WordDocument class also contains a couple of methods and properties to manipulate the Word document like relative image URL or link URL. Refer to the gGitHub project home page for more information.
Rhea TPosted Mar 2, 2020, 8:39 AM
Hello, the library for converting from HTML to doc really works well. Need further help on this. In our project we have images in the HTML file, can you please let us know how to convert image to .docx. Also the converted file when we open in Libre Open Office, the formatting of the document goes away. is there any solution for that too.