html

package
v0.3.1 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: Apache-2.0 Imports: 30 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package html reads reflowable documents: EPUB, MOBI and AZW3, CHM, FB2, DOCX, PPTX, XLSX and plain text.

doc, err := html.Open("book.epub")
defer doc.Close()

p, err := doc.Page(0)
img, err := p.ImageDPI(150)

A document is a spine of parts rather than pages. Document.Spine lists them, Document.Read hands over the markup, Document.StylePart parses one and computes the style of every element, and Document.Layout reflows the lot onto pages of a size. Document.Text and Document.Markdown read the parts rather than the pages and need no layout.

A page is laid out in CSS pixels, 96 to the inch; Page.Bounds returns points, as a PDF page does. Page.Run draws through gfx.Device.

A face comes from the document when an @font-face rule brings one, from the machine when it has one for a family the document names, and from the base fourteen otherwise.

Pages may be rendered from several goroutines at once, but not while Document.Layout is running.

Index

Constants

View Source
const DefaultFontSize = 16

DefaultFontSize is a medium font, what every relative size works out from.

Variables

View Source
var (
	// ErrInvalid means the file is not a book, or is damaged past recovery.
	ErrInvalid = errors.New("html: invalid document")
	// ErrUnsupported is a well formed file this package cannot read.
	ErrUnsupported = errors.New("html: unsupported document")
	// ErrNotFound means the document has no part by that path.
	ErrNotFound = errors.New("html: no such part")
)

Errors returned by this package.

Functions

func Attr

func Attr(n *Node, name string) string

Attr returns an element's attribute by name, and empty when it has none.

func NodeMarkdown added in v0.2.0

func NodeMarkdown(n *Node) string

NodeMarkdown writes one tree as Markdown.

func NodeText

func NodeText(n *Node) string

NodeText returns the text of a subtree, a newline after each block element.

func Resolve

func Resolve(base, ref string) string

Resolve turns a link inside the part at base into the path of another, with any fragment cut.

func Walk

func Walk(n *Node, fn func(*Node) bool)

Walk calls fn for every node depth first, not descending where fn returns false.

Types

type Border

type Border struct {
	Width float32
	Style BorderStyle
	Color Color
}

Border is one edge of a box.

func (Border) Thickness

func (b Border) Thickness() float32

Thickness is how much room the edge takes, none when nothing is drawn.

type BorderStyle

type BorderStyle uint8

BorderStyle is how an edge of a box is drawn.

const (
	BorderNone BorderStyle = iota
	BorderSolid
	BorderDashed
	BorderDotted
	BorderDouble
	// BorderHidden draws nothing, and in a collapsed table it takes the
	// edge away from every other border that meets it.
	BorderHidden
)

The border styles. The three dimensional ones are drawn solid.

type Clear

type Clear uint8

Clear is which floats a box must come below.

const (
	ClearNone Clear = iota
	ClearLeft
	ClearRight
	ClearBoth
)

The clear values.

type Color

type Color struct{ R, G, B, A uint8 }

Color is a color as CSS writes one.

type Corner

type Corner struct {
	X, Y Length
}

Corner is the two radii one corner of a border box is rounded by.

func (Corner) Zero

func (c Corner) Zero() bool

Zero reports a corner that is not rounded at all.

type Declaration

type Declaration struct {
	Name      string
	Important bool
	// contains filtered or unexported fields
}

Declaration is one property and its value.

type Decoration

type Decoration uint8

Decoration is a set of text decoration lines.

const (
	Underline Decoration = 1 << iota
	Overline
	LineThrough
)

The decoration lines.

type Direction

type Direction uint8

Direction is which way the characters of a box run, CSS 2.1 9.10.

const (
	DirLTR Direction = iota
	DirRTL
)

The two directions.

func (Direction) RTL

func (d Direction) RTL() bool

RTL reports a direction that runs right to left.

type Display

type Display uint8

Display is the box an element generates.

