html2text
html2text is a Rust crate which converts HTML to plain text.
It makes use of the Servo project's HTML parser, html5ever, using the DOM to generate text (which can optionally include annotations for some features such as hyperlinks).
The project aims to do a reasonable job of rendering reasonable HTML in a terminal or other places where HTML needs to be converted to text (for example the text/plain fallback in HTML e-mails).
With features (see below) some CSS/colour support is available.
Examples
The simple functions like from_read()
return formatted text (in various
formats including plain text).
use from_read;
let html = b"
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>";
assert_eq!;
A lower level API gives a bit more control. This give the same result (except for returning errors as Result instead of panicking):
use config;
let html = b"
<ul>
<li>Item one</li>
<li>Item two</li>
<li>Item three</li>
</ul>";
assert_eq!;
A couple of simple demonstration programs are included as examples:
html2text
The simplest example uses from_read
to convert HTML on stdin into plain
text:
html2term
A very simple example of using the rich interface (from_read_rich
) for a
slightly interactive console HTML viewer is provided as html2term
.
Note that this example takes the HTML file as a parameter so that it can read keys from stdin.
Cargo Features
Feature | Description |
---|---|
css | Limited handling of CSS, adding Coloured nodes to the render tree. |
html_trace | Add verbose internal logging (not recommended) |
html_trace_bt | Add backtraces to the verbose internal logging |
CSS support
When the css
feature is enabled, some simple CSS handling is done.
- The contents of <style> elements are parsed and some colour rules are extracted
- Some simplified selector matching is done: currently
<span class="foo">
with CSS rules similar to.foo { color:#123456; }
. This will addColoured(...)
nodes to the render tree when matching.
The CSS handling is expected to improve in future (PRs welcome), but not to a full- blown browser style system, which would be overkill for terminal output.
There are two ways to make use of the colours:
- Use
from_read_rich()
or one of its variants. One of the annotations you may get back isColour(..)
. - Use
from_read_coloured()
. This is similar tofrom_read()
, but you provide a function to add terminal colours (or other styling) based on the same RichAnnotations. See examples/html2text.rs for an example using termion.