Install the html2text package
masterTo use html2text as a dependency in your Go project, download it using go get:
go get jaytaylor.com/html2textNote: This package requires Go 1.x or newer.
repository·master·Indexed 20 days ago
https://github.com/jaytaylor/html2textA Go package and CLI tool for converting HTML into markdown-flavored plaintext, designed for creating readable text fallbacks for HTML emails. It provides a library API with functions like FromString and FromReader, as well as a command-line interface that reads from standard input.
To use html2text as a dependency in your Go project, download it using go get:
go get jaytaylor.com/html2textNote: This package requires Go 1.x or newer.
You can convert HTML strings to markdown-flavored plaintext using the html2text.FromString function. This function accepts the input HTML string and an html2text.Options struct to configure the output behavior.
Commonly used options include:
PrettyTables: A boolean that, when set to true, renders HTML tables with ASCII-style borders for better readability.package main
import (
"fmt"
"jaytaylor.com/html2text"
)
func main() {
inputHTML := `<html><body><h1>Hello</h1></body></html>` // Example input
// Convert HTML to text with PrettyTables enabled
text, err := html2text.FromString(inputHTML, html2text.Options{PrettyTables: true})
if err != nil {
panic(err)
}
fmt.Println(text)
}The package can be used as a CLI tool. You can pipe HTML content into the html2text command to receive the plaintext output in your terminal.
echo '<div>hi</div>' | html2textIn Go applications, you can convert HTML to text by calling html2text.FromReader. This function accepts an io.Reader containing the HTML content and an html2text.Options struct to configure the conversion process. It returns the converted text as a string and an error if the conversion fails.
import (
"bufio"
"fmt"
"os"
"jaytaylor.com/html2text"
)
func main() {
reader := bufio.NewReader(os.Stdin)
opts := html2text.Options{}
out, err := html2text.FromReader(reader, opts)
if err != nil {
fmt.Fprintf(os.Stderr, "error: %s\n", err)
os.Exit(1)
}
fmt.Println(out)
}The html2text command-line tool reads HTML content from standard input (os.Stdin) and prints the converted markdown-flavored text to standard output. If an error occurs during conversion, the error message is printed to os.Stderr and the process exits with code 1.
# Example usage (piping HTML to the tool)
echo "<h1>Hello</h1>" | html2text