const (
	DisplayInline Display = iota
	DisplayBlock
	DisplayInlineBlock
	DisplayListItem
	DisplayTable
	DisplayTableRowGroup
	DisplayTableRow
	DisplayTableCell
	DisplayTableCaption
	DisplayNone
)

The display values the engine reads. Everything it does not, a table or a flex container, becomes a block.

type Document

type Document struct {
	// ImageCacheBytes bounds the decoded pictures kept while pages render: zero
	// is the default, negative is none. It is set before Layout.
	ImageCacheBytes int
	// PixelLimit bounds the pixel area a rendered page may allocate. Zero is
	// the default of 2^28 and a negative number is no limit at all.
	PixelLimit int
	// contains filtered or unexported fields
}

Document is an open book.

func Load

func Load(b []byte) (*Document, error)

Load reads a book from a buffer.

func NewReader

func NewReader(r io.ReaderAt, size int64) (*Document, error)

NewReader reads a book from a reader.

func NewStream added in v0.2.0

func NewStream(r io.Reader) (*Document, error)

NewStream reads a document from a stream, all of it into memory first. An untrusted source should be bounded with io.LimitReader.

func Open

func Open(name string) (*Document, error)

Open reads the named file, deciding from its contents what it is.

func (*Document) Close

func (d *Document) Close() error

Close releases what the document holds.

func (*Document) Kind

func (d *Document) Kind() Kind

Kind returns the container the document came out of.

func (*Document) Layout

func (d *Document) Layout(o *LayoutOptions) (int, error)

Layout lays the book out onto pages of a size and returns how many it makes. NumPages and Page call it with nil options when a caller has not, so it is only needed to choose the page; calling it again with another size lays the book out afresh. Pages may be rendered from several goroutines at once, but not while another Layout is running.

func (*Document) Manifest

func (d *Document) Manifest() []Item

Manifest is every part the book carries, nil for a container listing none.

func (*Document) Markdown added in v0.2.0

func (d *Document) Markdown() (string, error)

Markdown returns the document as Markdown, with inline HTML for what Markdown cannot express.

func (*Document) Metadata

func (d *Document) Metadata() Metadata

Metadata returns what the book says about itself.

func (*Document) NumPages

func (d *Document) NumPages() int

NumPages is how many pages the last Layout made. A book that has not been laid out is laid out first, at the size it asks for or the default one.

func (*Document) Outline

func (d *Document) Outline() []Outline

Outline returns the table of contents, built from the headings of the parts when the book carries none.

func (*Document) Page

func (d *Document) Page(i int) (*Page, error)

Page returns one page of the book, laying it out when nothing else has.

func (*Document) PageOf added in v0.2.5

func (d *Document) PageOf(path, fragment string) int

PageOf is the page a place in the book is on: the part path names and, in it, the element fragment names, counting from zero. A fragment the part does not have leads to the part's first page, and a part the book does not lay out to -1.

func (*Document) ParsePart

func (d *Document) ParsePart(path string) (*Node, error)

ParsePart reads a part by path.

func (*Document) Read

func (d *Document) Read(p string) ([]byte, error)

Read returns the bytes of one part.

func (*Document) Spine

func (d *Document) Spine() []Item

Spine returns the parts to read, in order.

func (*Document) StylePart

func (d *Document) StylePart(path string, media Media) (*Node, Styles, error)

StylePart parses one part of a book and styles every element in it.

func (*Document) Stylesheets

func (d *Document) Stylesheets(path string, root *Node) []*Stylesheet

Stylesheets returns the sheets that style one part, in cascade order: the user agent sheet, then what the part links or carries and what those import.

func (*Document) Text

func (d *Document) Text() (string, error)

Text returns the text of every part of the spine in order, a blank line between blocks.

type Float

type Float uint8

Float is the side a box is taken out of the flow to.

const (
	FloatNone Float = iota
	FloatLeft
	FloatRight
)

The float values.

type FontFace

type FontFace struct {
	Family string
	// Src are the parts the rule names, in order, resolved against the sheet.
	Src    []string
	Weight int
	Italic bool
}

FontFace is an @font-face rule: a family the book brings and where its program is.

type FontStyle

type FontStyle uint8

FontStyle is the slant of a face.

const (
	StyleNormal FontStyle = iota
	StyleItalic
	StyleOblique
)

The slants.

type Import

type Import struct {
	// Path is the reference as written, before Resolve.
	Path  string
	Media MediaList
}

Import is what an @import rule asks for.

type Item

type Item struct {
	// Path is the part's name in the container.
	Path string
	// Type is the media type the container declares.
	Type string
	// ID is the manifest identifier.
	ID string
	// Properties are the manifest properties of an EPUB item.
	Properties []string
	// Linear is false for a spine item the package marks as auxiliary.
	Linear bool
}

Item is one part of a book: a chapter, a stylesheet, an image.

func (Item) IsChapter

func (i Item) IsChapter() bool

IsChapter reports whether the item is a part with text in it.

type Kind

type Kind int

Kind is the container a document came out of.

const (
	KindEPUB Kind = iota
	KindMOBI
	KindText
	KindCHM
	KindDOCX
	KindPPTX
	KindXLSX
	KindFB2
	KindHTML
)

The containers.

func (Kind) String

func (k Kind) String() string

String returns the name of the container.

type LayoutOptions

type LayoutOptions struct {
	// Width and Height are the page in CSS pixels, 96 to the inch. Zero is
	// the size the document asks for, and 800 by 1200 for one that asks for
	// none, which is a page of about eight inches by twelve.
	Width, Height float32
	// Margin is what is left blank around the text, in CSS pixels.
	Margin float32
	// FontSize is the size the reader is set to, which every relative length
	// resolves against. Zero is 16.
	FontSize float32
	// UserSheet is a stylesheet over the user agent's and under the book's own.
	UserSheet *Stylesheet
}

LayoutOptions is the page a book is laid out onto.

type Length

type Length struct {
	Value float32
	Unit  Unit
}

Length is a computed length.

func Px

func Px(v float32) Length

Px is a length in CSS pixels.

func (Length) Auto

func (l Length) Auto() bool

Auto reports the absence of a length.

func (Length) Resolve

func (l Length) Resolve(against float32) float32

Resolve returns the length in CSS pixels against a containing block of the given size, and zero for a length there is none of.

type Link struct {
	// Rect is the area the link covers, in page space at 72 dots per inch.
	Rect raster.Rect
	// URI is where a link out of the document points, and "" for one inside.
	URI string
	// Path is the part a link inside the document leads to, Fragment the anchor.
	Path, Fragment string
}

Link is a link on a page: the area it covers, and where following it goes.

type ListStyle

type ListStyle uint8

ListStyle is the marker a list item carries.

const (
	ListNone ListStyle = iota
	ListDisc
	ListCircle
	ListSquare
	ListDecimal
	ListLowerAlpha
	ListUpperAlpha
	ListLowerRoman
	ListUpperRoman
)

The markers.

type Media

type Media struct {
	Width, Height float32
	FontSize      float32
}

Media is the viewport in CSS pixels and the font size relative lengths in a query resolve against.

type MediaList

type MediaList []MediaQuery

MediaList is the comma separated query list of a media rule. It matches when any query does, and always when empty.

func (MediaList) Match

func (l MediaList) Match(m Media) bool

Match reports any query of the list matching, true for an empty list.

type MediaQuery

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

MediaQuery is one query of a media list.

type Metadata

type Metadata struct {
	Title       string
	Author      string
	Language    string
	Identifier  string
	Publisher   string
	Description string
	Subjects    []string
	// Created and Modified are zero when the book gives no date.
	Created  time.Time
	Modified time.Time
}

Metadata is a book's title, authors and the rest of its description.

type Node

type Node = xhtml.Node

Node is a parsed element of a part, in x/net/html's tree.

