Skip to content

Instantly share code, notes, and snippets.

@muhadmr
Last active January 27, 2025 08:50
Show Gist options
  • Select an option

  • Save muhadmr/5711f0887531ba4dca6459aaa85e11d0 to your computer and use it in GitHub Desktop.

Select an option

Save muhadmr/5711f0887531ba4dca6459aaa85e11d0 to your computer and use it in GitHub Desktop.
using openxml to convert html to word - c#
// nuget
// Install-Package HtmlToOpenXml.dll -Version 2.1.0
// Install-Package DocumentFormat.OpenXml -Version 2.11.3
// using DocumentFormat.OpenXml.Packaging;
// using DocumentFormat.OpenXml.Wordprocessing;
// using HtmlToOpenXml;
public async Task TryConvert()
{
// using openxml
string htmlFile = "C:/someHtmlFile.html";
// Read the content of the file into a string
string fileContent = System.IO.File.ReadAllText(htmlFile);
await GenerateWordDocumentAsync(fileContent);
}
public async Task GenerateWordDocumentAsync(string text)
{
// Set the file name and path
var filePath = "C:/";
// create a random fileName using second ticks
var fileName = filePath + DateTime.Now.Ticks + ".docx";
using (FileStream wordStream = new FileStream(fileName, FileMode.Create, FileAccess.ReadWrite))
{
// Create a Wordprocessing document in memory
using (WordprocessingDocument wordDoc = WordprocessingDocument.Create(wordStream, DocumentFormat.OpenXml.WordprocessingDocumentType.Document))
{
// Add a main document part to the Word file
MainDocumentPart mainPart = wordDoc.AddMainDocumentPart();
mainPart.Document = new Document(new Body());
// Convert HTML content to Word content and append to the document
HtmlConverter converter = new(mainPart);
var documentBody = mainPart.Document.Body;
var paragraphs = converter.Parse(text);
documentBody.Append(paragraphs);
// Save the Word document
wordDoc.Save();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment