Convert HTML to Markdown

HiQPdf 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 HiQPdf 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 HtmlToMarkdown Class

The HiQPdf.NextHtmlToMarkdown 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
HtmlToMarkdown htmlToMarkdownConverter = new HtmlToMarkdown();

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

// 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.ConvertHtmlToMarkdown("<h1>Title</h1><p>The first paragraph</p>", "https://www.example.com/");
Convert an URL to a Markdown File
HtmlToMarkdown htmlToMarkdownConverter = new HtmlToMarkdown();

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

Markdown Options

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

The HtmlToMarkdownImageMode property controls how the images of the HTML document are written, using a value of the HiQPdf.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 HtmlToMarkdownConvertedElementsSelector property with a CSS selector, or leave elements out of the result with the HtmlToMarkdownExcludedElementsSelector 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 HtmlToMarkdownBrowserWidth property. For pages that fill their content from JavaScript after they are loaded you can set a delay with the HtmlToMarkdownWaitBeforeConvert property or wait for an element to be present with the HtmlToMarkdownWaitForSelector 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
HtmlToMarkdown htmlToMarkdownConverter = new HtmlToMarkdown();

string markdown = await htmlToMarkdownConverter.ConvertUrlToMarkdownAsync("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 HiQPdf_Next_AspNetDemo.Models;

using HiQPdf.Next;

namespace HiQPdf_Next_AspNetDemo.Controllers
{
    public class HtmlToMarkdownController : Controller
    {
        public IActionResult Index()
        {
            var model = new HtmlToMarkdownViewModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult ConvertToMarkdown(HtmlToMarkdownViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Set the serial number received after purchase to use the library in licensed mode; leave it commented for demo mode
            // Licensing.SerialNumber = "your-serial-number";

            // create the HTML to Markdown converter
            HtmlToMarkdown htmlToMarkdownConverter = new HtmlToMarkdown();

            // set browser width
            htmlToMarkdownConverter.BrowserWidth = model.BrowserWidth;

            // 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 wait time before starting conversion
            htmlToMarkdownConverter.WaitBeforeConvert = model.WaitTime;

            // set HTML Load timeout
            htmlToMarkdownConverter.HtmlLoadedTimeout = model.LoadHtmlTimeout;

            string markdown = null;
            if (model.UrlOrHtmlCode == "ConvertUrl")
            {
                // convert URL
                string url = model.Url;

                markdown = htmlToMarkdownConverter.ConvertUrlToMarkdown(url);
            }
            else
            {
                // convert HTML code
                string htmlCode = model.HtmlCode;
                string baseUrl = model.BaseUrl;

                markdown = htmlToMarkdownConverter.ConvertHtmlToMarkdown(htmlCode ?? string.Empty, baseUrl);
            }

            // send the Markdown file to browser
            FileResult fileResult = new FileContentResult(Encoding.UTF8.GetBytes(markdown), "text/markdown; charset=utf-8");
            fileResult.FileDownloadName = "HtmlToMarkdown.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