func Parse

func Parse(b []byte) (*Node, error)

Parse reads one part of a book into a DOM.

type Orientation

type Orientation uint8

Orientation is how a character is turned in vertical text.

const (
	OrientMixed Orientation = iota
	OrientUpright
	OrientSideways
)

The text orientations.

type Origin

type Origin uint8

Origin is where a stylesheet came from, the first thing the cascade sorts.

const (
	OriginUA Origin = iota
	OriginUser
	OriginAuthor
)

The origins, in the order they lose to one another.

type Outline

type Outline struct {
	Title string
	// Path is the part the entry leads to, and Fragment the anchor inside it.
	Path     string
	Fragment string
	Children []Outline
}

Outline is one entry of a book's table of contents.

type Page

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

Page is one page of a laid out book.

func (*Page) Bounds

func (p *Page) Bounds() raster.Rect

Bounds returns the page in points.

func (*Page) DeviceBounds

func (p *Page) DeviceBounds(dpi float64) raster.Rect

DeviceBounds is the page at a resolution, in whole pixels.

func (*Page) HTML added in v0.2.0

func (p *Page) HTML() (string, error)

HTML returns the page as HTML.

func (*Page) Image

func (p *Page) Image() (*image.RGBA, error)

Image renders the page at the resolution its own content is in. A page with no text whose largest image covers a quarter of it is cropped to that image.

func (*Page) ImageBands added in v0.3.0

func (p *Page) ImageBands(dpi float64, rows int, fn func(*image.RGBA) error) error

ImageBands renders the page as ImageDPI does, rows at a time, and hands each band to fn in order from the top. A band's Rect is its place in the image ImageDPI returns, valid only until fn returns, and a dpi of zero or less is the resolution and the crop of Image. The pixel limit bounds a band, not the page, and rows of zero or less is as many as it allows. An error from fn stops the render and is returned.

func (*Page) ImageDPI

func (p *Page) ImageDPI(dpi float64) (*image.RGBA, error)

ImageDPI renders the page at a resolution.

func (p *Page) Links() []Link

Links returns the links on the page, one for every run of text an anchor covers, in the order they are laid out.

func (*Page) Matrix

func (p *Page) Matrix(dpi float64) raster.Matrix

Matrix returns the transform from page space to a device at a resolution.

func (*Page) NaturalDPI added in v0.2.8

func (p *Page) NaturalDPI() float64

NaturalDPI is the resolution Image renders the page at.

func (*Page) Number

func (p *Page) Number() int

Number is where the page sits in the book, counting from zero.

func (*Page) Path

func (p *Page) Path() string

Path is the part of the spine the page came out of.

func (*Page) Run

func (p *Page) Run(dev gfx.Device, ctm raster.Matrix) error

Run draws the page through a device, from page space in points to the device.

func (*Page) SVG added in v0.2.0

func (p *Page) SVG() (string, error)

SVG returns the page as SVG.

func (*Page) StructuredText added in v0.2.0

func (p *Page) StructuredText() (*TextPage, error)

StructuredText returns the page's text with the box every character covers.

func (*Page) StructuredTextOptions added in v0.2.0

func (p *Page) StructuredTextOptions(o *TextOptions) (*TextPage, error)

StructuredTextOptions is StructuredText with options.

func (*Page) Text

func (p *Page) Text() (string, error)

Text returns what the page says, a line of the text for each line box.

func (*Page) WriteHTML added in v0.2.0

func (p *Page) WriteHTML(w io.Writer) error

WriteHTML writes the page as HTML: the text where it was laid out, in the face and colour it was drawn with. Read gives the markup it was written in.

func (*Page) WriteSVG added in v0.2.0

func (p *Page) WriteSVG(w io.Writer) error

WriteSVG writes the page as SVG, with text, borders and pictures as such.

type PageBreak

type PageBreak uint8

PageBreak is what a page break property asks for.

const (
	BreakAuto PageBreak = iota
	BreakAlways
	BreakAvoid
)

