Skip to content

Repository files navigation

htmltotext

UnDotNet.HtmlToText

HTML to Text converter for DotNet

Ported from node-html-to-text

Advanced converter that parses HTML and returns beautiful text.

Features

  • Inline and block-level tags.
  • Tables with colspans and rowspans.
  • Links with both text and href.
  • Word wrapping.
  • Unicode support.
  • Plenty of customization options.

Installation

Add NuGet package UnDotNet.HtmlToText to your project

Basic Usage

usingUnDotNet.HtmlToText;vartext=newHtmlToTextConverter().Convert(html);

With Options

usingUnDotNet.HtmlToText;varoptions=newHtmlToTextOptions{Wordwrap:120,// ...};vartext=newHtmlToTextConverter().Convert(html,options);

Example

General Options

OptionDefaultDescription
BaseElementsDescribes which parts of the input document have to be converted and present in the output text, and in what order.
BaseElements.Selectors['body']Elements matching any of provided selectors will be processed and included in the output text, with all inner content.
Refer to Supported selectors section below.
BaseElements.OrderBy'selectors''selectors' - arrange base elements in the same order as BaseElements.Selectors array;
'occurrence' - arrange base elements in the order they are found in the input document.
BaseElements.ReturnDomByDefaulttrueConvert the entire document if none of provided selectors match.
EncodeCharacters{}A dictionary with characters that should be replaced in the output text and corresponding escape sequences.
Formatters{}An object with custom formatting functions for specific elements (see Override formatting section below).
LimitsDescribes how to limit the output text in case of large HTML documents.
Limits.Ellipsis'...'A string to insert in place of skipped content.
Limits.MaxBaseElementsundefinedStop looking for more base elements after reaching this amount. Unlimited if undefined.
Limits.MaxChildNodesundefinedMaximum number of child nodes of a single node to be added to the output. Unlimited if undefined.
Limits.MaxDepthundefinedStop looking for nodes to add to the output below this depth in the DOM tree. Unlimited if undefined.
Limits.MaxInputLength16_777_216If the input string is longer than this value - it will be truncated and a message will be sent to stderr. Ellipsis is not used in this case. Unlimited if undefined.
LongWordSplitDescribes how to wrap long words.
LongWordSplit.WrapCharacters[]An array containing the characters that may be wrapped on. Checked in order, search stops once line length requirement can be met.
LongWordSplit.ForceWrapOnLimitfalseBreak long words at the line length limit in case no better wrap opportunities found.
PreserveNewlinesfalseBy default, any newlines \n from the input HTML are collapsed into space as any other HTML whitespace characters. If true, these newlines will be preserved in the output. This is only useful when input HTML carries some plain text formatting instead of proper tags.
Selectors[]Describes how different HTML elements should be formatted. See Selectors section below.
WhitespaceCharacters' \t\r\n\f\u200b'A string of characters that are recognized as HTML whitespace. Default value uses the set of characters defined in HTML4 standard. (It includes Zero-width space compared to living standard.)
Wordwrap80After how many chars a line break should follow.
Set to false to disable word-wrapping.
Predefined formatters

Following selectors have a formatter specified as a part of the default configuration. Everything can be overridden, but you don't have to repeat the format or options that you don't want to override. (But keep in mind this is only true for the same selector. There is no connection between different selectors.)

SelectorDefault formatNotes
*inlineUniversal selector.
aanchor
articleblock
asideblock
blockquoteblockquote
brlineBreak
divblock
footerblock
formblock
h1heading
h2heading
h3heading
h4heading
h5heading
h6heading
headerblock
hrhorizontalLine
imgimage
mainblock
navblock
olorderedList
pparagraph
prepre
tabletableEquivalent to block. Use dataTable instead for tabular data.
ulunorderedList
wbrwbr

More formatters also available for use:

FormatDescription
dataTableFor visually-accurate tables. Note that this might be not search-friendly (output text will look like gibberish to a machine when there is any wrapped cell contents) and also better to be avoided for tables used as a page layout tool.
skipSkips the given tag with it's contents without printing anything.
blockStringInsert a block with the given string literal (formatOptions.string) instead of the tag.
blockTagRender an element as HTML block tag, convert it's contents to text.
blockHtmlRender an element with all it's children as HTML block.
inlineStringInsert the given string literal (formatOptions.string) inline instead of the tag.
inlineSurroundRender inline element wrapped with given strings (formatOptions.prefix and formatOptions.suffix).
inlineTagRender an element as inline HTML tag, convert it's contents to text.
inlineHtmlRender an element with all it's children as inline HTML.
Format options

Following options are available for built-in formatters.

OptionDefaultApplies toDescription
LeadingLineBreaks1, 2 or 3all block-level formattersNumber of line breaks to separate previous block from this one.
Note that N+1 line breaks are needed to make N empty lines.
TrailingLineBreaks1 or 2all block-level formattersNumber of line breaks to separate this block from the next one.
Note that N+1 line breaks are needed to make N empty lines.
BaseUrlnullanchor, imageServer host for link href attributes and image src attributes relative to the root (the ones that start with /).
For example, with baseUrl = 'http://asdf.com' and <a href='/dir/subdir'>...</a> the link in the text will be http://asdf.com/dir/subdir.
LinkBrackets['[', ']']anchor, imageSurround links with these brackets.
Set to false or ['', ''] to disable.
PathRewriteundefinedanchor, imageA function to rewrite link href attributes and image src attributes. Optional second argument is the metadata object.
Applied before baseUrl.
HideLinkHrefIfSameAsTextfalseanchorBy default links are translated in the following way:
<a href='link'>text</a> => becomes => text [link].
If this option is set to true and link and text are the same, [link] will be omitted and only text will be present.
IgnoreHreffalseanchorIgnore all links. Only process internal text of anchor tags.
NoAnchorUrltrueanchorIgnore anchor links (where href='#...').
ItemPrefix' * 'unorderedListString prefix for each list item.
UppercasetrueheadingBy default, headings (<h1>, <h2>, etc) are uppercased.
Set this to false to leave headings as they are.
LengthundefinedhorizontalLineLength of the line. If undefined then wordwrap value is used. Falls back to 40 if that's also disabled.
TrimEmptyLinestrueblockquoteTrim empty lines from blockquote.
While empty lines should be preserved in HTML, space-saving behavior is chosen as default for convenience.
UppercaseHeaderCellstruedataTableBy default, heading cells (<th>) are uppercased.
Set this to false to leave heading cells as they are.
MaxColumnWidth60dataTableData table cell content will be wrapped to fit this width instead of global wordwrap limit.
Set this to undefined in order to fall back to wordwrap limit.
ColSpacing3dataTableNumber of spaces between data table columns.
RowSpacing0dataTableNumber of empty lines between data table rows.
StringLiteral''blockString, inlineStringA string to be inserted in place of a tag.
Prefix''inlineSurroundString prefix to be inserted before inline tag contents.
Suffix''inlineSurroundString suffix to be inserted after inline tag contents.

About

HTML to Text converter for DotNet

Topics

Resources

Stars

10 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages