litehtml

package module
v0.2.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Apr 6, 2026 License: LGPL-3.0 Imports: 6 Imported by: 0

README

litehtml-go

AI generated Go bindings for litehtml, a lightweight HTML/CSS rendering engine. litehtml parses HTML/CSS and performs layout, then calls back into your code to draw text, backgrounds, borders, and images. This package wraps that engine via cgo so you can drive it entirely from Go.

Requirements

  • Go 1.25+
  • A C/C++ toolchain (gcc / clang with C++17 support) No external shared libraries are needed -- the litehtml C++ source is vendored directly in the litehtml/ directory and compiled from source as part of the normal go build process through cgo.

Installation

go get github.com/andresbott/litehtml-go

That's it -- no git submodules or system libraries to install.

Quick start

The core workflow is:

  1. Implement the DocumentContainer interface (fonts, drawing, resources).
  2. Create a Document from an HTML string.
  3. Call Render to lay out at a given width.
  4. Call Draw to trigger your container's drawing callbacks.
package main

import (
    "fmt"
    litehtml "github.com/andresbott/litehtml-go"
)

func main() {
    container := NewMyContainer(800, 600) // your DocumentContainer impl

    doc, err := litehtml.NewDocument(
        "<html><body><h1>Hello!</h1></body></html>",
        container,
        "", // master CSS (empty = litehtml default)
        "", // user CSS
    )
    if err != nil {
        panic(err)
    }
    defer doc.Close()

    doc.Render(800)

    clip := litehtml.Position{X: 0, Y: 0, Width: 800, Height: 600}
    doc.Draw(0, 0, 0, &clip)

    fmt.Printf("Document size: %.0f x %.0f\n", doc.Width(), doc.Height())
}

API overview

Document
Method Description
NewDocument(html, container, masterCSS, userCSS) Parse HTML and return a *Document.
doc.Render(maxWidth) Perform layout. Returns the actual width used.
doc.Draw(hdc, x, y, clip) Trigger draw callbacks. Pass nil for clip to draw everything.
doc.Width() / doc.Height() Document dimensions after Render.
doc.OnMouseOver(...) Mouse move -- returns changed flag and redraw boxes.
doc.OnLButtonDown(...) / doc.OnLButtonUp(...) Mouse button events.
doc.OnMouseLeave() Mouse left the document area.
doc.Close() Free C++ resources. Safe to call multiple times. Also called by the finalizer.
MasterCSS() Returns litehtml's built-in default stylesheet.
DocumentContainer interface

You must implement all methods of DocumentContainer. The engine calls these during parsing, layout, and drawing. The full list:

Fonts and text

  • CreateFont(descr FontDescription) (uintptr, FontMetrics) -- create a font, return a handle and metrics.
  • DeleteFont(hFont uintptr) -- release a font handle.
  • TextWidth(text string, hFont uintptr) float32 -- measure text width.
  • DrawText(hdc uintptr, text string, hFont uintptr, color WebColor, pos Position) -- draw a text run.
  • TransformText(text string, tt TextTransform) string -- apply text-transform (uppercase, lowercase, etc.).
  • PtToPx(pt float32) float32 -- convert CSS points to pixels.
  • GetDefaultFontSize() float32 -- default font size in pixels (typically 16).
  • GetDefaultFontName() string -- default font family name.

Drawing

  • DrawSolidFill(hdc uintptr, layer BackgroundLayer, color WebColor) -- fill a background rectangle.
  • DrawBorders(hdc uintptr, borders Borders, drawPos Position, root bool) -- draw element borders.
  • DrawListMarker(hdc uintptr, marker ListMarker) -- draw a list bullet or number.
  • DrawImage(hdc uintptr, layer BackgroundLayer, url, baseURL string) -- draw a background/foreground image.
  • DrawLinearGradient(...) / DrawRadialGradient(...) / DrawConicGradient(...) -- draw CSS gradients.
  • SetClip(pos Position, bdrRadius BorderRadiuses) / DelClip() -- push/pop a clipping region.

Resources and navigation

  • LoadImage(src, baseurl string, redrawOnReady bool) -- start loading an image.
  • GetImageSize(src, baseurl string) Size -- return a previously loaded image's dimensions.
  • ImportCSS(url, baseurl string) (text, newBaseURL string) -- fetch an external stylesheet.
  • Link(href, rel, mediaType string) -- notification of a <link> element.

