html2text

repository·master·Indexed 20 days ago

https://github.com/jaytaylor/html2text

A 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.

Tokens
717
Snippets
5
Records
5
Agent score
20%

What's inside html2text

  1. Convert HTML to text using the Library API

    master

    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)
    }
  2. Convert HTML from a reader using html2text.FromReader

    master

    In 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)
    }
  3. Use html2text as a CLI tool via Stdin

    master

    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