Getting started

edit

Install the package

Add the Meziantou.Framework.Markdown package to a project:

dotnet package add Meziantou.Framework.Markdown

The examples of this documentation omit the using directives. The first ones only need using Meziantou.Framework.Markdown;; see Namespaces for the others.

Convert Markdown to HTML

MarkdownConverter.ToHtml converts a Markdown string to HTML:

var html = MarkdownConverter.ToHtml("This is a text with some *emphasis*");
Assert.Equal("<p>This is a text with some <em>emphasis</em></p>\n", html);

Without a pipeline, the conversion follows the CommonMark specification, with no extension. Raw HTML in the Markdown is copied to the output: read Security before you render Markdown from an untrusted source.

Enable extensions

Tables, task lists, footnotes and the other syntaxes that CommonMark does not define come from extensions. Build a pipeline that enables them, and pass it to ToHtml:

var pipeline = new MarkdownPipelineBuilder()
    .UseAdvancedExtensions()
    .Build();

var html = MarkdownConverter.ToHtml("| a | b |\n|---|---|\n| 1 | 2 |", pipeline);
Assert.StartsWith("<table>", html);

UseAdvancedExtensions enables the most common extensions at once. Build the pipeline once and reuse it: it is immutable and can be shared between threads. Extensions lists all the extensions.

Read the syntax tree

MarkdownConverter.Parse returns the syntax tree of the document. Use it to find elements, such as the headings and the links:

var document = MarkdownConverter.Parse("# Title\n\nSee [the docs](https://example.com).");

foreach (var heading in document.Descendants<HeadingBlock>())
{
    Assert.Equal(1, heading.Level);
    Assert.Equal(0, heading.Line);
}

foreach (var link in document.Descendants<LinkInline>())
{
    Assert.Equal("https://example.com", link.Url);
}

Next steps