The page break values.

type Position

type Position uint8

Position is how a box is placed against the flow.

const (
	PosStatic Position = iota
	PosRelative
	PosAbsolute
)

The position values. A fixed box is placed like an absolute one: a book has no viewport to fix it to.

type PseudoElement

type PseudoElement uint8

PseudoElement names a ::before or ::after box.

const (
	PseudoNone PseudoElement = iota
	PseudoBefore
	PseudoAfter
)

The pseudo-elements a rule may style.

type Quad added in v0.2.0

type Quad = gfx.Quad

Quad is the four corners a character covers.

type Repeat

type Repeat uint8

Repeat is how the picture behind a box is tiled.

const (
	RepeatBoth Repeat = iota
	RepeatX
	RepeatY
	RepeatNone
)

The background repeats.

type Rule

type Rule struct {
	Selectors []Selector
	Decls     []Declaration
	// Media are the conditions of the @media rules around the rule; all match.
	Media []MediaList
	// contains filtered or unexported fields
}

Rule is a selector list and the declarations it applies.

type Selector

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

Selector is one complex selector, its compounds held right to left, subject first.

func (Selector) Match

func (s Selector) Match(n *Node) bool

Match reports whether an element matches the selector; one naming a pseudo-element matches none.

func (Selector) Pseudo

func (s Selector) Pseudo() PseudoElement

Pseudo is the pseudo-element the selector styles, if it names one.

func (Selector) Spec

func (s Selector) Spec() Specificity

Spec returns the specificity of the selector.

type Specificity

type Specificity uint32

Specificity is the CSS 2.1 (a, b, c) triple packed into one comparable number.

type Style

type Style struct {
	Display Display

	MarginTop, MarginRight, MarginBottom, MarginLeft     Length
	PaddingTop, PaddingRight, PaddingBottom, PaddingLeft Length
	BorderTop, BorderRight, BorderBottom, BorderLeft     Border
	Width, Height                                        Length
	MinWidth, MaxWidth, MinHeight, MaxHeight             Length

	Position                    Position
	Top, Right, Bottom, LeftPos Length

	FontFamily []string
	FontSize   float32
	FontStyle  FontStyle
	FontWeight int
	LineHeight Length
	// SmallCaps draws the lower case of a run as capitals of a smaller size.
	SmallCaps bool

	Color      Color
	Background Color
	// BackgroundImage is the picture painted over the colour, with where in
	// the box it sits, how big it is drawn and how it is tiled.
	BackgroundImage          string
	BackgroundRepeat         Repeat
	BackgroundX, BackgroundY Length
	BackgroundW, BackgroundH Length

	TextAlign     TextAlign
	TextIndent    Length
	TextTransform TextTransform
	LetterSpacing float32
	Decoration    Decoration
	WhiteSpace    WhiteSpace
	VerticalAlign VerticalAlign
	// VerticalShift is how far AlignLength raises the box, in line heights.
	VerticalShift Length
	ListStyle     ListStyle

	Float Float
	Clear Clear

	// Writing is the direction the lines run in, Orient how a character is
	// turned when they run down the page, and Direction which way the
	// characters of a line run.
	Writing   Writing
	Orient    Orientation
	Direction Direction

	// Collapse is whether the cells of a table share the borders between
	// them, and Spacing the gap between them when they do not.
	Collapse           bool
	SpacingX, SpacingY Length

	// Radius is the corner radii of the border box, clockwise from top left.
	Radius [4]Corner

	// Content is the text a rule generates before or after an element, and
	// HasContent whether it generates a box there at all.
	Content    string
	HasContent bool

	BreakBefore, BreakAfter PageBreak
}

Style is the computed value of every property the engine reads. Lengths are in CSS pixels except where a percentage survived the cascade.

type Styles

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

Styles is the computed style of every element of a tree and of its ::before and ::after boxes.

func Cascade

func Cascade(root *Node, media Media, sheets ...*Stylesheet) Styles

