Documentation
¶
Overview ¶
Package html converts HTML+CSS markup into layout elements that the github.com/carlos7ags/folio/layout package can render to PDF.
The converter parses an HTML string (via golang.org/x/net/html), resolves inline and <style> CSS, and produces a tree of layout.Element values — Paragraphs, Divs, Tables, Lists, Images, and so on — ready to be fed to the layout engine.
Supported HTML Elements ¶
Block: div, p, section, article, main, header, footer, nav, aside, blockquote, pre, figure, figcaption, h1–h6, hr, dl/dt/dd, fieldset, legend, details, summary.
Inline: span, em, strong, b, i, u, s, del, mark, small, sub, sup, code, a, br, abbr, cite, dfn, kbd, q, samp, var.
Lists: ul, ol, li (nested, ordered/unordered).
Tables: table, thead, tbody, tfoot, tr, td, th, caption, colgroup, col.
Media: img (JPEG, PNG, WebP, GIF, SVG, data URIs), svg (inline).
Forms: input, button, select, textarea, label (visual only, not interactive).
Supported CSS Properties ¶
Text: font-family, font-size, font-weight, font-style, color, text-align, text-align-last, text-decoration (underline, line-through), text-decoration-color, text-decoration-style, text-transform, text-indent, text-shadow, text-overflow, letter-spacing, word-spacing, word-break, hyphens, white-space, line-height.
Box model: margin (shorthand + individual sides, auto for centering), padding (shorthand + individual), border (width, style, color per side), border-radius (uniform + per-corner), border-collapse, border-spacing, box-sizing, width, height, min-width, max-width, min-height, max-height.
Background: background-color, background-image (url, linear-gradient, radial-gradient, repeating variants), background-size, background-position, background-repeat.
Layout: display (block, inline, flex, grid, table, none), float, clear, position (static, relative, absolute), top/left/right/bottom, z-index, overflow, visibility, opacity.
Flexbox: flex-direction, flex-wrap, justify-content, align-items, align-self, align-content, flex-grow, flex-shrink, flex-basis, gap.
Grid: grid-template-columns, grid-template-rows, grid-template-areas, grid-column-start/end, grid-row-start/end, grid-auto-flow, grid-auto-rows, row-gap, column-gap, gap.
Multi-column: column-count, column-width, column-gap, column-rule (width, style, color).
Lists: list-style-type, ::marker (color, font-size).
Visual effects: box-shadow (multiple), outline (width, style, color, offset), transform (rotate, scale, translate, skew, matrix), transform-origin, object-fit, object-position.
Paged media: @page (size, margins, :first/:left/:right), margin boxes (@top-center, @bottom-left, etc.) with counter(page)/counter(pages)/string(), page-break-before, page-break-after, page-break-inside (avoid), orphans, widows, string-set, bookmark-level, bookmark-label.
Colors: named (148 CSS keywords), #RGB, #RRGGBB, #RGBA, #RRGGBBAA, rgb(), rgba(), hsl(), hsla(), cmyk(), device-cmyk().
Values: px, pt, em, rem, %, mm, cm, in, calc(), min(), max(), clamp().
@-rules: @page, @font-face, @media print, @supports.
Selectors: type, .class, #id, *, descendant, child (>), adjacent (+), general sibling (~), [attr], [attr=val], [attr^=], [attr$=], [attr*=], [attr~=], [attr|=], :first-child, :last-child, :nth-child(), :nth-of-type(), :nth-last-child(), :nth-last-of-type(), :first-of-type, :last-of-type, :root, :not(), :is(), :where(), ::before, ::after, ::marker.
CSS custom properties (variables) via var() with fallback values.
CSS counters via counter-reset, counter-increment, counter().
Not Supported ¶
Interactive pseudo-classes (:hover, :focus, :active) — not applicable to static PDF. @media queries beyond print. Vendor prefixes. @import (use inline <style> or Options.ExternalCSS). :has() selector. CSS animations, transitions. clip-path, mask. Vertical writing modes. ::first-line, ::first-letter pseudo-elements.
Loading local assets ¶
Local references (images, fonts, linked stylesheets, background-image url()) resolve through Options.BaseFS — an os.DirFS, embed.FS, or fstest.MapFS; when nil, local references fail and assets must be inlined as data: URIs. Set Options.FallbackFontPath for glyphs outside WinAnsiEncoding.
A failed asset load is logged (Options.Logger) and skipped by default, so broken paths silently degrade output. Set Options.StrictAssets to return those failures as an error (with the partial result) — use it in dev and CI.
Feeding the result into a document ¶
Prefer github.com/carlos7ags/folio/document.Document.AddHTML, which wires the whole conversion into a document in one call. Use ConvertFull only to inspect the raw ConvertResult first, then pass it to github.com/carlos7ags/folio/document.Document.AddConvertResult — adding result.Elements by hand drops result.Absolutes and the @page configuration.
Index ¶
- Variables
- func Convert(htmlStr string, opts *Options) ([]layout.Element, error)
- func ConvertWithContext(ctx context.Context, htmlStr string, opts *Options) ([]layout.Element, error)
- func DenyInternalHosts(rawURL string) error
- func ParseCSSLength(s string, fontSize, relativeTo float64) float64
- func RenderCSSPropertiesMarkdown() string
- type AbsoluteItem
- type AssetError
- type ConvertResult
- type DocMetadata
- type LimitError
- type LimitKind
- type MarginBoxContent
- type Options
- type PageConfig
- type PageMargins
- type ParseError
- type URLPolicy
Constants ¶
This section is empty.
Variables ¶
var ErrAbsolutePathDenied = errors.New("html: absolute filesystem path denied (set Options.AllowAbsolutePaths)")
ErrAbsolutePathDenied is returned when the document references an absolute filesystem path but Options.AllowAbsolutePaths is false. Programmatic paths (Options.FallbackFontPath, system-font search) are not affected. Reported normally, like ErrRemoteFetchDisabled. Use with errors.Is.
var ErrAssetBudgetExceeded = errors.New("html: total asset byte budget exceeded")
ErrAssetBudgetExceeded is returned when a conversion's aggregate asset read size crosses Options.MaxTotalAssetBytes. The offending load and any later ones fail with it. Reported normally (logged, and surfaced under StrictAssets). Use with errors.Is.
var ErrRemoteFetchDisabled = errors.New("html: remote fetch disabled (set Options.AllowRemoteFetch)")
ErrRemoteFetchDisabled is returned when the document references an http(s) asset but Options.AllowRemoteFetch is false. Unlike an ErrURLPolicyDenied, it is reported normally — logged via Options.Logger and, under Options.StrictAssets, added to the joined return-error — so callers discover why the asset did not load. Use with errors.Is.
var ErrURLPolicyDenied = errors.New("html: URL fetch blocked by URLPolicy")
ErrURLPolicyDenied wraps a URLPolicy rejection so that asset-loading code paths can distinguish a policy decision (the caller's intent) from a network or filesystem failure. When Options.StrictAssets is true, errors matching ErrURLPolicyDenied are still logged via Options.Logger but are not added to the joined return-error — the caller already received the signal they wired URLPolicy to produce. Use with errors.Is to test the cause.
Functions ¶
func Convert ¶
Convert parses an HTML string and returns a slice of layout elements suitable for passing to a layout.Renderer. Only a subset of HTML is supported — see package documentation for details. It is equivalent to ConvertWithContext with a background context.
func ConvertWithContext ¶ added in v0.9.0
func ConvertWithContext(ctx context.Context, htmlStr string, opts *Options) ([]layout.Element, error)
ConvertWithContext is the context-aware variant of Convert. It checks ctx at element boundaries while walking the HTML tree and returns ctx.Err() if the context is done.
func DenyInternalHosts ¶ added in v0.10.0
DenyInternalHosts is a URLPolicy that blocks non-http(s) schemes and targets that resolve to loopback, private (RFC1918 / ULA), link-local, unspecified, or multicast addresses. It is the default policy applied when AllowRemoteFetch is true and Options.URLPolicy is nil, and it is re-checked on every redirect hop. Callers may also set it explicitly.
For a DNS name, every resolved address is checked; the fetch is denied if any resolves to an internal address. This leaves a narrow TOCTOU window (the http client re-resolves at dial time); closing it fully would require a dial-time guard, tracked as a follow-up.
func ParseCSSLength ¶ added in v0.6.1
ParseCSSLength converts a CSS length string to PDF points. Supported units: px, pt, em, rem, %, mm, cm, in. Also supports calc(), min(), max(), clamp() expressions.
fontSize is used to resolve em units. rem assumes a 16px (12pt) root font size. relativeTo is used for percentage values. Returns 0 for unparseable or empty values.
ParseCSSLength("1in", 12, 0) // 72.0
ParseCSSLength("25.4mm", 12, 0) // 72.0
ParseCSSLength("16px", 12, 0) // 12.0 (16 * 0.75)
ParseCSSLength("2em", 12, 0) // 24.0
ParseCSSLength("50%", 12, 200) // 100.0
func RenderCSSPropertiesMarkdown ¶ added in v0.8.0
func RenderCSSPropertiesMarkdown() string
RenderCSSPropertiesMarkdown produces the contents of docs/CSS_SUPPORT.md from the cssProperties registry. The output is grouped by Category in a fixed order, then alphabetized within each category. Properties in the registry are the ground truth — any change to cssProperties regenerates the doc on the next `go generate`.
The function is exported so that internal/gen-css-docs/main.go can invoke it without importing unexported internals. It is otherwise not part of Folio's public API contract — callers outside the doc generator should not rely on its output format.
Types ¶
type AbsoluteItem ¶
type AbsoluteItem struct {
Element layout.Element
X, Y float64 // X from left edge, Y from top in PDF coordinates (bottom-left origin)
Width float64
Fixed bool // position:fixed (render on every page)
RightAligned bool // true when positioned with CSS right (X is right-edge offset)
ZIndex int // z-index: negative = render behind normal flow
}
AbsoluteItem represents an element removed from normal flow via position:absolute or position:fixed.
type AssetError ¶ added in v0.9.0
type AssetError struct {
// Category labels the reference site, e.g. "image" or "@font-face".
Category string
// Ref is the offending src/href/url/path, or "" when not available.
Ref string
// Err is the underlying load failure.
Err error
// contains filtered or unexported fields
}
AssetError indicates a referenced asset failed to load during conversion. It is the typed form of the failures collected when Options.StrictAssets is set; the joined error returned by Convert / ConvertFull contains one AssetError per failed reference, discoverable with errors.As.
Category is a short label for the reference site ("image", "@font-face", "background-image", "stylesheet", "SVG image", "FallbackFontPath"). Ref is the offending URL or path when one is known. Err is the underlying cause, exposed via Unwrap so errors.Is keeps working (e.g. against fs.ErrNotExist or ErrURLPolicyDenied).
func (*AssetError) Error ¶ added in v0.9.0
func (e *AssetError) Error() string
func (*AssetError) Unwrap ¶ added in v0.9.0
func (e *AssetError) Unwrap() error
Unwrap returns the underlying load failure so callers can errors.Is against fs.ErrNotExist, ErrURLPolicyDenied, network errors, etc.
type ConvertResult ¶
type ConvertResult struct {
Elements []layout.Element
Absolutes []AbsoluteItem
PageConfig *PageConfig // page settings from @page rules (nil if none)
Metadata DocMetadata // extracted from <title> and <meta> tags
// MarginBoxes are ready-to-use margin box definitions from @page rules
// (e.g. page numbers via @bottom-center). Pass directly to
// document.SetMarginBoxes. Nil if no margin boxes were declared.
MarginBoxes map[string]layout.MarginBox
// FirstMarginBoxes are margin boxes for @page :first only.
// Pass to document.SetFirstMarginBoxes. Nil if not declared.
FirstMarginBoxes map[string]layout.MarginBox
// LeftMarginBoxes are margin boxes for @page :left (even pages, LTR).
// Pass to document.SetLeftMarginBoxes. Nil if not declared.
LeftMarginBoxes map[string]layout.MarginBox
// RightMarginBoxes are margin boxes for @page :right (odd pages, LTR).
// Pass to document.SetRightMarginBoxes. Nil if not declared.
RightMarginBoxes map[string]layout.MarginBox
}
ConvertResult holds the full result of an HTML → layout conversion, including both normal-flow elements and absolutely positioned items.
func ConvertFull ¶
func ConvertFull(htmlStr string, opts *Options) (*ConvertResult, error)
ConvertFull parses an HTML string and returns both normal-flow elements and absolutely positioned items. It is equivalent to ConvertFullWithContext with a background context.
func ConvertFullWithContext ¶ added in v0.9.0
func ConvertFullWithContext(ctx context.Context, htmlStr string, opts *Options) (*ConvertResult, error)
ConvertFullWithContext is the context-aware variant of ConvertFull. It checks ctx at element boundaries while walking the HTML tree and returns ctx.Err() (context.Canceled or context.DeadlineExceeded) if the context is done, letting callers bound the conversion of pathological input with a deadline or cancellation. A nil result is returned on cancellation.
type DocMetadata ¶
type DocMetadata struct {
Title string // from <title>
Author string // from <meta name="author">
Description string // from <meta name="description">
Keywords string // from <meta name="keywords">
Creator string // from <meta name="generator">
Subject string // from <meta name="subject">
// Language is the BCP-47 tag from <html lang="..."> when present
// (e.g. "zh-CN", "ja", "en-US"). It is currently consumed by the
// @font-face loader to select the appropriate face from pan-CJK
// TTCs via font.ParseFontForLanguage — a document declaring
// lang="zh-CN" with a NotoSansCJK-Regular.ttc loads the SC face
// instead of the JP face-0 default. Per-element lang attributes
// (<p lang="ja">) are NOT yet honoured; the property is currently
// document-level only (issue #280, deferred Phase 2).
Language string
}
DocMetadata holds document metadata extracted from HTML head elements.
type LimitError ¶ added in v0.9.0
type LimitError struct {
// Kind is the ceiling that was crossed.
Kind LimitKind
// Limit is the configured maximum (the value of MaxElements or MaxDepth).
Limit int
}
LimitError indicates conversion was aborted because a configured resource ceiling (Options.MaxElements or Options.MaxDepth) was crossed. It is a terminal, input-side fault with no wrapped cause: the conversion stops and returns this error instead of continuing to allocate, so a very large or deeply-nested (e.g. programmatically-expanded) template cannot exhaust memory or the goroutine stack. Test for it with errors.As(err, new(*html.LimitError)).
func (*LimitError) Error ¶ added in v0.9.0
func (e *LimitError) Error() string
type LimitKind ¶ added in v0.9.0
type LimitKind int
LimitKind identifies which resource ceiling a LimitError reports.
const ( // LimitElements reports that Options.MaxElements was exceeded — the // input produced more layout elements than the configured budget. LimitElements LimitKind = iota // LimitDepth reports that Options.MaxDepth was exceeded — the input // nested elements more deeply than the configured budget. LimitDepth )
type MarginBoxContent ¶
type MarginBoxContent struct {
Content string // resolved content string (after evaluating counter(), string literals, etc.)
// HasContent is true when a `content` declaration was present in the
// margin-box rule, even if it resolved to the empty string (e.g.
// `content: ""` or `content: none`). It lets a pseudo-page box
// (@page :first { @bottom-center { content: "" } }) be preserved so it
// can OVERRIDE — and thereby blank — the inherited default box for that
// page/slot, instead of being dropped and falling back to the default.
HasContent bool
FontSize float64 // font size in points (0 = use default 9pt)
Color [3]float64 // RGB color (0-1 each)
// HasColor is true only when a `color` declaration was present in the
// margin-box rule. It lets the renderer distinguish an explicit
// `color: black` from an unset color (which defaults to gray).
HasColor bool
// FontStyle is the parsed font-style ("italic" or "normal"). Empty
// when the margin box declared none, in which case the box falls
// back to plain (non-italic) rather than inheriting <body>'s style —
// symmetric with how FontSize/Color already default rather than
// inherit.
FontStyle string
// FontWeight is the CSS Fonts L4 numeric weight (100-900). 0 means
// the margin box declared none (treated as 400).
FontWeight int
// FontFamily is the parsed font-family (lowercased, quotes/first-of-
// list stripped, see parseFontFamily). Empty when the margin box
// declared none.
FontFamily string
// Font is the resolved standard PDF font used when Embedded is nil,
// computed in resolveMarginBoxFont from FontStyle/FontWeight/
// FontFamily. nil until that resolution runs.
Font *font.Standard
// Embedded is the document's default body font, stamped during
// conversion so the renderer can draw the margin box with an embedded
// (PDF/A-safe) font instead of the non-embedded standard Helvetica.
// Nil when the document uses no embedded fonts, or when the box's own
// font-style/font-weight/font-family resolves to a standard font
// instead (see resolveMarginBoxFont).
Embedded *font.EmbeddedFont
}
MarginBoxContent holds the parsed content of a CSS margin box (e.g. @top-center).
type Options ¶
type Options struct {
// DefaultFontSize is the root font size in points (default 12).
DefaultFontSize float64
// BaseFS resolves all local paths referenced by the document: images,
// fonts, linked stylesheets, background-image url(), and FallbackFontPath.
// Pass embed.FS for embedded assets, os.DirFS(dir) or (*os.Root).FS() for
// sandboxed directory access, fstest.MapFS in tests.
// Paths are normalised to fs.FS conventions: forward slashes only, no
// leading slash, no ".." traversal — invalid paths are rejected before
// the read. A leading "/" in src/href is treated as web-style root and
// stripped (resolved from the BaseFS root). When BaseFS is nil, every
// local-asset reference fails — the document is expected to inline its
// assets via data: URIs.
BaseFS fs.FS
// PageWidth is the page width in points (default 612 = US Letter).
PageWidth float64
// PageHeight is the page height in points (default 792 = US Letter).
PageHeight float64
// FallbackFontPath is a Unicode-capable TTF/OTF font used when text
// contains characters outside WinAnsiEncoding (e.g. CJK, emoji). When
// BaseFS is set, the path is resolved through it first; otherwise the
// converter searches common system font locations.
FallbackFontPath string
// URLPolicy is called before the converter fetches a remote URL
// (for <img src="http://...">, background-image: url(), etc.), and
// again for each redirect hop. Return nil to allow the fetch, or an
// error to block it. Only consulted when AllowRemoteFetch is true.
// If nil while AllowRemoteFetch is true, the built-in DenyInternalHosts
// policy is used; set URLPolicy to a function that always returns nil
// to allow every host.
URLPolicy URLPolicy
// AllowRemoteFetch enables fetching http(s) assets referenced by the
// document (<img src="http://...">, background-image: url(http://...),
// linked stylesheets, @font-face url(http://...)). Default false: no
// network request is made and such references fail with
// ErrRemoteFetchDisabled (logged, and surfaced under StrictAssets).
// When true, every fetch is filtered by URLPolicy; if URLPolicy is nil,
// the built-in DenyInternalHosts policy is applied, which blocks
// loopback, RFC1918, link-local, and non-http(s) targets and is
// re-checked on every redirect hop.
AllowRemoteFetch bool
// AllowAbsolutePaths enables reading absolute filesystem paths named in
// document content (<img src="/etc/..."> or @font-face url('/abs/...'))
// when BaseFS is nil. Default false: such references fail with
// ErrAbsolutePathDenied. When true, the read is capped at the same byte
// limit as the HTTP path. This does NOT affect Options.FallbackFontPath
// or the built-in system-font search, which load programmatic absolute
// paths through a separate trusted code path.
AllowAbsolutePaths bool
// Client is the HTTP client used to fetch remote images and stylesheets.
// If nil, http.DefaultClient is used.
Client *http.Client
// Logger receives warn-level events when an asset fails to load: missing
// fonts in @font-face, unreadable linked stylesheets, image fetch errors
// that fall back to alt text. If nil, these events are dropped.
Logger *slog.Logger
// StrictAssets promotes asset-load failures from warn-and-continue to
// returned errors. When true, Convert and ConvertFull collect every
// failed @font-face url(), <img>, background-image, linked stylesheet,
// SVG load, and FallbackFontPath, then return them joined via
// errors.Join at the end of the conversion. The partial result (the
// elements that did render) is returned alongside the error so callers
// can inspect both. Errors are returned in document order: linked
// stylesheets first, then @font-face rules, then asset references in
// tree-walk order — stable across runs given byte-identical input.
//
// URLPolicy denials are wrapped with ErrURLPolicyDenied and excluded
// from the joined error, since they represent the caller's intent
// (the policy callback already returned the signal it was wired to
// produce) rather than a load failure. The denial is still logged
// through Options.Logger.
//
// When false (default), every asset failure is logged through Logger
// (if set) and the conversion continues. This suits production where
// missing assets should not abort a render. Use StrictAssets in
// development and CI to surface broken paths in the local feedback
// loop instead of letting them silently degrade the output.
StrictAssets bool
// MaxElements caps the number of HTML nodes converted into layout
// elements. 0 (the default) means unlimited. It guards against
// resource exhaustion from very large or programmatically-expanded
// input (e.g. a small template rendered against a huge dataset): once
// the cap is crossed, Convert/ConvertFull stop walking the tree and
// return a *LimitError (Kind LimitElements) instead of continuing to
// allocate. Recommended for any path that converts untrusted HTML.
MaxElements int
// MaxDepth caps the nesting depth of converted elements. 0 (the
// default) means unlimited. It guards against pathologically nested
// input that would otherwise grow the conversion recursion (and the
// goroutine stack) without bound. Exceeding it returns a *LimitError
// (Kind LimitDepth).
MaxDepth int
// MaxTotalAssetBytes caps the aggregate bytes read across every asset
// loaded during one conversion (images, fonts, linked stylesheets —
// remote, BaseFS-relative, and absolute alike). 0 selects a generous
// default (512 MiB) that comfortably fits realistic documents with
// several embedded fonts and images while bounding the worst case,
// where many references at the per-asset limit would otherwise
// multiply into unbounded memory. Once the running total is crossed,
// the offending and any later asset loads fail with
// ErrAssetBudgetExceeded (logged, and surfaced under StrictAssets).
// Set a large value to effectively disable, or a small one to tightly
// bound untrusted input.
MaxTotalAssetBytes int64
}
Options configures the HTML → layout.Element conversion.
type PageConfig ¶
type PageConfig struct {
Width float64 // page width in points (0 = use default)
Height float64 // page height in points (0 = use default)
AutoHeight bool // true when @page size has explicit height of 0 (size to content)
Landscape bool
// OrientationOnly is true when @page { size: ... } gave only an
// orientation keyword (landscape/portrait) with no named size or
// explicit dimensions. Width/Height are then 0 and the orientation
// must be applied to the document default page size at apply time.
// Landscape distinguishes the two keywords (true = landscape).
OrientationOnly bool
// Default margins (from @page with no pseudo-selector).
MarginTop float64
MarginRight float64
MarginBottom float64
MarginLeft float64
HasMargins bool // true if any margin property was explicitly set (even to 0)
// Per-page-type margin overrides (nil = use default).
First *PageMargins // @page :first
Left *PageMargins // @page :left (even pages in LTR)
Right *PageMargins // @page :right (odd pages in LTR)
// Default margin boxes (from @page with no pseudo-selector).
MarginBoxes map[string]MarginBoxContent // e.g. "top-center" → content
// contains filtered or unexported fields
}
PageConfig holds page dimensions and margins from CSS @page rules.
func (*PageConfig) Resolve ¶ added in v0.9.1
func (pc *PageConfig) Resolve(defaultW, defaultH float64) (width, height float64, autoHeight bool)
Resolve computes the final page geometry for this @page config and resolves all margin lengths (default + :first / :left / :right) against that geometry. It is the single entry point every Document-building consumer must call so that page sizing, the orientation-only swap, and deferred percent / calc margin resolution behave identically across all code paths (AddHTML, the C ABI, WASM, the tmpl package, and examples).
defaultW / defaultH are the document's default page dimensions in points, used when the @page rule supplied no explicit size (or only an orientation keyword). The returned width / height are the final page dimensions; autoHeight reports the CSS `size: <w> 0` content-sized case (height is then 0). Margins are resolved in place on pc and read by the caller from pc.MarginTop/… and pc.First/Left/Right after this returns.
Precedence (S-1): an orientation-only keyword (size: landscape | portrait) rotates whatever size is otherwise in effect — the explicit @page dims if given, else the document default — rather than being ignored when explicit dims exist.
func (*PageConfig) ResolveMargins ¶ added in v0.9.1
func (pc *PageConfig) ResolveMargins(pageW, pageH float64)
ResolveMargins resolves the default-margin deferred lengths against the page box, then resolves any per-page-type variant overrides (:first, :left, :right). See PageMargins.ResolveMargins for the percent basis rules. pageW / pageH are the resolved page dimensions in points (the @page size if given, otherwise the document default).
type PageMargins ¶
type PageMargins struct {
Top, Right, Bottom, Left float64
HasMargins bool // true if any margin property was explicitly set (even to 0)
MarginBoxes map[string]MarginBoxContent // e.g. "top-center" → content
// contains filtered or unexported fields
}
PageMargins holds the margin values and margin-box content for a page variant (e.g. :first, :left, :right) parsed from a CSS @page rule.
func (*PageMargins) ResolveMargins ¶ added in v0.9.1
func (m *PageMargins) ResolveMargins(pageW, pageH float64)
ResolveMargins resolves any deferred (percent / calc) margin lengths against the page box. Per CSS Paged Media, @page margin percentages resolve against the page dimensions: left/right against pageW, top/bottom against pageH. Sides without a deferred length keep their eagerly resolved float value.
type ParseError ¶ added in v0.9.0
type ParseError struct {
// Err is the underlying parser error.
Err error
}
ParseError indicates the input HTML could not be parsed into a document tree. It wraps the underlying parser error.
Folio's HTML parsing is lenient — malformed markup is recovered rather than rejected — so this is rare in practice. It exists to give callers a typed signal that the failure originated in the input, distinct from an internal fault. Test for it with errors.As(err, new(*html.ParseError)).
func (*ParseError) Error ¶ added in v0.9.0
func (e *ParseError) Error() string
func (*ParseError) Unwrap ¶ added in v0.9.0
func (e *ParseError) Unwrap() error
Unwrap returns the underlying parser error so errors.Is / errors.As can inspect the cause.
Source Files
¶
- bookmark.go
- converter.go
- converter_assets.go
- converter_block.go
- converter_dispatch.go
- converter_flex.go
- converter_fonts.go
- converter_forms.go
- converter_heading.go
- converter_helpers.go
- converter_image.go
- converter_link.go
- converter_list.go
- converter_paragraph.go
- converter_style.go
- converter_style_parsers.go
- converter_table.go
- css.go
- css_props.go
- css_props_doc.go
- css_selectors.go
- doc.go
- errors.go
- fetch_image.go
- grid.go
- length.go
- page.go
- properties.go
- style.go