Environment

  • GetViewport() Position -- return the viewport rectangle.
  • GetMediaFeatures() MediaFeatures -- describe the display (size, color depth, resolution).
  • GetLanguage() (language, culture string) -- document language (e.g. "en", "en-US").

Events and UI

  • SetCaption(caption string) -- <title> content.
  • SetBaseURL(baseURL string) -- <base> href.
  • OnAnchorClick(url string) -- a link was clicked.
  • OnMouseEvent(event MouseEvent) -- mouse enter/leave an element.
  • SetCursor(cursor string) -- requested cursor style.
  • CreateElement(tagName string, attributes map[string]string) uintptr -- optionally create a custom element (return 0 to use default).

See litehtml_types.go for all supporting types (Position, WebColor, FontMetrics, Borders, BackgroundLayer, gradients, etc.).

Examples

Three working examples are included under examples/:

basic

Renders a simple HTML page to a PNG image using Go's bundled fonts (golang.org/x/image/font/gofont).

go run ./examples/basic
# writes output.png
rich

Renders a more complex page with headings, styled divs, lists, multiple font sizes, colors, borders, and an embedded generated image.

go run ./examples/rich
# writes output.png
dump

Prints every container callback invocation to stdout. Useful for understanding what litehtml does internally during parse, layout, and draw phases.

go run ./examples/dump

Development

Running tests
make test
Full verification (lint, tests, license check, benchmarks, coverage)
make verify

This requires:

Coverage

The coverage threshold is 70%. If you add new exported functions, add corresponding tests. Run the coverage report:

make cover-report

Architecture

litehtml-go/
  litehtml/          # litehtml C++ source (vendored)
  bridge.h           # flat C API over litehtml's C++ classes
  bridge.cpp         # C++ implementation of the bridge
  bridge_gumbo.c     # compiles litehtml's Gumbo HTML parser
  container.go       # Go <-> C callback trampolines, DocumentContainer interface
  litehtml.go        # Document type and cgo bindings
  litehtml_types.go  # Go types mirroring litehtml's C++ enums and structs
  litehtml_test.go   # tests
  examples/          # runnable examples

The binding works by:

  1. bridge.h / bridge.cpp expose litehtml's C++ API as plain C functions and a struct of callback function pointers (lh_container_callbacks).
  2. container.go registers Go DocumentContainer implementations in a handle map and provides //export trampoline functions that C calls back into.
  3. litehtml.go wraps the C document lifecycle (create, render, draw, destroy) in a Go-friendly Document type with a finalizer for safety.

License

This project provides Go bindings. The litehtml engine itself is licensed under its own terms (see litehtml/LICENSE).

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func MasterCSS

func MasterCSS() string

MasterCSS returns the default master CSS stylesheet built into litehtml.

Types

type BackgroundAttachment

type BackgroundAttachment int

BackgroundAttachment mirrors litehtml::background_attachment.

const (
	BackgroundAttachmentScroll BackgroundAttachment = iota
	BackgroundAttachmentFixed
)

type BackgroundLayer

type BackgroundLayer struct {
	BorderBox    Position
	BorderRadius BorderRadiuses
	ClipBox      Position
	OriginBox    Position
	Attachment   BackgroundAttachment
	Repeat       BackgroundRepeat
	IsRoot       bool
}

BackgroundLayer holds geometry for a background draw call.

type BackgroundRepeat

type BackgroundRepeat int

BackgroundRepeat mirrors litehtml::background_repeat.

const (
	BackgroundRepeatRepeat BackgroundRepeat = iota
	BackgroundRepeatRepeatX
	BackgroundRepeatRepeatY
	BackgroundRepeatNoRepeat
)

type Border

type Border struct {
	Width float32
	Style BorderStyle
	Color WebColor
}

Border describes one side of a border.

type BorderRadiuses

type BorderRadiuses struct {
	TopLeftX, TopLeftY         float32
	TopRightX, TopRightY       float32
	BottomRightX, BottomRightY float32
	BottomLeftX, BottomLeftY   float32
}

BorderRadiuses holds the 4-corner border radius values.

type BorderStyle

type BorderStyle int

BorderStyle mirrors litehtml::border_style.

const (
	BorderStyleNone BorderStyle = iota
	BorderStyleHidden
	BorderStyleDotted
	BorderStyleDashed
	BorderStyleSolid
	BorderStyleDouble
	BorderStyleGroove
	BorderStyleRidge
	BorderStyleInset
	BorderStyleOutset
)

