UNPKG

18.9 kBMarkdownView Raw
1# html-to-text
2
3[![lint status](https://github.com/html-to-text/node-html-to-text/workflows/lint/badge.svg)](https://github.com/html-to-text/node-html-to-text/actions/workflows/lint.yml)
4[![test status](https://github.com/html-to-text/node-html-to-text/workflows/test/badge.svg)](https://github.com/html-to-text/node-html-to-text/actions/workflows/test.yml)
5[![Test Coverage](https://codeclimate.com/github/html-to-text/node-html-to-text/badges/coverage.svg)](https://codeclimate.com/github/html-to-text/node-html-to-text/coverage)
6[![License: MIT](https://img.shields.io/badge/license-MIT-green.svg)](https://github.com/html-to-text/node-html-to-text/blob/master/LICENSE-MIT)
7[![npm](https://img.shields.io/npm/v/html-to-text?logo=npm)](https://www.npmjs.com/package/html-to-text)
8[![npm](https://img.shields.io/npm/dw/html-to-text?color=informational&logo=npm)](https://www.npmjs.com/package/html-to-text)
9
10Advanced converter that parses HTML and returns beautiful text.
11
12## Features
13
14* Inline and block-level tags.
15* Tables with colspans and rowspans.
16* Links with both text and href.
17* Word wrapping.
18* Unicode support.
19* Plenty of customization options.
20
21## Changelog
22
23Available here: [CHANGELOG.md](https://github.com/html-to-text/node-html-to-text/blob/master/CHANGELOG.md)
24
25Version 6 contains a ton of changes, so it worth to take a look.
26
27Version 7 contains an important change for custom formatters.
28
29Version 8 brings the selectors support to greatly increase the flexibility but that also changes some things introduced in version 6. Base element(s) selection also got important changes.
30
31## Installation
32
33```
34npm install html-to-text
35```
36
37## Usage
38
39Convert a single document:
40
41```js
42const { convert } = require('html-to-text');
43// There is also an alias to `convert` called `htmlToText`.
44
45const html = '<h1>Hello World</h1>';
46const text = convert(html, {
47 wordwrap: 130
48});
49console.log(text); // Hello World
50```
51
52Configure `html-to-text` once for batch processing:
53
54```js
55const { compile } = require('html-to-text');
56
57const convert = compile({
58 wordwrap: 130
59});
60
61const htmls = [
62 '<h1>Hello World!</h1>',
63 '<h1>こんにちは世界!</h1>',
64 '<h1>Привет, мир!</h1>'
65];
66const texts = htmls.map(convert);
67console.log(texts.join('\n'));
68// Hello World!
69// こんにちは世界!
70// Привет, мир!
71```
72
73### Options
74
75#### General options
76
77Option | Default | Description
78----------------------- | ------------ | -----------
79`baseElements` | | Describes which parts of the input document have to be converted and present in the output text, and in what order.
80`baseElements.selectors` | `['body']` | Elements matching any of provided selectors will be processed and included in the output text, with all inner content.<br/>Refer to [Supported selectors](#supported-selectors) section below.
81`baseElements.orderBy` | `'selectors'` | `'selectors'` - arrange base elements in the same order as `baseElements.selectors` array;<br/>`'occurrence'` - arrange base elements in the order they are found in the input document.
82`baseElements.returnDomByDefault` | `true` | Convert the entire document if none of provided selectors match.
83`decodeOptions` | `{ isAttributeValue: false, strict: false }` | Text decoding options given to `he.decode`. For more information see the [he](https://github.com/mathiasbynens/he) module.
84`formatters` | `{}` | An object with custom formatting functions for specific elements (see [Override formatting](#override-formatting) section below).
85`limits` | | Describes how to limit the output text in case of large HTML documents.
86`limits.ellipsis` | `'...'` | A string to insert in place of skipped content.
87`limits.maxBaseElements` | `undefined` | Stop looking for more base elements after reaching this amount. Unlimited if undefined.
88`limits.maxChildNodes` | `undefined` | Maximum number of child nodes of a single node to be added to the output. Unlimited if undefined.
89`limits.maxDepth` | `undefined` | Stop looking for nodes to add to the output below this depth in the DOM tree. Unlimited if undefined.
90`limits.maxInputLength` | `16_777_216` | If 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.
91`longWordSplit` | | Describes how to wrap long words.
92`longWordSplit.wrapCharacters` | `[]` | An array containing the characters that may be wrapped on. Checked in order, search stops once line length requirement can be met.
93`longWordSplit.forceWrapOnLimit` | `false` | Break long words at the line length limit in case no better wrap opportunities found.
94`preserveNewlines` | `false` | By 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.
95`selectors` | `[]` | Describes how different HTML elements should be formatted. See [Selectors](#selectors) section below.
96`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](https://www.w3.org/TR/html4/struct/text.html#h-9.1). (It includes Zero-width space compared to [living standard](https://infra.spec.whatwg.org#ascii-whitespace).)
97`wordwrap` | `80` | After how many chars a line break should follow.<br/>Set to `null` or `false` to disable word-wrapping.
98
99#### Deprecated or removed options
100
101Old&nbsp;option | Depr. | Rem. | Instead&nbsp;use
102-------------------------- | --- | ----- | -----------------
103`baseElement` | 8.0 | | `baseElements: { selectors: [ 'body' ] }`
104`format` | | 6.0 | The way formatters are written has changed completely. New formatters have to be added to the `formatters` option, old ones can not be reused without rewrite. See [new instructions](#override-formatting) below.
105`hideLinkHrefIfSameAsText` | 6.0 | *9.0* | `selectors: [ { selector: 'a', options: { hideLinkHrefIfSameAsText: true } } ]`
106`ignoreHref` | 6.0 | *9.0* | `selectors: [ { selector: 'a', options: { ignoreHref: true } } ]`
107`ignoreImage` | 6.0 | *9.0* | `selectors: [ { selector: 'img', format: 'skip' } ]`
108`linkHrefBaseUrl` | 6.0 | *9.0* | `selectors: [`<br/>`{ selector: 'a', options: { baseUrl: 'https://example.com' } },`<br/>`{ selector: 'img', options: { baseUrl: 'https://example.com' } }`<br/>`]`
109`noAnchorUrl` | 6.0 | *9.0* | `selectors: [ { selector: 'a', options: { noAnchorUrl: true } } ]`
110`noLinkBrackets` | 6.0 | *9.0* | `selectors: [ { selector: 'a', options: { linkBrackets: false } } ]`
111`returnDomByDefault` | 8.0 | | `baseElements: { returnDomByDefault: true }`
112`singleNewLineParagraphs` | 6.0 | *9.0* | `selectors: [`<br/>`{ selector: 'p', options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } },`<br/>`{ selector: 'pre', options: { leadingLineBreaks: 1, trailingLineBreaks: 1 } }`<br/>`]`
113`tables` | 8.0 | | `selectors: [ { selector: 'table.class#id', format: 'dataTable' } ]`
114`tags` | 8.0 | | See [Selectors](#selectors) section below.
115`unorderedListItemPrefix` | 6.0 | *9.0* | `selectors: [ { selector: 'ul', options: { itemPrefix: ' * ' } } ]`
116`uppercaseHeadings` | 6.0 | *9.0* | `selectors: [`<br/>`{ selector: 'h1', options: { uppercase: false } },`<br/>`...`<br/>`{ selector: 'table', options: { uppercaseHeaderCells: false } }`<br/>`]`
117
118Other things deprecated:
119
120* `fromString` method;
121* positional arguments in `BlockTextBuilder` methods (in case you have written some custom formatters for version 6.0).
122
123#### Selectors
124
125Some example:
126
127```javascript
128const { convert } = require('html-to-text');
129
130const html = '<a href="/page.html">Page</a><a href="!#" class="button">Action</a>';
131const text = convert(html, {
132 selectors: [
133 { selector: 'a', options: { baseUrl: 'https://example.com' } },
134 { selector: 'a.button', format: 'skip' }
135 ]
136});
137console.log(text); // Page [https://example.com/page.html]
138```
139
140Selectors array is our loose approximation of a stylesheet.
141
142* highest [specificity](https://www.w3.org/TR/selectors/#specificity) selector is used when there are multiple matches;
143* the last selector is used when there are multiple matches of equal specificity;
144* all entries with the same selector value are merged (recursively) at the compile stage, in such way so the last defined properties a kept and the relative order of unique selectors is kept;
145* user-defined entries are appended after [predefined entries](#predefined-formatters);
146* Every unique selector must have `format` value specified (at least once);
147* unlike in CSS, values from different matched selectors are NOT merged at the convert stage. Single best match is used instead (that is the last one of those with highest specificity).
148
149To achieve the best performance when checking each DOM element against provided selectors, they are compiled into a decision tree. But it is also important how you choose selectors. For example, `div#id` is much better than `#id` - the former will only check divs for the id while the latter has to check every element in the DOM.
150
151##### Supported selectors
152
153`html-to-text` relies on [parseley](https://github.com/mxxii/parseley) and [selderee](https://github.com/mxxii/selderee) packages for selectors support.
154
155Following selectors can be used in any combinations:
156
157* `*` - universal selector;
158* `div` - tag name;
159* `.foo` - class name;
160* `#bar` - id;
161* `[baz]` - attribute presence;
162* `[baz=buzz]` - attribute value (with any operators and also quotes and case sensitivity modifiers);
163* `+` and `>` combinators (other combinators are not supported).
164
165You can match `<p style="...; display:INLINE; ...">...</p>` with `p[style*="display:inline"i]` for example.
166
167##### Predefined formatters
168
169Following 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.)
170
171Selector | Default&nbsp;format | Notes
172------------- | ------------------- | -----
173`*` | `inline` | Universal selector.
174`a` | `anchor` |
175`article` | `block` |
176`aside` | `block` |
177`blockquote` | `blockquote` |
178`br` | `lineBreak` |
179`div` | `block` |
180`footer` | `block` |
181`form` | `block` |
182`h1` | `heading` |
183`h2` | `heading` |
184`h3` | `heading` |
185`h4` | `heading` |
186`h5` | `heading` |
187`h6` | `heading` |
188`header` | `block` |
189`hr` | `horizontalLine` |
190`img` | `image` |
191`main` | `block` |
192`nav` | `block` |
193`ol` | `orderedList` |
194`p` | `paragraph` |
195`pre` | `pre` |
196`table` | `table` | Equivalent to `block`. Use `dataTable` instead for tabular data.
197`ul` | `unorderedList` |
198`wbr` | `wbr` |
199
200More formatters also available for use:
201
202* `dataTable` - for 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;
203* `skip` - as the name implies it skips the given tag with it's contents without printing anything.
204
205##### Format options
206
207Following options are available for built-in formatters.
208
209Option | Default | Applies&nbsp;to | Description
210------------------- | ----------- | ------------------ | -----------
211`leadingLineBreaks` | `1`, `2` or `3` | all block-level formatters | Number of line breaks to separate previous block from this one.<br/>Note that N+1 line breaks are needed to make N empty lines.
212`trailingLineBreaks` | `1` or `2` | all block-level formatters | Number of line breaks to separate this block from the next one.<br/>Note that N+1 line breaks are needed to make N empty lines.
213`baseUrl` | `null` | `anchor`, `image` | Server host for link `href` attributes and image `src` attributes relative to the root (the ones that start with `/`).<br/>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`.<br/>Keep in mind that `baseUrl` should not end with a `/`.
214`linkBrackets` | `['[', ']']` | `anchor`, `image` | Surround links with these brackets.<br/>Set to `false` or `['', '']` to disable.
215`hideLinkHrefIfSameAsText` | `false` | `anchor` | By default links are translated in the following way:<br/>`<a href='link'>text</a>` => becomes => `text [link]`.<br/>If this option is set to `true` and `link` and `text` are the same, `[link]` will be omitted and only `text` will be present.
216`ignoreHref` | `false` | `anchor` | Ignore all links. Only process internal text of anchor tags.
217`noAnchorUrl` | `true` | `anchor` | Ignore anchor links (where `href='#...'`).
218`itemPrefix` | `' * '` | `unorderedList` | String prefix for each list item.
219`uppercase` | `true` | `heading` | By default, headings (`<h1>`, `<h2>`, etc) are uppercased.<br/>Set this to `false` to leave headings as they are.
220`length` | `undefined` | `horizontalLine` | Length of the line. If undefined then `wordwrap` value is used. Falls back to 40 if that's also disabled.
221`trimEmptyLines` | `true` | `blockquote` | Trim empty lines from blockquote.<br/>While empty lines should be preserved in HTML, space-saving behavior is chosen as default for convenience.
222`uppercaseHeaderCells` | `true` | `dataTable` | By default, heading cells (`<th>`) are uppercased.<br/>Set this to `false` to leave heading cells as they are.
223`maxColumnWidth` | `60` | `dataTable` | Data table cell content will be wrapped to fit this width instead of global `wordwrap` limit.<br/>Set this to `undefined` in order to fall back to `wordwrap` limit.
224`colSpacing` | `3` | `dataTable` | Number of spaces between data table columns.
225`rowSpacing` | `0` | `dataTable` | Number of empty lines between data table rows.
226
227##### Deprecated format options
228
229Old option | Applies&nbsp;to | Depr. | Rem. | Instead use
230------------------- | ------------------ | ----- | ---- | ---------------------
231`noLinkBrackets` | `anchor` | 8.1 | | `linkBrackets: false`
232
233### Override formatting
234
235This is significantly changed in version 6.
236
237`formatters` option is an object that holds formatting functions. They can be assigned to format different elements in the `selectors` array.
238
239Each formatter is a function of four arguments that returns nothing. Arguments are:
240
241* `elem` - the HTML element to be processed by this formatter;
242* `walk` - recursive function to process the children of this element. Called as `walk(elem.children, builder)`;
243* `builder` - [BlockTextBuilder](https://github.com/html-to-text/node-html-to-text/blob/master/lib/block-text-builder.js) object. Manipulate this object state to build the output text;
244* `formatOptions` - options that are specified for a tag, along with this formatter (Note: if you need general html-to-text [options](#general-options) - they are accessible via `builder.options`).
245
246Custom formatter example:
247
248```javascript
249const { convert } = require('html-to-text');
250
251const html = '<foo>Hello World</foo>';
252const text = convert(html, {
253 formatters: {
254 // Create a formatter.
255 'fooBlockFormatter': function (elem, walk, builder, formatOptions) {
256 builder.openBlock({ leadingLineBreaks: formatOptions.leadingLineBreaks || 1 });
257 walk(elem.children, builder);
258 builder.addInline('!');
259 builder.closeBlock({ trailingLineBreaks: formatOptions.trailingLineBreaks || 1 });
260 }
261 },
262 selectors: [
263 // Assign it to `foo` tags.
264 {
265 selector: 'foo',
266 format: 'fooBlockFormatter',
267 options: { leadingLineBreaks: 1, trailingLineBreaks: 1 }
268 }
269 ]
270});
271console.log(text); // Hello World!
272```
273
274Refer to [built-in formatters](https://github.com/html-to-text/node-html-to-text/blob/master/lib/formatter.js) for more examples. The easiest way to write your own is to pick an existing one and customize.
275
276Refer to [BlockTextBuilder](https://github.com/html-to-text/node-html-to-text/blob/master/lib/block-text-builder.js) for available functions and arguments.
277
278Note: `BlockTextBuilder` got some important [changes](https://github.com/html-to-text/node-html-to-text/commit/f50f10f54cf814efb2f7633d9d377ba7eadeaf1e) in the version 7. Positional arguments are deprecated and formatters written for the version 6 have to be updated accordingly in order to keep working after next major update.
279
280## Command Line Interface
281
282It is possible to use html-to-text as command line interface. This allows an easy validation of your generated text and the integration in other systems that does not run on node.js.
283
284`html-to-text` uses `stdin` and `stdout` for data in and output. So you can use `html-to-text` the following way:
285
286```
287cat example/test.html | html-to-text > test.txt
288```
289
290There also all options available as described above. You can use them like this:
291
292```
293cat example/test.html | html-to-text --tables=#invoice,.address --wordwrap=100 > test.txt
294```
295
296The `tables` option has to be declared as comma separated list without whitespaces.
297
298## Example
299
300* Input text: [test.html](https://github.com/html-to-text/node-html-to-text/blob/master/test/test.html)
301* Output text: [test.txt](https://github.com/html-to-text/node-html-to-text/blob/master/test/test.txt)
302
303## Contributors
304
305* [@mlegenhausen](https://github.com/mlegenhausen) - creator;
306* [@KillyMXI](https://github.com/KillyMXI) - maintainer since 2020;
307* Everyone else who [added something](https://github.com/html-to-text/node-html-to-text/graphs/contributors) to the tool or helped us shaping it via [issues](https://github.com/html-to-text/node-html-to-text/issues) and [PRs](https://github.com/html-to-text/node-html-to-text/pulls).
308
309## License
310
311[MIT License](https://github.com/html-to-text/node-html-to-text/blob/master/LICENSE-MIT)