English | 繁體中文
Markdown viewers for .NET that show the same text the same way on different front ends, and Markdown source editors for Avalonia and Blazor. One package parses the text and applies the safety policy; a package for each UI framework renders the result, adds a reader with a table of contents around it, and edits the source.
| Package | For |
|---|---|
Polhem.Markdown |
Parsing (with Markdig), the safety policy shared by the viewers, and HTML export |
Polhem.Markdown.Avalonia |
A viewer control, a reader control with a table of contents, and a source editor control for Avalonia |
Polhem.Markdown.Blazor |
A viewer component for Blazor, rendering semantic HTML styled with CSS variables, a reader component with a table of contents, and a source editor component |
The packages are published on nuget.org; the changes of each release are in the CHANGELOG. They are at 0.x: a minor version may still change the API, and the CHANGELOG says when it does.
Both viewers render the same model, so a reply looks alike in a browser and in a desktop or mobile app. The picture shows the start of the sample text in each.
| Syntax or capability | Written as, or what it does | Avalonia | Blazor |
|---|---|---|---|
| Headings, emphasis, quotes, lists, rules | CommonMark | ✓ | ✓ |
| Strikethrough | ~~text~~ |
✓ | ✓ |
| Task lists | - [x] done |
✓ | ✓ |
| Tables with column alignment | :--, :-:, --: |
✓ | ✓ |
| Footnotes | text[^note] |
✓ | ✓ |
| GitHub alerts | > [!NOTE], [!TIP], [!IMPORTANT], [!WARNING], [!CAUTION] |
✓ | ✓ |
| Emoji shortcodes | :wave: |
✓ | ✓ |
| Front matter | YAML (---) and TOML (+++): hidden, or shown as a title, a byline and tags, and the other fields behind More (ShowFrontMatter); MarkdownFrontMatter.Read reads the fields |
✓ | ✓ |
| Links to a heading | [setup](#setup) scrolls to it |
✓ | ✓ |
| Code blocks | Language label, copy button, highlighting for common languages | ✓ | ✓ |
| Code block actions | A host's own buttons next to Copy, such as "Insert at cursor", on the blocks it chooses (CodeBlockActions) |
✓ | ✓ |
| Mermaid diagrams | Flowcharts, sequence, class, state, ER, Gantt, pie and the other types Mermaider draws, without a script | ✓ | ✓ |
| Math | $…$, $$…$$ and ```math, laid out without a script |
✓ | ✓ |
| HTML that README files use | <div align>, <details>, <sup>, <kbd>, <img>, <picture>; other HTML is dropped |
✓ | ✓ |
| Link schemes | Only allowed schemes can be clicked (http, https, mailto by default) |
✓ | ✓ |
| Image schemes | Only allowed schemes load (https by default) |
✓ | ✓ |
| Image hosts | Only listed hosts load, when the host lists any (AllowedImageHosts) |
✓ | ✓ |
| Holding back images | The host decides for each address, learns which images it held back, and loads them later, as a mail client does (ImageRequestFilter) |
✓ | ✓ |
| SVG images | Trusted badge hosts | Every allowed image | |
| Selecting text | A drag runs across blocks; copying gives the same plain text on both, with tabs between table cells, an image as its alternative text and a formula as LaTeX; a host's Edit menu selects all and copies | ✓ | ✓ |
| Streaming | Set the text again as a reply arrives; with IsStreaming, syntax the reply leaves open shows as it will once complete |
✓ | ✓ |
| Light and dark themes | Brushes | CSS variables | |
| Source positions | For keeping an editor in step | ✓ | ✓ |
| Headings | Listed for a table of contents, and scrolled to by id | ✓ | ✓ |
| Table of contents | MarkdownReader scrolls a viewer with a rail of its headings along the edge; the list slides out over the text or is pinned beside it, marking the section being read |
✓ | ✓ |
| Finding text | A find bar on Ctrl+F (⌘F) on Avalonia, the browser's own find on Blazor, and the same API on both | ✓ | ✓ |
| Wide tables | A table wider than the viewer scrolls sideways, and ExpandTables (on by default) adds a button that opens it over the window |
✓ | ✓ |
| Opening an image | ZoomImages opens an image at full size over the window, to zoom and pan; a handler can show it instead. A save button saves the original file |
✓ | ✓ |
| Screen readers and keyboard | Headings with their level, links, lists, tables and alerts are announced; Tab moves through links and buttons, Enter follows a link | ✓ | ✓ |
The sections below and each viewer's README give the details.
-
GitHub Flavored Markdown: headings, emphasis,
strikethrough, lists and task lists, quotes, tables with column alignment, footnotes, emoji shortcodes such as:wave:, and GitHub alerts (> [!NOTE],> [!TIP],> [!IMPORTANT],> [!WARNING],> [!CAUTION]). A link to a heading of the same text scrolls to it. -
Front matter, the YAML (
---) or TOML (+++) block at the top of a Hugo, Jekyll or Docusaurus post, is hidden by default. WithShowFrontMatterset inMarkdownOptions, both viewers andMarkdownHtmlshow it as one block: thetitlein the style of a level-one heading,date,authorandtagsin a line of small text under it, and the other fields in a list behind a More toggle (FrontMatterMoreLabeltranslates it), open in the HTML. Values are text, an address becomes a link only with an allowed scheme, and front matter that cannot be read shows as code. The block is not a heading of the text, so the table of contents and find pass over it.MarkdownFrontMatter.Readreads the fields without rendering, for a window or tab title, andToPagetitles a page with thetitlefield:var frontMatter = MarkdownFrontMatter.Read(markdown); window.Title = frontMatter.Title ?? fileName; var tags = frontMatter.GetField("tags")?.Items ?? [];
-
Code blocks show their language and a copy button, and code in common languages such as C#, JSON, SQL, XML, JavaScript and Python is highlighted. A host can add its own buttons next to Copy, such as "Insert at cursor" or "Run", which receive the block's code and language. Light and dark themes are both supported:
-
Mermaid diagrams: flowcharts, sequence, class, state and ER diagrams, Gantt and pie charts, and the other types Mermaider draws, with no script, in the viewer's text and link colors. A diagram with a syntax error, or a statement Mermaider does not read, shows as code.
-
Math written as on GitHub,
$…$in a line and$$…$$or a```mathblock on its own, also without a script. Dollar signs in prose, such as prices, stay text. -
The HTML README files use, such as
<div align="center">,<details>,<sup>,<kbd>and<img>, becomes part of the text; any other HTML is dropped, and scripts with their content. -
Safety: only links with an allowed scheme (by default
http,httpsandmailto) can be clicked, and only images from an allowed scheme (by defaulthttps) load. An application that shows untrusted text, such as a model's reply, can also list the hosts images may load from (AllowedImageHosts), so an image it writes is requested only from those hosts; a browser still follows their redirects. A host can add a scheme of its own and decide what such a link does. -
Streaming: the text can be set again as a reply arrives, and only the blocks it changes are rendered again. With
IsStreamingset, the syntax the reply leaves open, such as an unclosed emphasis or a link whose address is still arriving, shows as it will once the reply is complete, so markers do not show and then jump. The gallery's replay shows it. -
Reading: text is selected and copied across blocks as in a browser.
Headingslists the headings for a table of contents, andMarkdownReadershows one itself: a rail along the viewer's edge, with a list that slides out over the text or is pinned beside it and marks the section being read.ZoomImagesopens an image at full size to zoom and pan, and a table too wide for the viewer opens over the window with the button at its corner. -
Finding text: Ctrl+F (⌘F) opens a find bar in the Avalonia viewer, the browser's own find works in the Blazor one, and both have the same API for a host's own search box (
Findon Avalonia,FindAsyncon Blazor). -
Accessibility: screen readers hear headings with their level, links, lists, tables and alerts in both viewers, and Tab and Enter reach and follow links.
Each package's README shows how to use its viewer: Avalonia, Blazor.
MarkdownEditor, in Polhem.Markdown.Avalonia and in Polhem.Markdown.Blazor, edits Markdown as source, with a live
preview in MarkdownViewer beside it, not as rich text. The two editors color and edit a text the same way.
- Colours the source the way the viewer reads it: markers, headings, emphasis, inline code, links and their addresses, raw HTML and formulas, and fenced code with the viewer's highlighting.
- Formats and list keys:
ApplyFormat(ApplyFormatAsyncon Blazor) toggles bold, italic, strikethrough, inline code, links, images, headings, lists, task lists, quotes and code blocks, and inserts tables and horizontal rules, with Ctrl or Cmd and B, I, K or E for the inline ones.CycleHeading(CycleHeadingAsyncon Blazor) steps a line through heading levels 1 to 3 and back to plain text. Enter continues a list, and Tab and Shift+Tab move an item in and out; in a pipe table they move between the cells and line up the columns (FormatTable,FormatTableAsyncon Blazor, does it from a host's menu). A Markdown marker (*,_,`,~,[,() typed over a selection wraps it instead of replacing it, and an address pasted over a selection makes it a link. - A toolbar above the text, with a button for each format, the heading cycle, undo and redo. Its labels are
English unless the host gives its own;
ShowToolbar = falsehides it. It stays on one row: in a narrow editor the buttons that do not fit go into a menu at its end. - Keeps in step with the viewer: the editor reports the source at the top of its view and scrolls to a source offset; the viewer maps source offsets to positions and back, and a command-click asks for the source of what was clicked. The gallery wires the two together.
- Its links cannot be opened from the source: the viewer opens them after checking their scheme.
- On Avalonia it is built on AvaloniaEdit and works under any theme with no styles from the host. A host reads
and sets the selection (
SelectionStart,SelectionLength,SelectedText,Select,SelectionChanged) and replaces ranges from code, one range or several together, as one step to undo (Replace). Ctrl+F (⌘F) opens the viewer's find bar over the source, and Ctrl+H (⌥⌘F) adds a row to replace the current match or every match, with options for case, whole words and regular expressions; a host opens them from its own menu or finds and replaces from code. It draws the host's own marks over ranges (a background, an underline, a strikethrough, or a color for the text itself) that move with the edits, and tells where a range is on the screen (GetTextBounds,ViewChanged), for a popup next to the selection. It shows a replacement as a diff before it is made (PreviewReplace): accepting it leaves one step to undo and rejecting it none, while the user's edits elsewhere keep their own. - On Blazor the text is typed into a native textarea, so input methods and screen readers work as anywhere on the
page, under interactive server, WebAssembly and auto rendering. A host reads and sets the selection, replaces ranges
as one step to undo, marks ranges, finds where a range is on the screen, and previews a replacement, as on Avalonia,
with asynchronous methods (
SelectAsync,ReplaceAsync,AddMark,GetTextBoundsAsync,PreviewReplaceAsync). Its find bar works as the Avalonia editor's, with the same keys, options and matches (FindAsync,ReplaceAllMatchesAsync,OpenFindAsync), in place of the browser's own find, which does not search a textarea reliably. A host's own Edit menu cuts, copies, pastes and selects all (CutAsync,CopyAsync,PasteAsync,SelectAllAsync), and copying or cutting with nothing selected takes the caret's whole line, as on Avalonia.
Each package's README shows how to use its editor: Avalonia, Blazor.
MarkdownHtml, in Polhem.Markdown, writes a text as HTML from the same model and under the same safety policy as the
viewers, so a host can save a document as a web page, or print that page to PDF from the platform's web view.
// Only allowed schemes reach ImageContent, and by default that is https alone.
var options = new MarkdownOptions { AllowedImageSchemes = { "file" } };
var page = MarkdownHtml.ToPage(markdown, options, new MarkdownHtmlOptions
{
// Return the bytes of an image to embed it as a data: URI; null keeps it as a link.
ImageContent = source => source.IsFile
? new MarkdownImageContent("image/png", File.ReadAllBytes(source.LocalPath))
: null,
});ToPagewrites a standalone page with the viewers' look;ToFragmentwrites onedivto place in a page of the host's own, and that page includesMarkdownHtml.StyleSheet. UnlessMarkdownHtmlOptions.Titleis set, the page is titled by the front matter'stitle, or else by the first heading.- The markup is the Blazor viewer's: highlighted code, Mermaid diagrams as inline SVG and math as MathML, with no
script. The stylesheet uses the same
--pmd-*variables, so an exported page is themed the same way. - Images stay links unless the host returns their bytes; the package never reads a file or the network itself. The
host is asked only for images whose scheme is allowed, so a
fileimage needsfileinAllowedImageSchemes, and a relative source needsBaseUri.
When the images come from the web or another slow source, ToPageAsync and ToFragmentAsync take an asynchronous
reader instead of ImageContent. It is asked once for each allowed source, a few at a time, before the HTML is written:
var page = await MarkdownHtml.ToPageAsync(markdown, async (source, token) =>
{
using var response = await http.GetAsync(source, token);
return response.IsSuccessStatusCode && response.Content.Headers.ContentType?.MediaType is { } type
? new MarkdownImageContent(type, await response.Content.ReadAsByteArrayAsync(token))
: null;
}, options, cancellationToken: token);The Blazor package writes no PDF. A user who wants a copy prints the viewer from the browser, whose print dialog can also save it as PDF. The text stays searchable, the fonts and emoji are the browser's, it looks as the viewer does, and it needs no server, so it works in a WebAssembly-only app. Writing PDF bytes is left to the Avalonia package (#188).
polhem-markdown.css lays the viewer out for paper, for any print of a page with a viewer on it: the buttons on code
and tables are left out, code and tables wrap to the paper's width, and code blocks, diagrams, formulas, table rows and
images are not split across pages. MarkdownViewer.PrintAsync prints the viewer alone, without the rest of the page.
Whether to offer it is the host's choice.
A host can offer the HTML page as a download too, from MarkdownHtml.ToPageAsync and a few lines of script:
@using Polhem.Markdown
@using Polhem.Markdown.Blazor
@inject IJSRuntime JS
@inject HttpClient Http
<button @onclick="() => viewer.PrintAsync()">Print or save as PDF</button>
<button @onclick="DownloadAsync">Download HTML</button>
<MarkdownViewer @ref="viewer" Markdown="@markdown" />
@code {
private MarkdownViewer viewer = default!;
private string markdown = "# Notes";
private async Task DownloadAsync()
{
// Embed the images, so the page shows them offline.
var page = await MarkdownHtml.ToPageAsync(markdown, async (source, token) =>
{
using var response = await Http.GetAsync(source, token);
return response.IsSuccessStatusCode && response.Content.Headers.ContentType?.MediaType is { } type
? new MarkdownImageContent(type, await response.Content.ReadAsByteArrayAsync(token))
: null;
});
await JS.InvokeVoidAsync("saveText", "notes.html", "text/html", page);
}
}// In a script the host page loads: save a text as a file in the browser's downloads.
window.saveText = (name, type, text) => {
const url = URL.createObjectURL(new Blob([text], { type }));
const link = Object.assign(document.createElement("a"), { href: url, download: name });
link.click();
setTimeout(() => URL.revokeObjectURL(url));
};MarkdownPdf, in Polhem.Markdown.Avalonia, writes a text as a PDF that looks as the Avalonia viewer shows it. Skia
draws it, so its text can be searched and copied. The PDF embeds the glyphs it uses from the fonts the text is drawn
with; the package ships no fonts.
await using var file = File.Create(path);
await MarkdownPdf.WriteAsync(markdown, file, new MarkdownPdfOptions
{
Paper = MarkdownPdfPaper.Letter, // A4 by default
Title = "Release notes", // the first heading by default
CjkFontFamily = new FontFamily("PingFang TC, Microsoft JhengHei UI, Noto Sans CJK TC"),
ImageLoader = LoadImageAsync, // the viewer's own loader by default
});- Call it on the UI thread of a running application that shows a window or a view: a viewer of its own lays the text out there, out of sight, in the light theme.
- On paper, code blocks and tables wrap to the width instead of scrolling, and the copy buttons and table expanders are left out. A page ends between lines, table rows and blocks, and a heading near the bottom moves to the next page.
- Links to web and mail addresses can be clicked, and links within the text, such as
#links to a heading, go to the page it is on. - It waits until every image has loaded, failed or been held back, so a slow image is not left blank.
- Without an
ImageLoader, images are read as the viewer reads them, underAllowedImageSchemesandAllowedImageHosts(by defaulthttpsimages only). To read nothing, pass a loader that returnsnull; the images then show their alternative text. - Characters some CJK fonts give as Kangxi radicals in a PDF's text, such as 一, 人 and 心 in PingFang, are written as the ideographs, so searching the PDF finds them.
The Blazor package writes no PDF; the browser prints the viewer, as the section above shows.
samples/MarkdownGallery shows every kind of node on a Semi theme, light or dark, in a MarkdownReader with its table
of contents, with a replay that types the text in chunks as a streamed reply arrives. Images open at full size, and
Ctrl+F (⌘F) finds text. Its Edit switch puts the editor beside the viewer, scrolling together; there, Propose change
shows a change as a diff with marks and Accept and Reject buttons, and a code block's Insert into editor button puts
its code at the caret. Its Post switch shows a blog post whose front matter is shown at the top.
dotnet run --project samples/MarkdownGallery.Desktop
dotnet run --project samples/MarkdownGallery.Blazor
dotnet run --project samples/MarkdownGallery.WasmThe Blazor gallery shows the same text, so the two viewers can be compared side by side, with a find box that uses the
viewer's find API. Its Edit and Post switches work the same way, and a code block that names
its language has a Count lines button. MarkdownGallery.Blazor runs with interactive server rendering;
MarkdownGallery.Wasm runs the same page on standalone Blazor WebAssembly, in the browser with no server. Build CI
publishes it trimmed, so a change that breaks the Blazor package under trimming fails the build.
The iOS head is not in the solution, because it needs the iOS workload. On a Mac, build and start it on a simulator:
dotnet build samples/MarkdownGallery.iOS -c Release -p:RuntimeIdentifier=iossimulator-arm64
dotnet build samples/MarkdownGallery.iOS -c Release -t:Run -p:RuntimeIdentifier=iossimulator-arm64 -p:_DeviceName=":v2:udid=<simulator UDID>"If the build says the iOS workload needs another Xcode version, point DEVELOPER_DIR at that version for the build.
dotnet build Polhem.Markdown.slnx --configuration Release
dotnet test Polhem.Markdown.slnx --configuration Release --no-build