type Borders

type Borders struct {
	Left, Top, Right, Bottom Border
	Radius                   BorderRadiuses
}

Borders holds all four border sides plus radiuses.

type ColorPoint

type ColorPoint struct {
	Offset float32
	Color  WebColor
}

ColorPoint is a single color stop in a gradient.

type ConicGradient

type ConicGradient struct {
	Position    PointF
	Angle       float32
	Radius      float32
	ColorPoints []ColorPoint
}

ConicGradient holds data for a conic gradient draw call.

type Document

type Document struct {
	// contains filtered or unexported fields
}

Document represents a parsed and renderable HTML document.

func NewDocument

func NewDocument(html string, container DocumentContainer, masterCSS, userCSS string) (*Document, error)

NewDocument parses an HTML string and creates a Document. The container provides callbacks for fonts, drawing, and resources. Pass empty strings for masterCSS/userCSS to use litehtml defaults.

func (*Document) Close

func (d *Document) Close()

Close releases the C++ resources. Safe to call multiple times.

func (*Document) Draw

func (d *Document) Draw(hdc uintptr, x, y float32, clip *Position)

Draw draws the document at position (x, y). Pass nil for clip to draw everything.

func (*Document) Height

func (d *Document) Height() float32

Height returns the document height after rendering.

func (*Document) OnLButtonDown

func (d *Document) OnLButtonDown(x, y, clientX, clientY float32) (bool, []Position)

OnLButtonDown handles a left mouse button press.

func (*Document) OnLButtonUp

func (d *Document) OnLButtonUp(x, y, clientX, clientY float32) (bool, []Position)

OnLButtonUp handles a left mouse button release.

func (*Document) OnMouseLeave

func (d *Document) OnMouseLeave() (bool, []Position)

OnMouseLeave handles the mouse leaving the document area.

func (*Document) OnMouseOver

func (d *Document) OnMouseOver(x, y, clientX, clientY float32) (bool, []Position)

OnMouseOver handles a mouse move event. Returns whether any elements changed and the list of boxes to redraw.

func (*Document) Render

func (d *Document) Render(maxWidth float32) float32

Render performs layout at the given maximum width. Returns the actual width used.

func (*Document) Width

func (d *Document) Width() float32

Width returns the document width after rendering.

type DocumentContainer

type DocumentContainer interface {
	CreateFont(descr FontDescription) (uintptr, FontMetrics)
	DeleteFont(hFont uintptr)
	TextWidth(text string, hFont uintptr) float32
	DrawText(hdc uintptr, text string, hFont uintptr, color WebColor, pos Position)
	PtToPx(pt float32) float32
	GetDefaultFontSize() float32
	GetDefaultFontName() string
	DrawListMarker(hdc uintptr, marker ListMarker)
	LoadImage(src, baseurl string, redrawOnReady bool)
	GetImageSize(src, baseurl string) Size
	DrawImage(hdc uintptr, layer BackgroundLayer, url, baseURL string)
	DrawSolidFill(hdc uintptr, layer BackgroundLayer, color WebColor)
	DrawLinearGradient(hdc uintptr, layer BackgroundLayer, gradient LinearGradient)
	DrawRadialGradient(hdc uintptr, layer BackgroundLayer, gradient RadialGradient)
	DrawConicGradient(hdc uintptr, layer BackgroundLayer, gradient ConicGradient)
	DrawBorders(hdc uintptr, borders Borders, drawPos Position, root bool)
	SetCaption(caption string)
	SetBaseURL(baseURL string)
	Link(href, rel, mediaType string)
	OnAnchorClick(url string)
	OnMouseEvent(event MouseEvent)
	SetCursor(cursor string)
	TransformText(text string, tt TextTransform) string
	ImportCSS(url, baseurl string) (text string, newBaseURL string)
	SetClip(pos Position, bdrRadius BorderRadiuses)
	DelClip()
	GetViewport() Position
	CreateElement(tagName string, attributes map[string]string) uintptr
	GetMediaFeatures() MediaFeatures
	GetLanguage() (language, culture string)
}

DocumentContainer is the callback interface that consumers implement to provide font, drawing, and resource loading services to litehtml.

type FontDescription

