Convert HTML to Markdown

EvoPdf Next for .NET can convert HTML pages and HTML strings to Markdown text. The headings, paragraphs, lists, tables, code blocks, links and images of the HTML document are written with the Markdown syntax, which makes the content easy to store, to index and to pass to AI tools.

The HTML to Markdown functionality is part of the HTML to PDF Converter component of the EvoPdf Next for .NET library. The HTML document is loaded with its CSS and JavaScript before it is converted, like in the conversion to PDF.

Convert HTML to Markdown Using the HtmlToMarkdownConverter Class

The EvoPdf.NextHtmlToMarkdownConverter class converts a web page given by its URL or a HTML string to Markdown. The result can be returned as a string or written to a file encoded as UTF-8.

Convert an URL to Markdown
// Create a HTML to Markdown converter object with default settings
HtmlToMarkdownConverter htmlToMarkdownConverter = new HtmlToMarkdownConverter();

// Convert the web page to a Markdown string
string markdown = htmlToMarkdownConverter.ConvertUrl("https://www.example.com");
Convert a HTML String to Markdown
// Create a HTML to Markdown converter object with default settings
HtmlToMarkdownConverter htmlToMarkdownConverter = new HtmlToMarkdownConverter();

// Convert the HTML string to a Markdown string
// The base URL is used to resolve the relative URLs found in the HTML string
string markdown = htmlToMarkdownConverter.ConvertHtml("<h1>Title</h1><p>The first paragraph</p>", "https://www.example.com/");
Convert an URL to a Markdown File
HtmlToMarkdownConverter htmlToMarkdownConverter = new HtmlToMarkdownConverter();

// Convert the web page and write the Markdown text to a file
htmlToMarkdownConverter.ConvertUrlToFile("https://www.example.com", "page.md");

Markdown Options

The HtmlToMarkdownConverterIncludeLinks property controls if the links of the HTML document are written as Markdown links. The default value is true.

The HtmlToMarkdownConverterImageMode property controls how the images of the HTML document are written, using a value of the EvoPdf.NextMarkdownImageMode enumeration. By default the images are written with their alternative text and their URL. The images can also be left out, written with the source they have in the HTML document or embedded in the Markdown text.

Set the Markdown Options
// Write the text of the links without their addresses
htmlToMarkdownConverter.IncludeLinks = false;

// Embed the images in the Markdown text
htmlToMarkdownConverter.ImageMode = MarkdownImageMode.Embed;

You can convert only a part of the HTML document by setting the HtmlToMarkdownConverterConvertedElementsSelector property with a CSS selector, or leave elements out of the result with the HtmlToMarkdownConverterExcludedElementsSelector property.

Select the HTML Elements to Convert
// Convert only the main content of the page
htmlToMarkdownConverter.ConvertedElementsSelector = "main";

// Leave the navigation and the footer out of the Markdown
htmlToMarkdownConverter.ExcludedElementsSelector = "nav, footer";

HTML Loading Options

The width of the browser window used to load the HTML document is set by the HtmlToMarkdownConverterHtmlViewerWidth property. For pages that fill their content from JavaScript after they are loaded you can set a delay with the HtmlToMarkdownConverterConversionDelay property or wait for an element to be present with the HtmlToMarkdownConverterWaitForSelector property.

Wait for the Content Before the Conversion
// Start the conversion after the element with the given CSS selector is present in the page
htmlToMarkdownConverter.WaitForSelector = "#content-loaded";

Asynchronous HTML to Markdown Methods

All the conversion methods have asynchronous versions that accept a cancellation token.

Asynchronously Convert an URL to Markdown
HtmlToMarkdownConverter htmlToMarkdownConverter = new HtmlToMarkdownConverter();

string markdown = await htmlToMarkdownConverter.ConvertUrlAsync("https://www.example.com", cancellationToken);

Code Sample - Convert HTML to Markdown

Convert HTML to Markdown in ASP.NET Core
using System;
using System.ComponentModel.DataAnnotations;
using System.Text;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using EvoPdf_Next_AspNetDemo.Models;
using EvoPdf_Next_AspNetDemo.Models.HTML_to_Markdown;

// Use EVO PDF Namespace
using EvoPdf.Next;

namespace EvoPdf_Next_AspNetDemo.Controllers.HTML_to_Markdown
{
    public class HTML_to_MarkdownController : Controller
    {
        public IActionResult Index()
        {
            var model = new HTML_to_Markdown_ViewModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult ConvertHtmlToMarkdown(HTML_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 a HTML to Markdown converter object with default settings
            HtmlToMarkdownConverter htmlToMarkdownConverter = new HtmlToMarkdownConverter();

            // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width
            htmlToMarkdownConverter.HtmlViewerWidth = model.HtmlViewerWidth;

            // Write the links of the HTML document as Markdown links
            htmlToMarkdownConverter.IncludeLinks = model.IncludeLinks;

            // Set how the images of the HTML document are written in Markdown
            htmlToMarkdownConverter.ImageMode = SelectedImageMode(model.ImageMode);

            // Set the maximum time in seconds to wait for HTML page to be loaded
            // Leave it not set for a default 120 seconds maximum wait time
            htmlToMarkdownConverter.NavigationTimeout = model.NavigationTimeout;

            // Set an additional delay in seconds to wait for JavaScript or AJAX calls after page load completed
            // Set this property to 0 if you don't need to wait for such asynchronous operations to finish
            if (model.ConversionDelay.HasValue)
                htmlToMarkdownConverter.ConversionDelay = model.ConversionDelay.Value;

            string markdown = null;
            if (model.HtmlPageSource == "Url")
            {
                string url = model.Url;

                // Convert the HTML page given by an URL to Markdown
                markdown = htmlToMarkdownConverter.ConvertUrl(url);
            }
            else
            {
                string htmlString = model.HtmlString;
                string baseUrl = model.BaseUrl;

                // Convert a HTML string with a base URL to Markdown
                markdown = htmlToMarkdownConverter.ConvertHtml(htmlString ?? string.Empty, baseUrl);
            }

            // Send the Markdown file to browser
            FileResult fileResult = new FileContentResult(Encoding.UTF8.GetBytes(markdown), "text/markdown; charset=utf-8");
            fileResult.FileDownloadName = "HTML_to_Markdown.md";

            return fileResult;
        }

        private MarkdownImageMode SelectedImageMode(string selectedValue)
        {
            switch (selectedValue)
            {
                case "None":
                    return MarkdownImageMode.None;
                case "KeepSource":
                    return MarkdownImageMode.KeepSource;
                case "Embed":
                    return MarkdownImageMode.Embed;
                default:
                    return MarkdownImageMode.Link;
            }
        }
    }
}

See Also