Cascade computes the style of every element of a tree. The sheets are given in reading order, the user agent sheet first.

func (Styles) Has

func (s Styles) Has(n *Node) bool

Has reports whether an element has a style of its own.

func (Styles) Of

func (s Styles) Of(n *Node) *Style

Of is the style of an element, or of the nearest element above a text node.

func (Styles) Pseudo

func (s Styles) Pseudo(n *Node, p PseudoElement) *Style

Pseudo returns the style of an element's ::before or ::after box, or nil when it has none.

type Stylesheet

type Stylesheet struct {
	Rules   []Rule
	Imports []Import
	// Faces are the fonts the sheet's @font-face rules bring with them.
	Faces  []FontFace
	Origin Origin
	// Errors are the selectors and declarations the sheet dropped.
	Errors []error
}

Stylesheet is a parsed sheet.

func ParseCSS

func ParseCSS(b []byte, origin Origin) *Stylesheet

ParseCSS reads a stylesheet. It never fails; anything it cannot read goes in Errors.

func UserAgent

func UserAgent() *Stylesheet

UserAgent is the user agent stylesheet, cut to the properties engine reads.

func (*Stylesheet) Coverage

func (s *Stylesheet) Coverage() (read, ignored int)

Coverage returns how many of a sheet's declarations the engine reads and how many it has no use for.

type TextAlign

type TextAlign uint8

TextAlign is how a line box sits in its containing block.

const (
	AlignStart TextAlign = iota
	AlignLeft
	AlignRight
	AlignCenter
	AlignJustify
	AlignEnd
)

The alignments. Start is the initial value and End its opposite, which are the two edges of the direction the text runs in.

func (TextAlign) Resolve

func (a TextAlign) Resolve(d Direction) TextAlign

Resolve turns the two direction-dependent alignments into two that are not.

type TextBlock added in v0.2.0

type TextBlock = gfx.TextBlock

TextBlock is a paragraph of text, or one image.

type TextChar added in v0.2.0

type TextChar = gfx.TextChar

TextChar is one character where it was drawn.

type TextLine added in v0.2.0

type TextLine = gfx.TextLine

TextLine is a run of characters along one baseline.

type TextOptions added in v0.2.0

type TextOptions = gfx.TextOptions

TextOptions configure what StructuredTextOptions collects.

type TextPage added in v0.2.0

type TextPage = gfx.TextPage

TextPage is a page's text: blocks of lines of characters.

type TextTransform

type TextTransform uint8

TextTransform is the case a run of text is drawn in.

const (
	TransformNone TextTransform = iota
	TransformUpper
	TransformLower
	TransformCapitalize
)

The text transforms.

type Unit

type Unit uint8

Unit is what a Length is measured in once the cascade has computed it.

const (
	UnitAuto Unit = iota
	UnitPx
	UnitPercent
	UnitScale
)

The units a computed length is left in. Everything absolute is folded into CSS pixels and a percentage is left standing.

type VerticalAlign

type VerticalAlign uint8

VerticalAlign is the baseline an inline box sits on.

const (
	AlignBaseline VerticalAlign = iota
	AlignSub
	AlignSuper
	AlignTop
	AlignMiddle
	AlignBottom
	AlignTextTop
	AlignTextBottom
	AlignLength
)

The vertical alignments.

type WhiteSpace

type WhiteSpace uint8

WhiteSpace is how the white space of the source is collapsed.

const (
	WhiteNormal WhiteSpace = iota
	WhitePre
	WhiteNowrap
	WhitePreWrap
	WhitePreLine
)

The white space values.

type Writing

type Writing uint8

Writing is the direction the lines of a box run in.

const (
	WritingHorizontal Writing = iota
	WritingVerticalRL
	WritingVerticalLR
)

The writing modes.

func (Writing) Vertical

func (w Writing) Vertical() bool

Vertical reports a mode whose lines run down the page.

Jump to

Keyboard shortcuts

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