type FontDescription struct {
	Family              string
	Size                float32
	Style               FontStyle
	Weight              int
	DecorationLine      int
	DecorationThickness float32
	DecorationStyle     TextDecorationStyle
	DecorationColor     WebColor
	EmphasisStyle       string
	EmphasisColor       WebColor
	EmphasisPosition    int
}

FontDescription describes a font request from the layout engine.

type FontMetrics

type FontMetrics struct {
	FontSize   float32
	Height     float32
	Ascent     float32
	Descent    float32
	XHeight    float32
	ChWidth    float32
	DrawSpaces bool
	SubShift   float32
	SuperShift float32
}

FontMetrics holds font measurement data returned by CreateFont.

type FontStyle

type FontStyle int

FontStyle mirrors litehtml::font_style.

const (
	FontStyleNormal FontStyle = iota
	FontStyleItalic
)

type LinearGradient

type LinearGradient struct {
	Start, End  PointF
	ColorPoints []ColorPoint
}

LinearGradient holds data for a linear gradient draw call.

type ListMarker

type ListMarker struct {
	Image      string
	BaseURL    string
	MarkerType ListStyleType
	Color      WebColor
	Pos        Position
	Index      int
	Font       uintptr
}

ListMarker holds data for a list marker draw call.

type ListStyleType

type ListStyleType int

ListStyleType mirrors litehtml::list_style_type.

const (
	ListStyleTypeNone ListStyleType = iota
	ListStyleTypeCircle
	ListStyleTypeDisc
	ListStyleTypeSquare
	ListStyleTypeArmenian
	ListStyleTypeCjkIdeographic
	ListStyleTypeDecimal
	ListStyleTypeDecimalLeadingZero
	ListStyleTypeGeorgian
	ListStyleTypeHebrew
	ListStyleTypeHiragana
	ListStyleTypeHiraganaIroha
	ListStyleTypeKatakana
	ListStyleTypeKatakanaIroha
	ListStyleTypeLowerAlpha
	ListStyleTypeLowerGreek
	ListStyleTypeLowerLatin
	ListStyleTypeLowerRoman
	ListStyleTypeUpperAlpha
	ListStyleTypeUpperLatin
	ListStyleTypeUpperRoman
)

type MediaFeatures

type MediaFeatures struct {
	Type         MediaType
	Width        float32
	Height       float32
	DeviceWidth  float32
	DeviceHeight float32
	Color        int
	ColorIndex   int
	Monochrome   int
	Resolution   float32
}

MediaFeatures describes the media environment.

type MediaType

type MediaType int

MediaType mirrors litehtml::media_type.

const (
	MediaTypeUnknown MediaType = iota
	MediaTypeAll
	MediaTypePrint
	MediaTypeScreen
)

type MouseEvent

type MouseEvent int

MouseEvent mirrors litehtml::mouse_event.

const (
	MouseEventEnter MouseEvent = iota
	MouseEventLeave
)

type PointF

type PointF struct {
	X, Y float32
}

PointF represents a 2D floating-point coordinate.

type Position

type Position struct {
	X, Y, Width, Height float32
}

Position represents a rectangle with x, y, width, height.

type RadialGradient

type RadialGradient struct {
	Position    PointF
	Radius      PointF
	ColorPoints []ColorPoint
}

RadialGradient holds data for a radial gradient draw call.

type Size

type Size struct {
	Width, Height float32
}

Size represents a width/height pair.

type TextDecorationStyle

type TextDecorationStyle int

TextDecorationStyle mirrors litehtml::text_decoration_style.

const (
	TextDecorationStyleSolid TextDecorationStyle = iota
	TextDecorationStyleDouble
	TextDecorationStyleDotted
	TextDecorationStyleDashed
	TextDecorationStyleWavy
)

type TextTransform

type TextTransform int

TextTransform mirrors litehtml::text_transform.

const (
	TextTransformNone TextTransform = iota
	TextTransformCapitalize
	TextTransformUppercase
	TextTransformLowercase
)

type WebColor

type WebColor struct {
	Red, Green, Blue, Alpha uint8
}

WebColor represents an RGBA color.

Directories

Path Synopsis
examples
basic command
Example: render HTML to a PNG image using litehtml-go
Example: render HTML to a PNG image using litehtml-go
dump command
Example: dump all litehtml container callbacks
Example: dump all litehtml container callbacks
rich command
Example: render a rich HTML page to PNG using litehtml-go
Example: render a rich HTML page to PNG using litehtml-go

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL