translate

package
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: MIT Imports: 44 Imported by: ? modules, 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 translate converts a parsed HTML DOM into a slice of Paper rows.

Index

Constants

This section is empty.

Variables

View Source
var ErrImageResolverRefused = errors.New(
	"html: default resolver refuses local file reads; configure html.WithImageBaseDir or translate.WithImageResolver",
)

ErrImageResolverRefused is returned by the default resolver when asked to load a non-data: URI without an explicit html.WithImageBaseDir or the lower-level translate.WithImageResolver.

View Source
var ErrStylesheetResolverRefused = errors.New("html: default stylesheet resolver refuses local file reads; configure WithStylesheetBaseDir")

ErrStylesheetResolverRefused is returned by the default resolver when asked to load a non-data: URI without an explicit WithStylesheetBaseDir.

View Source
var ErrURLPolicyDenied = errors.New("html: URL fetch blocked by URLPolicy")

ErrURLPolicyDenied wraps a URLPolicy rejection so callers can distinguish intentional policy blocks from network or filesystem failures.

Functions

func NewBlankPageRow added in v0.2.2

func NewBlankPageRow(control core.PageControl) core.Row

NewBlankPageRow creates a zero-content row that inserts one physical blank page. The supplied control determines whether that blank page receives repeated footer/page-number decorations.

func NewPageBreakRow

func NewPageBreakRow() core.Row

NewPageBreakRow creates an exported pageBreakRow for use in tests and the translate pipeline.

func NewPageControlRow added in v0.2.2

func NewPageControlRow(control core.PageControl) core.Row

NewPageControlRow creates a zero-content row that changes how the current physical page is committed, for example suppressing footer/page-number reservation on a title or interstitial page.

func Translate

func Translate(ctx context.Context, doc *dom.Document, opts ...Option) ([]core.Row, error)

Translate walks the styled DOM and emits Paper rows. It observes ctx at cheap phase and recursive traversal boundaries. With WithStrictAssets the partially-translated rows are returned together with the joined asset errors, so callers can decide whether to use the degraded output.

Types

type AssetError added in v0.2.2

type AssetError struct {
	Category string
	Ref      string
	Err      error
}

AssetError indicates a document-referenced asset failed to load while translating HTML with strict asset checking enabled.

func NewAssetError added in v0.2.2

func NewAssetError(category, ref string, err error) *AssetError

NewAssetError builds an AssetError for a reference that could not be loaded. category names the kind of asset, and ref is the value that failed.

func (*AssetError) Error added in v0.2.2

func (e *AssetError) Error() string

func (*AssetError) Unwrap added in v0.2.2

func (e *AssetError) Unwrap() error

type Document added in v0.2.0

type Document struct {
	Rows []core.Row
	// HeaderRows and FooterRows hold the translated content of the FIRST
	// top-level <header> / <footer> element (direct children of <body>).
	// They are meant for Paper's RegisterHeader/RegisterFooter so the bands
	// repeat on every page. Subsequent top-level header/footer elements and
	// nested ones render inline as part of Rows.
	HeaderRows []core.Row
	FooterRows []core.Row
	// Page holds size/margin options from a plain `@page { ... }` rule, or
	// nil when the document has none (or none that parsed to a usable value).
	Page *PageOptions
}

Document is the full result of translating an HTML document: the content rows plus document-level options parsed from `@page` rules.

func FromDOM added in v0.2.2

func FromDOM(ctx context.Context, doc *dom.Document, opts ...Option) (*Document, error)

FromDOM walks the styled DOM and returns the full Document: content rows plus @page options. It observes ctx at cheap phase and recursive traversal boundaries. Unlike Translate, the first top-level <header>/<footer> elements are extracted into HeaderRows/FooterRows instead of rendering inline.

type ImageResolver

type ImageResolver func(src string) (data []byte, ext string, err error)

ImageResolver loads image bytes for a given <img src="…"> value. It returns the raw bytes and a hint extension ("png", "jpg", "svg", etc.). When err is non-nil the caller falls back to the <img>'s alt text.

type LimitError added in v0.2.2

type LimitError struct {
	Kind  LimitKind
	Limit int
	Err   error
}

LimitError indicates HTML translation stopped because a configured resource ceiling was crossed.

func (*LimitError) Error added in v0.2.2

func (e *LimitError) Error() string

func (*LimitError) Unwrap added in v0.2.2

func (e *LimitError) Unwrap() error

type LimitKind added in v0.2.2

type LimitKind int

LimitKind identifies which HTML translation resource ceiling was exceeded.

const (
	// LimitElements reports that the configured element/node budget was exceeded.
	LimitElements LimitKind = iota
	// LimitDepth reports that the configured DOM nesting depth was exceeded.
	LimitDepth
	// LimitStyleRules reports that the configured stylesheet rule budget was exceeded.
	LimitStyleRules
)

func (LimitKind) String added in v0.2.2

func (k LimitKind) String() string

type Option

type Option func(*translator)

Option configures translator behaviour.

func WithContentWidth

func WithContentWidth(mm float64) Option

WithContentWidth sets the content width in mm, used for gap-to-col approximation.

func WithFallbackFontPath added in v0.2.2

func WithFallbackFontPath(path string) Option

WithFallbackFontPath registers a font (local path, data: URI, or http(s) URL with WithRemoteAssets) that is loaded on demand when the document contains text outside the WinAnsi (cp1252) repertoire, so such text renders instead of degrading.

func WithGridSize

func WithGridSize(n int) Option

WithGridSize overrides the default 12-column grid size used for flex quantization.

func WithHTTPClient added in v0.2.2

func WithHTTPClient(client *http.Client) Option

WithHTTPClient overrides http.DefaultClient for remote asset fetches.

func WithImageBaseDir

func WithImageBaseDir(dir string) Option

WithImageBaseDir scopes the default resolver to a single directory. Local file reads outside this directory are refused (path-traversal safe).

func WithImageResolver

func WithImageResolver(fn ImageResolver) Option

WithImageResolver lets callers plug in a custom <img src=…> loader.

func WithLimits

func WithLimits(l htmllimits.Limits) Option

WithLimits configures resource limits for untrusted HTML translation.

func WithOutlineFromHeadings added in v0.2.0

func WithOutlineFromHeadings() Option

WithOutlineFromHeadings marks h1-h6 headings with a props.Outline so they appear in the PDF document outline (h1 = level 0 ... h6 = level 5).

func WithRemoteAssets added in v0.2.2

func WithRemoteAssets() Option

WithRemoteAssets enables http(s) fetching for document-referenced assets (stylesheet links and the fallback font). Off by default: remote URLs are refused so untrusted HTML cannot trigger network access.

func WithStrictAssets added in v0.2.2

func WithStrictAssets() Option

WithStrictAssets makes asset load failures (stylesheet links, @font-face sources, images, background images) surface as errors from Translate. The partially-translated rows are still returned alongside the joined asset errors. Without this option failures warn-and-continue.

func WithStylesheetBaseDir

func WithStylesheetBaseDir(dir string) Option

WithStylesheetBaseDir scopes the default stylesheet resolver to a single directory. Local-file reads outside this directory are refused.

func WithURLPolicy added in v0.2.2

func WithURLPolicy(policy URLPolicy) Option

WithURLPolicy registers a callback that can veto individual URLs before any remote fetch. Only consulted when remote fetching is enabled.

func WithUnsupportedHandler

func WithUnsupportedHandler(fn func(thing, value string)) Option

WithUnsupportedHandler registers a callback for unsupported tags/props.

type PageOptions added in v0.2.0

type PageOptions struct {
	// PageSize is a normalized lowercase named size ("a4", "letter", ...);
	// empty when explicit Width/Height are set or only orientation was given.
	PageSize string
	// Width and Height are explicit page dimensions in mm; 0 when unset.
	Width  float64
	Height float64
	// Landscape reports the `landscape` keyword.
	Landscape bool
	// Margins in mm; -1 means unset (keep the document default).
	MarginLeft   float64
	MarginTop    float64
	MarginRight  float64
	MarginBottom float64
}

PageOptions captures the supported subset of the CSS `@page` rule: `size` (named size, explicit dimensions, landscape/portrait keyword) and `margin` (shorthand or per-side).

type ParseError added in v0.2.2

type ParseError struct {
	Err error
}

ParseError indicates the input HTML could not be parsed into a document.

func (*ParseError) Error added in v0.2.2

func (e *ParseError) Error() string

func (*ParseError) Unwrap added in v0.2.2

func (e *ParseError) Unwrap() error

type StylesheetResolver

type StylesheetResolver func(href string) ([]byte, error)

StylesheetResolver loads CSS text for a given <link href="…"> value. Returns the raw bytes (UTF-8 CSS text) and any error.

type URLPolicy added in v0.2.2

type URLPolicy func(rawURL string) error

URLPolicy vets a URL before any remote fetch. Returning a non-nil error blocks the fetch; the error is wrapped in ErrURLPolicyDenied.

Jump to

Keyboard shortcuts

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