The Word to Markdown Converter writes the content of Word DOCX documents as Markdown text, with the headings, lists, tables, links, notes, formulas and pictures of the document.
The Word to Markdown Converter is part of the Word to PDF component of the EvoPdf Next for .NET library. It is available in the applications that reference the NuGet packages of this component, described in the Convert Word DOCX to PDF documentation section.
The EvoPdf.NextWordToMarkdownConverter class converts a Word document from a file or from a memory buffer to a Markdown string or to a Markdown file.
// Create a Word to Markdown converter instance
WordToMarkdownConverter wordToMarkdownConverter = new WordToMarkdownConverter();
// Convert the Word file to a Markdown string
string markdown = wordToMarkdownConverter.ConvertToMarkdown("document.docx");WordToMarkdownConverter wordToMarkdownConverter = new WordToMarkdownConverter();
// Convert the Word document and write the Markdown text to a file encoded as UTF-8
wordToMarkdownConverter.ConvertToMarkdownFile(wordBytes, "document.md");The Markdown text follows the structure of the Word document:
The paragraphs with heading styles are written as Markdown headings of the same level
The bold, italic and strikethrough text keeps its formatting
The numbered and bulleted lists are written as Markdown lists with their nested levels
The tables are written as Markdown tables
The hyperlinks are written as Markdown links
The footnotes and the endnotes are written as Markdown footnotes
The formulas are written in LaTeX notation between dollar signs
A chart is written with its title and with its data as a table
The text boxes and the diagrams are written with their text
The Markdown text has the content of the document body, without the headers and footers of the pages.
A picture of the document is written by default with its alternative text. The WordToMarkdownConverterImageMode property, with a value of the EvoPdf.NextWordToMarkdownImageMode enumeration, also writes the image of the picture, embedded in the Markdown text or saved as a file in a folder.
wordToMarkdownConverter.ImageMode = WordToMarkdownImageMode.Embed;When the pictures are saved as files, the WordToMarkdownConverterImagesFolder property gives the folder and the WordToMarkdownConverterImageFileName property gives the name of the files, which is followed by a number. The links of the Markdown text use the name of the images folder or the path given by the WordToMarkdownConverterImagesLinkPath property.
wordToMarkdownConverter.ImageMode = WordToMarkdownImageMode.File;
// The folder where the image files are saved
wordToMarkdownConverter.ImagesFolder = "output/document_images";
// Optionally set the path used by the links of the Markdown text and the name of the files
wordToMarkdownConverter.ImagesLinkPath = "document_images";
wordToMarkdownConverter.ImageFileName = "picture";To convert a password protected Word document set the WordToMarkdownConverterOpenPassword property before the conversion.
wordToMarkdownConverter.OpenPassword = "open-password";The conversion methods have asynchronous versions that accept a cancellation token.
string markdown = await wordToMarkdownConverter.ConvertToMarkdownAsync(wordBytes, cancellationToken);using System;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using EvoPdf_Next_AspNetDemo.Models;
using EvoPdf_Next_AspNetDemo.Models.Word_to_PDF;
// Use EVO PDF Namespace
using EvoPdf.Next;
namespace EvoPdf_Next_AspNetDemo.Controllers.Word_to_PDF
{
public class Word_to_MarkdownController : Controller
{
private readonly IWebHostEnvironment m_hostingEnvironment;
public Word_to_MarkdownController(IWebHostEnvironment hostingEnvironment)
{
m_hostingEnvironment = hostingEnvironment;
}
public IActionResult Index()
{
var model = SetViewModel();
return View(model);
}
[HttpPost]
public async Task<IActionResult> ConvertWordToMarkdown(Word_to_Markdown_ViewModel model)
{
if (!ModelState.IsValid)
{
var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
throw new ValidationException(errorMessage);
}
// Set the license key received after purchase to use the library in licensed mode; leave it commented for demo mode
// Licensing.LicenseKey = "your-license-key";
// Create the Word to Markdown converter instance with default options
WordToMarkdownConverter wordToMarkdownConverter = new WordToMarkdownConverter();
// Optionally set the password to open a password-protected Word document
if (!string.IsNullOrEmpty(model.OpenPassword))
wordToMarkdownConverter.OpenPassword = model.OpenPassword;
// Write the pictures as their alternative text or embed their images in the Markdown text
wordToMarkdownConverter.ImageMode = model.ImageMode == "Embed" ? WordToMarkdownImageMode.Embed : WordToMarkdownImageMode.None;
byte[] inputWordBytes = null;
string outputFileName = null;
// If an uploaded file exists, use it with priority
if (model.WordFile != null && model.WordFile.Length > 0)
{
try
{
using var ms = new MemoryStream();
await model.WordFile.CopyToAsync(ms);
inputWordBytes = ms.ToArray();
}
catch (Exception ex)
{
throw new Exception("Failed to read the uploaded Word file", ex);
}
outputFileName = Path.GetFileNameWithoutExtension(model.WordFile.FileName) + ".md";
}
else
{
// Otherwise, fall back to the URL
string wordUrl = model.WordFileUrl?.Trim();
if (string.IsNullOrWhiteSpace(wordUrl))
throw new Exception("No Word file provided: upload a file or specify a URL");
try
{
if (wordUrl.StartsWith("file://", StringComparison.OrdinalIgnoreCase))
{
string localPath = new Uri(wordUrl).LocalPath;
inputWordBytes = await System.IO.File.ReadAllBytesAsync(localPath);
}
else
{
using var httpClient = new System.Net.Http.HttpClient();
inputWordBytes = await httpClient.GetByteArrayAsync(wordUrl);
}
}
catch (Exception ex)
{
throw new Exception("Could not download the Word file from URL", ex);
}
outputFileName = Path.GetFileNameWithoutExtension(model.WordFileUrl) + ".md";
}
// Convert the Word document to Markdown
string markdown = wordToMarkdownConverter.ConvertToMarkdown(inputWordBytes);
// Encode the Markdown text as UTF-8 bytes
byte[] outputMarkdownBytes = Encoding.UTF8.GetBytes(markdown);
// Return the Markdown text as a downloadable file
return File(outputMarkdownBytes, "text/markdown; charset=utf-8", outputFileName);
}
private Word_to_Markdown_ViewModel SetViewModel()
{
var model = new Word_to_Markdown_ViewModel();
HttpRequest request = ControllerContext.HttpContext.Request;
UriBuilder uriBuilder = new UriBuilder();
uriBuilder.Scheme = request.Scheme;
uriBuilder.Host = request.Host.Host;
if (request.Host.Port != null)
uriBuilder.Port = (int)request.Host.Port;
uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
uriBuilder.Query = request.QueryString.ToString();
string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Word_to_Markdown".Length);
model.WordFileUrl = rootUrl + "/DemoAppFiles/Input/Word_Files/Word_Document.docx";
return model;
}
}
}